Send Console Output to File in Windows PowerShell


How to send console output to a file in Windows PowerShell?



You can use the "Out-File" cmdlet to send console output into a file in Windows PowerShell.

The "Out-File" cmdlet sends output to a file. You can use this cmdlet instead of the redirection operator (>) with more controlling parameters.

For example, this command also sends a list of processes to the Process.txt file, but it uses the NoClobber parameter, which prevents an existing file from being overwritten.

PS C:\fyicenter> get-process | out-file process.txt -noclobber

Note that, Both "Out-File" and "Put-Content" cmdlets are saving data into a file. But they take input differently. If you put them in the command pipeline, they behave differently.

For example, the following same script shows the difference between "Out-File" and "Put-Content" cmdlets:

"`n--- First 5 lines of the console output ---"
Get-Process | Out-File temp.txt
Get-Content -First 5 temp.txt

"`n--- First 5 objects  ---"
Get-Process | Set-Content temp.txt
Get-Content -First 5 temp.txt

If you run the script, you will get:

PS C:\fyicenter> .\Test.ps1

--- First 5 lines of the console output ---

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    123       6     3668       1324    38             480 AgtAdmSvc
    252      10    49384       6400   243            2024 bndaemon

--- First 5 objects  ---
System.Diagnostics.Process (AgtAdmSvc)
System.Diagnostics.Process (bndaemon)
System.Diagnostics.Process (CcmExec)
System.Diagnostics.Process (CmRcService)
System.Diagnostics.Process (conhost)

Another way to remember the behavior of the "Out-File" cmdlet is to think of "Out-File" as the command line redirection operator (>) or (>>). Take a look at the following identical commands:

# 2 identical commands
... > output.txt
... | Out-File output.txt

# 2 identical commands
... >> output.txt
... | Out-File output.txt -Append


Work with File System in Windows PowerShell

⇒⇒Windows PowerShell Tutorials

2016-10-20, 396👍, 0💬