create a log file using powershell

6

1

How can I create a log file using powershell?

I am using this code for log file creation.

#  Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
#  Log file name:
$LogFile = 'C:\PSLogs\'+"LOG_"+$LogTime+".log"

if(---)
{
    ----
    ----
   "done" | Out-File $LogFile -Append -Force
}
else
{
  "Unlucky!!" | Out-File $LogFile -Append -Force
}

But it's showing me an error like

Out-File : Could not find a part of the path

Vysakh

Posted 2013-06-19T09:08:13.903

Reputation: 178

Does the folder already exist? I can only reproduce your error by pointing it to a folder that does not exist. – TheUser1024 – 2013-06-19T09:35:02.877

@TheUser1024: No..It should be created @ runtime.. – Vysakh – 2013-06-19T09:37:49.957

Then create it beforehand in code. Just make sure Out-File has that folder available to write to when it runs. – TheUser1024 – 2013-06-19T09:42:06.880

@TheUser1024: But when it is run 2nd time, I assume an exception will occur..How can I handle that then? – Vysakh – 2013-06-19T09:46:09.310

Got the answer..The main point is from TheUser1024 only. From that point I built up the solution..Thanks TheUser1024... – Vysakh – 2013-06-19T09:54:27.357

Yeah, you gotta check if it exists already, but seems you figured it out. You're welcome – TheUser1024 – 2013-06-19T10:07:04.007

@Vysakh: If you've solved your own problem we encourage you to post a self-answer below (you can even self-accept). – Karan – 2013-06-19T16:29:33.897

Answers

5

#  Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
[xml] $var = Get-Content D:\ScriptMgr\Sample.xml
$ser = read-host "Enter the centre:"

#  Log file name:
$path = "C:\Logs\"

if([IO.Directory]::Exists($path))
{
    #Do Nothing!!
}
else
{
    New-Item -ItemType directory -Path C:\PSLogs
}

$LogFile = 'C:\PSLogs\'+$ser+$LogTime+".html"
if (($sea=$var.detail.centre | where {$_.name -eq $ser}) -ne $null)
{
    Write-Host "center:" $sea.name
    Write-Host "Servername:" $sea.servername
    Write-Host "ip:" $sea.ip
    Write-Host "Username:" $sea.uname
    Write-Host "Password:" $sea.pwd
    Write-Host "Database:" $sea.dbname
    "$LogTime Found" | Out-File $LogFile -Append -Force
}
else
{
    write-host "not listed!!!"
    "$LogTime Not Found" | Out-File $LogFile -Append -Force
}

Vysakh

Posted 2013-06-19T09:08:13.903

Reputation: 178