As other answers already pointed out, Write-Output
is the cmdlet that writes to the output stream, and can be used to redirect that output to a file. However, note its following trait which makes an important difference to Write-Host
when it's used inside functions:
Using Write-Output:
Function Get-SomeResult {
Write-Output "Some logging here"
return "My desired result"
}
Function Start-Something {
$result = Get-SomeResult
Write-Output "The result is: $result"
}
Start-Something >> "$PSScriptRoot\MyLog.log"
The log will be:
The result is: Some logging here My desired result
As you can see, the output has become part of the returned object $result
, which is likely unintended.
Using Write-Host:
Function Get-SomeResult {
Write-Host "Some logging here"
return "My desired result"
}
Function Start-Something {
$result = Get-SomeResult
Write-Host "The result is: $result"
}
Start-Something >> "$PSScriptRoot\MyLog.log"
The log will be, as expected:
Some logging here
The result is: My desired result
The returned object of the Get-SomeResult
function is therefore retaining the value that we meant to set.
Output to file function
One way to address this is to create a separate function such as the following, to avoid repeating the log path inside the script:
$script:logPath = "$PSScriptRoot\MyLog.log"
Function Write-Log {
param($Message)
Write-Output $Message >> $script:logPath
}
Function Get-SomeResult {
Write-Log "Some logging here"
return "My desired result"
}
Function Start-Something {
$result = Get-SomeResult
Write-Log "The result is: $result"
}
Start-Something
Our new Write-Log
can then be used just as Write-Output
but without that potentially unintended characteristic. It can be further extended for validation or replicating other parameters of Write-Output
, but this simple format may do for most use-cases.