Export powershell file to text file

I have a foreach loop inside my powershell script with prints $ outputs on the shell during each iteration. There are many many outputs, and the number of entries displayed by the shell is limited. I want to export the output to a text file. I know how to do this on the command line. How is this possible in powershell?

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

powershell c:\test.ps1 c:\log.log 
+5
source share
2 answers

You can always redirect exe output to such a file (even from cmd.exe):

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

PowerShell , , , , , , :

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

, script , . OTOH, , . - Write-Host , , script. , Write-Host .

, 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
+12

"tee"

C:\ipconfig | tee C:\log.txt
+4

All Articles