create a log file using powershell
85,475
# 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
}
Author by
Vysakh
Updated on September 18, 2022Comments
-
Vysakh over 1 year
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
-
TheUser1024 almost 11 yearsDoes the folder already exist? I can only reproduce your error by pointing it to a folder that does not exist.
-
Vysakh almost 11 years@TheUser1024: No..It should be created @ runtime..
-
TheUser1024 almost 11 yearsThen create it beforehand in code. Just make sure Out-File has that folder available to write to when it runs.
-
Vysakh almost 11 years@TheUser1024: But when it is run 2nd time, I assume an exception will occur..How can I handle that then?
-
Vysakh almost 11 yearsGot the answer..The main point is from TheUser1024 only. From that point I built up the solution..Thanks TheUser1024...
-
TheUser1024 almost 11 yearsYeah, you gotta check if it exists already, but seems you figured it out. You're welcome
-
Karan almost 11 years@Vysakh: If you've solved your own problem we encourage you to post a self-answer below (you can even self-accept).
-
-
genuinefafa over 3 yearsi think line 7 has wrong directory, right? should be
C:\PSLogs