Redirection and Substitution


One common thing you'll need to do is redirect the output of one cmdlet into another cmdlet to tie the two together. You may also want to redirect cmdlet output to a file to create a report of some kind. For example, the following cmdlet can be used to create your own reference file of available cmdlets:

 PS C:\>Get-Command > commandref.txt 

This cmdlet gives you a file named Commandref.txt that contains the output of the Get-Command cmdlet. This file is located in the current location, as indicated by the PowerShell prompt.

Append Output

To append output to an existing file, rather than overwriting it, use >> instead of >.

You can use the output of one cmdlet as the input, or argument, to another cmdlet or language expression. The syntax is $(cmdlet), as shown in this example:

 PS C:\>Get-ChildItem $(Read-Host -Prompt "Enter file path/name: ") 

This can be a bit difficult to follow, so let's walk through it slowly: The first cmdlet is Get-ChildItem. This cmdlet is designed to accept a file path, and then display the child items-files and subfolders, usually-of that path. The Read-Host cmdlet is designed to read input from the command-line; its -Prompt argument defines a text prompt. So, this example displays the following:

 PS C:\> Get-ChildItem $(Read-Host -Prompt "Enter file path/name: ") Enter filename: : C:\ Directory: Microsoft.Management.Automation.Core\FileSystem::C:\ Mode                LastWriteTime     Length Name ----                -------------     ------ ---- -a---         1/10/2005   9:01 PM      15320 ArchiveLogs.wsf -a---          1/9/2005  10:07 PM          0 AUTOEXEC.BAT -a---         4/10/2006  10:12 AM         17 computers.txt -a---          1/9/2005  10:07 PM          0 CONFIG.SYS -a---         4/12/2006  11:47 AM        526 hpfr5550.xml d----         2/26/2006   5:21 PM            Documents and Settings d----          1/9/2005  10:32 PM            Inetpub d----          3/2/2006   1:29 PM            logs d----         4/17/2006  11:34 AM            Program Files d----         4/13/2006   1:31 PM            temp d----         4/13/2006   8:56 PM            WINDOWS 

The output of Read-Host-that is, whatever was typed at the prompt-is passed as the input argument to Get-ChildItem.

Other forms of substitution are possible. For example, the following can be used to create five files named 1, 2, 3, 4, and 5:

 PS C:\>New-Item -type file $(1..5) 

The New-Item cmdlets has an input argument of -Type, which accepts an item type (specified as file) and name. For the name, we used substitution, specifying that the values 1 through 5, inclusive, should be used. This causes the cmdlet to run once for each value we supplied, creating five new files.



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net