Thursday, July 21, 2011

Process-Pipeline

PowerShell allows you to pipe the results of one command into the next.  It doesn’t simply pass along the text output but sends the entire resulting .NET object.  This may be an array or IEnumerable collection of objects.

For example, Get-ChildItem *.txt will return a list of files in the current folder.  However what it’s actually  returning is a list of System.IO.FileInfo objects.  Typing Get-ChildItem *.txt | Remove-Item will cause it to pass along that list of objects to the Remove-Item cmdlet which will subsequently delete them.

That’s not so interesting because you could have simply typed Remove-Item *.txt (or Del *.txt).  But what if you wanted to delete only text files larger than 10KB?  Try this:

Get-ChildItem *.txt | Where-Object {$_.Length -gt 10000} | Remove-item
So what’s going on here?  First we’re taking the output of the Get-ChildItem *.txt cmdlet which returns an array of System.IO.FileInfo objects representing all of the text files and passing it to the Where-Object.  One of the possible arguments for the Where-Object (aliased as Where) is a script block.

The script block here is {$_.Length > 10000}.  What’s going on here is that the Where-Object cmdlet is passing each input object (i.e. each FileInfo object) into the script block.  The passed in object is represented in the script block as “$_”.  We’re then testing to see whether it’s Length property is greater than 10000 using the –gt greater than operator and returning only those that evaluate to true. (Yes, PowerShell doesn’t use the standard operator symbols we’re used to but that’s another blog entry).

Next along we’re passing along the resulting text files bigger than 10KB to Remove-Item and deleting them.  Note that since we’re dealing with standard .NET FileInfo objects we could have used any of it’s properties such as LastAccessTime or Attributes.

No comments:

Post a Comment