Reputation: 43
I would like to record all my inputs and outputs of my Powershell script into a logfile. I've tried a function, but I have to write the function in each line. I have test it with a Start-transcript, I dont know, but I think its only for Errors, it doesn't work really good. It is possible, if I start my script to get a Log all lines?
for Example:
$u=rene
New-AdUser -Name $u ...
Write-Hoste "New User ist Create $u"
and in my log file should stand:
17.01.2018 13:00 $u=rene
17.01.2018 13:00 New-AdUser -Name $u ...
17.01.2018 13:00 Write-Hoste "New User ist Create $u"
... and everything else (for Example Errors)
Upvotes: 0
Views: 123
Reputation: 3350
If you want to log the entire script, then you could do something like this
@(
$u=rene
New-AdUser -Name $u ...
Write-Hoste "New User ist Create $u"
... Rest of your script
) | Out-file -FilePath \\PathToYourLogFile\Logfile.txt"
That is one way of doing it. One more way of doing it would be using the Start-Transcript
at the beginning of your script and ending your script with Stop-Transcript
cmdlet and redirecting the output to a text fie. See start-transcript and stop-transcript for details.
I found one example that will create a daily log for your script (if you run it multiple times a day it'll just append to what you have). The log will be in the same folder as your script and it'll clean out any logs older than 15 days.
$VerbosePreference = "Continue"
$LogPath = Split-Path $MyInvocation.MyCommand.Path
Get-ChildItem "$LogPath\*.log" | Where LastWriteTime -LT (Get-Date).AddDays(-15) | Remove-Item -Confirm:$false
$LogPathName = Join-Path -Path $LogPath -ChildPath "$($MyInvocation.MyCommand.Name)-$(Get-Date -Format 'MM-dd-yyyy').log"
Start-Transcript $LogPathName -Append
Then at the end of your script, just add
Stop-Transcript
Here is the link for the same.
If you want to log specific things then you could use Out-File
cmdlet at specific and desired places. Hope that helps!
Upvotes: 1