Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
    
Does the folder already exist? I can only reproduce your error by pointing it to a folder that does not exist. – TheUser1024 Jun 19 '13 at 9:35
    
@TheUser1024: No..It should be created @ runtime.. – Vysakh Jun 19 '13 at 9:37
    
Then create it beforehand in code. Just make sure Out-File has that folder available to write to when it runs. – TheUser1024 Jun 19 '13 at 9:42
    
@TheUser1024: But when it is run 2nd time, I assume an exception will occur..How can I handle that then? – Vysakh Jun 19 '13 at 9:46
    
Got the answer..The main point is from TheUser1024 only. From that point I built up the solution..Thanks TheUser1024... – Vysakh Jun 19 '13 at 9:54
up vote 3 down vote accepted
#  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
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.