Reputation: 53
I'm wanting to save each 'write-verbose' and 'write-warning' to a text/log file once the script has completed.
I have tried out-file within the loop and out of the loop with a var at the start, like items suggested here. How to dump the foreach loop output into a file in PowerShell?
edit: it would be handy to capture the outputs from the Measure-Command also.
But this didn't work for my script. Any help would be appreciated.
#initialisation
CLS
$ErrorActionPreference = 'Stop'
$VerbosePreference = "continue"
#Settings
$SubFolder = ".\_Orphan"
$FileListFile = ".\DirtoMove.csv"
#Retrieve List with folders to move from current folder.
Try { [Array]$FilesToMove = Get-Content $FileListFile }
Catch {Write-Warning "could not load $($FileListFile)"; Start-Sleep -S 3 ; Exit}
#If subfolder does not exist then create it.
If (!(Test-Path $SubFolder)) {
Try { New-Item $SubFolder -ItemType Directory | Out-Null}
Catch {Write-Warning "Could not create subfolder $($SubFolder)"; Start-Sleep -S 3 ; Exit}
}
Measure-Command{
#Try to moving the folders from the list to the the specified subfolder.
Foreach ($File in $FilesToMove) {
#If folder does not exist then skip.
If (!(Test-Path $File)) {
Write-Verbose "File $($File) Does not exist, skipping";
Continue
}
# Check if folder already exist in the sub folder.
If (Test-Path (Join-Path -Path $SubFolder -ChildPath $File)){
Write-Verbose "File $($File) exists already in the subfolder, skipping";
Continue
}
#try moving the folder.
Try {
$File | Move-Item -Destination $SubFolder;
Write-Verbose "File $($File) succesfully moved." ;
}
Catch {Write-Warning "Could not move file $($File), Skipping" ; Continue}
}
}
Write-Verbose "Script finished, waiting for 5 seconds before closing."
Start-Sleep -Seconds 5
Upvotes: 0
Views: 2686
Reputation: 31
Have a look at redirection. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-6
In this case, it's example 3 that would be appropriate for this.
When running your script, call it like this:
./Script.ps1 3>&1 4>&1 > C:\result.log
This redirects the warning stream (3>&1) and the verbose stream (4>&1) to the success stream which is then redirected to a file (> C:\result.log)
Upvotes: 1
Reputation: 4199
You can use Start-Transcript
at the very first line of your script , and Stop-Transcript
at the end. The entire thing that the script does will be logged automatically in a log file.
Upvotes: 0