Home > Blockchain >  How to redirect output from Powershell command to a text file
How to redirect output from Powershell command to a text file

Time:12-24

I'm trying to send a powershell output command to a text file. I need to add others output commands on one line when I execute a command.

In particular, I want send the output of this command:

Copy-Item -Verbose [fileName] -destination [path]

I tried to use:

$file = Copy-Item -Verbose [fileName] -destination [path]

add-Content $file [path] reportFile.txt

but the txt file is blank.

is it possibile to save the output of command "DETAILED: Execution of the "Copy file" to the destination etc...?

CodePudding user response:

Redirect the Verbose output stream to the log file.

PS C:\src\t> Copy-Item -Verbose .\zzz-.txt -Destination C:\src 4>.\zzz-result.txt
PS C:\src\t> type .\zzz-result.txt
Performing the operation "Copy File" on target "Item: C:\src\t\zzz-.txt Destination: C:\src\zzz-.txt".

CodePudding user response:

Read about_Redirection

If you want to redirect All Streams (including Verbose), see example:

Example 4: Redirect all streams to a file

So, for your example, would be:

Copy-Item -Verbose [fileName] -destination [path] *> .\reportFile.txt

CodePudding user response:

The other answers have already covered the stream redirection, but you can also consider using a transcript to log everything. This is obviously useful if you want to log several commands.

Example:

> Start-Transcript -Path "reportFile.txt"
> Copy-Item -Verbose [fileName] -destination [path]
> Stop-Transcript

the file reportFile.txt will contain detailed information on what was executed, along with the output.

By using a transcript, you don't have to bother redirecting the output of every command; you just need to make sure the command is executed within the start and the stopping of the transcript.

  • Related