Using the Output

When we write a little script like a logger it would be nice if we could save the output to a file instead of watching our PowerShell window. This page will handle the output in PowerShell.

Out cmdlets

First of all we need to know what commands (cmdlets) we can use to output something. There are a few cmdlets available for us in PowerShell.

This list below shows the available cmdlets:

CommandType     Name
-----------     ----
Cmdlet          Out-Default
Cmdlet          Out-File
Cmdlet          Out-Host
Cmdlet          Out-Null
Cmdlet          Out-Printer
Cmdlet          Out-String
		

If you want to see what you can use just type in your PowerShell Out- and press TAB a few times.

To see the cmdlets in a list like my example we look in the PowerShell help files (Get-Help command). We simply ask helpfiles for everything that begins with Out and by typing * we don't care what the next characters will be, it just need to start with Out.

Try it yourself:

PS C:\PwrShell.net> Get-Command Out*
or
PS C:\PwrShell.net> Get-Command Out-*
		

Writing to a file

When we want to write the content of a simple variable to a file we can do it like this:

PS C:\PwrShell.net> $strMyText = "Hello I will be in a text file soon"
PS C:\PwrShell.net> $strMyText | Out-File hello.txt
		

It is also possible to use > :

PS C:\PwrShell.net> $strMyText = "Hello I will be in a text file soon"
PS C:\PwrShell.net> $strMyText > hello2.txt
		

When we want to output script results to a text file we need to use > :

PS C:\PwrShell.net> .\myScript.ps1 > results.txt
		

"." is the current directory so we look for the script called "myScript.ps1" in the current directory. The current directory is where the prompt (PS C:\PwrShell.net>) is in our case it is C:\PwrShell.net.

Writing to an HTML file

In PowerShell it is possible to convert your output to an HTML file. We can do this in our example by pipelining our results to ConvertTo-Html.

Just look how we use properties, ConvertTo-Html and our pipeline (|) here.

PS C:\PwrShell.net> $myProcesses = Get-Process
PS C:\PwrShell.net> $myProcesses | ConvertTo-Html -property Name, Path, Company > processList.html
		

Writing to a CSV file

Special with CSV is that we use Select-Object and the Export-Csv cmdlet.

PS C:\PwrShell.net> $myProcesses = Get-Process
PS C:\PwrShell.net> $myProcesses | Select-Object Name, Path, Company | Export-Csv -path myCSVList.csv