Powershell Logging

Hello Powershell folks!

I am trying to export the powershell script logging and the log file will contains the name of the computer where the script will be running. I have tried this using start-Transcript but it omits the name of the computer in the file.
Maybe there is a better way to do it any recommendation and advice will be greatly appreciated.

# Start logging
$Computer = $env:computername
Start-Transcript -path "C:\Temp\$Computer_$((Get-Date).ToString('MMddyyyyhhmm')).txt" -NoClobber -IncludeInvocationHeader
$file = "C:\Temp\032520221151.txt" 
# If file does not exist, exit
if (!(Test-Path $file)) 
{
  Write-Output "File doesn't exist!"
} 

# Test if output file exist, if so delete it
else 
{
  Remove-Item $file
} 

And it looks like the Start-Transcript does not log the error. When I tested it with error, it was not showing up the log file. I would like to be able to see the error too.

I’m not a fan of Start-Transcript because it has a lot of useless info in it and it’s hard to read. I’d prefer something like this:

$Path = 'C:\Temp\{0}_{1}.csv' -f $env:COMPUTERNAME, $((Get-Date).ToString('yyyyMMdd_HHmm'))

$file = 'C:\Temp\032520221151.txt'
$Test = Test-Path -Path $file

$Result = 
[PSCustomObject]@{
    ComputerName = $env:COMPUTERNAME
    FileExists   = $Test
}

if ($Test) {
    Remove-Item $file
}

$Result | Export-Csv -Path $Path -NoTypeInformation

This way you have CSV file you could even re-import later on with PowerShell and create a report with it.

Errors will be written to another stream. I think it would be more professional anyway to handle errors with a proper error handling with a try catch block. :wink:

Thank you!
I will try that Try and Catch (sound like a game :upside_down_face:).

I like the way you format your script. You’re right the Start-Transcript lot of unneedy info.

I have noticed that you exported the results or output to a CSV file. That is interesting if it can be appended when run on multiple devices. I will steal that. :wink:

But what I would like it is just the logging.

The logging of what?

logging the script process like the Echo on for cmd. Maybe I am wrong.

But there is hardly anything to log in your script? Anyway, either use start-transcript or just output a status message before and after each step you want to log and write it to a log file.

But you should keep in mind that writing to a log file repeatedly will slow down your script considerably.

Okay, I see. That will be lot of work if the scrip becomes longer.
Now I know. This case can be closed. :slight_smile:
Thank you Olaf.