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 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 ?!
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 # | 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 |
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:
Post a Comment