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 # | Description | Introduced in |
---|---|---|
1 | Success Stream | PowerShell 2.0 |
2 | Error Stream | PowerShell 2.0 |
3 | Warning Stream | PowerShell 3.0 |
4 | Verbose Stream | PowerShell 3.0 |
5 | Debug Stream | PowerShell 3.0 |
6 | Information Stream | PowerShell 5.0 |
* | All Streams | PowerShell 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