Let’s think about the following case, create a PowerShell Scripte to copy files from the C:\MySource to D:\MyDestination, also writing log file which write the console to a file. seems simple, yes but not in the way expected. In this post the focus will be on PowerShell Console redirection.

Trying with Out-File

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 results output to a file, 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 ?!

PowerShell Console Redirection

Console redirection can be achieved by using the asterisk and the greater than sign *> .But before trying it check this table about the things which can replace the asterisk

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

So by replacing the asterisk with the number 2, redirect only the output of errors to the file, is 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 comments or questions, leave them in the comment section below.

What Else To Read

Take a look in to An advanced way to know why AD account is locked-out

Rate this post