Using Windows PowerShell as an IT Pro – Part 9
In my last post I wrapped up the format cmdlets. Now I will take a look at the output cmdlets.Windows PowerShell provides several cmdlets that let you control data output directly. These cmdlets share two important characteristics.
First, they generally transform data to some form of text. They do this because they output the data to system components that require text input. This means they need to represent the objects as text. Therefore, the text is formatted as you see it in the Windows PowerShell console window.
Second, these cmdlets use the Windows PowerShell verb Out because they send information out from Windows PowerShell to somewhere else. The Out-Host cmdlet is no exception: the host window display is outside of Windows PowerShell. This is important because when data is sent out of Windows PowerShell, it is actually removed. Because of this, any output cmdlets needs to be put at the end of the pipeline, otherwise the data is sent out of Windows PowerShell and any subsequent commands will have nothing to process.
The Output cmdlets are Out-Default, Out-File, Out-GridView, Out-Host, Out-Null, Out-Printer, and Out-String.
Output can be sent to a file by using the Out-File cmdlet. The following command line sends a list of services to the file C:\temp\serviceslist.txt:
Get-Service | Out-File -FilePath C:\temp\serviceslist.txt

The results of using the Out-File cmdlet may not be what you expect if you are used to traditional output redirection. You must be aware of the context in which the Out-File cmdlet operates to understand its behavior.
By default, the Out-File cmdlet creates a Unicode file. This is the best default in the long run, but it means that tools that expect ASCII files will not work correctly with the default output format. The Out-file formats file contents to look like console output, causing the output to be truncated just as it is in a console window in most circumstances.
The Out-Null cmdlet is designed to immediately discard any input it receives, which is useful for discarding unnecessary data obtained as a side-effect of running a command. When entering the following command (Graphic 22), the command results stating that the directory was created are not delivered.
New-Item -Path C:\ -Name test -Type Directory | Out-Null

The Out-Printer cmdlet routes the output to the specified printer. The Out-String cmdlet converts the objects that Windows PowerShell manages into an array of strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the stream parameter to direct Out-String to return one string at a time. This cmdlet lets you search and manipulate string output as you would in traditional shells when object manipulation is less convenient.
In my next post we will look at the Out-Gridview cmdlet.
No comments:
Post a Comment