Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting powershell output to text file

I have a foreach loop inside my powershell script with prints $output on the shell during each iteration. There are lot many outputs and the number of entries that the shell can display is limited. I am looking to export the output to a text file. I know how to do it in command line. How is it possible in a powershell though?

FYI, I am using a batch script from the command line to run the powershell script as

powershell c:\test.ps1 c:\log.log 
like image 579
ssn Avatar asked Apr 26 '12 19:04

ssn


People also ask

How do I copy a PowerShell output?

Just select the text in the console window and press enter or the right mouse button. That selected text ends up in your clipboard. Note that this will only work if QuickEdit mode is enabled for the console window.

How do I Export PowerShell output from CSV?

Getting output in a CSV file using PowerShell To get the output of any command in a CSV file, the Export-CSV cmdlet is used. It saves the output as comma-separated values. Here, the Export-CSV command will fetch the output of the Data_object and save it as a CSV file at the specified Path.

How do I Export output from PowerShell to excel?

As of now, there is no built-in command like CSV (Export-CSV) to export output to the excel file but we can use the Out-File command to export data to excel or any other file format. Let's use Out-File to export the output of the Get-Processes command to an excel file.


2 Answers

You can always redirect the output an exe to a file like so (even from cmd.exe):

powershell c:\test.ps1 > c:\test.log

Within PowerShell, you can also redirect individual commands to file but in those cases you probably want to append to the log file rather than overwrite it e.g.:

$logFile = 'c:\temp\test.log'
"Executing script $($MyInvocation.MyCommand.Path)" > $logFile
foreach ($proc in Get-Process) {
    $proc.Name >> $logFile
}
"Another log message here" >> $logFile

As you can see, doing the redirection within the script is a bit of a pain because you have to do lots of redirects to file. OTOH, if you only want to redirect part of the output to file then you have more control this way. Another option is to use Write-Host to output info to the console meant for someone observing the results of the script execution. Note that Write-Host output cannot be redirected to file.

This is an example executed from CMD.exe

C:\Temp>type test.ps1
$OFS = ', '
"Output from $($MyInvocation.MyCommand.Path). Args are: $args"

C:\Temp>powershell.exe -file test.ps1 1 2 a b > test.log

C:\Temp>type test.log
Setting environment for using Microsoft Visual Studio 2008 Beta2 x64 tools.
Output from C:\Temp\test.ps1. Args are: 1, 2, a, b
like image 64
Keith Hill Avatar answered Sep 21 '22 23:09

Keith Hill


what about using the 'tee' command

C:\ipconfig | tee C:\log.txt
like image 33
rojomisin Avatar answered Sep 20 '22 23:09

rojomisin