Tuesday, July 21, 2020

Powershell: Dump the console output to a file (Output redirection)


Let's think about the following case, I want to copy files from the following directory C:\MySource to D:\MyDestination plus adding a log file about the operation using Powershell. 
The easy answer is using the following command 

copy-Item -Path C:\MySource -Destination D:\MyDestination -Recurse | Out-File -FilePath D:\MyDestination\CopyLog.txt

The line above will copy the files from C:\MySource to D:\MyDestination and use the Out-File to redirect the console output to a file (output redirection), but when opening the file... the file is totally empty, so where is the output.

Actually, if we remove the out-file and checked the console output from the copy command, the result will be empty too... so how can we write the log ?!





There is two way we can use to write a log, one will be a bit complex by creating a function that will do the copy and the log writing, but I won't use this approach as there is a much easier way to do it.

Output redirection can be achieved by using the asterisk and the greater than sign *> 
But before trying it check this wonderful table about the things which can replace the asterisk [Microsoft.com]

Stream #DescriptionIntroduced in
1Success StreamPowerShell 2.0
2Error StreamPowerShell 2.0
3Warning StreamPowerShell 3.0
4Verbose StreamPowerShell 3.0
5Debug StreamPowerShell 3.0
6Information StreamPowerShell 5.0
*All StreamsPowerShell 3.0
So by replacing the asterisk (*) with the appropriate number, we will get only the required stream. For example, if you want to get only the errors that occurred during the copy operation, the code will be like this
Copy-Item -Path C:\MySource -Destination D:\MyDestination -Recurse 2> D:\MyDestination\CopyLog.txt

The line above and by replacing the asterisk with the number 2, it will only redirect the output of errors to the file, which in my case, something similar to this:

Copy-Item : An item with the specified name D:\MyDestination\MySource already exists.
At line:1 char:1
+ Copy-Item -Path C:\MySource -Destination D:\MyDestination -Recurse 2> ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (D:\MyDestination\MySource:String) [Copy-Item], IOException
    + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.CopyItemCommand


Hope you find this informative.
If you have any comment or question, leave it in the comment section below 
Have a good day.
 

No comments: