0

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)

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

If i use Transcript, he writes only one log if he had a mistake, if I have created a new user without errors then he writes nothing in the log. The orginal Script is bigger and the its to many work to add on every line the out-file
That's because there is no error encountered if a user is created successfully. If you want that in the log too, you would need to add an extra custom message to your script. Something like, write-output "User created successfully!"
yes thats right, but i will a log that logs all from start to stop. All Messages from Creat or success to error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.