Andre de Cavaignac

Let's blog it out...

PowerShell: Using Objects and Streams in your Command Prompt (Writing To Files)

PowerShell is really cool.  I've been using it alot recently and have found it to be an incredibly powerful too.  It blows away the Unix command line in flexibility and feature set; could this be a nail in the coffin of Unix?

One thing that I found incredibly interesting is the object-oriented approach of PowerShell.  One of the best samples I have come up with is writing to a stream using the shell and a variable.  Take a look at the example below:

  1. PS C:\> (new-item "helloworld.txt" -type file).AppendText() | set-variable a
  2. PS C:\> $a.WriteLine("Here is a list of all my processes")
  3. PS C:\> get-process | foreach-object { $a.WriteLine($_.ProcessName) }
  4. PS C:\> $a.Dispose()
  5. PS C:\> get-content "helloworld.txt"
    Here is a list of all my processes
    afscreds
    afsd_service
    afsdboot
    alg
    appmgrsvc
    [Truncated]
  6. PS C:\>

If you don't know much about PowerShell or .NET let me give a quick overview:  PowerShell commands return .NET objects that you can manipulate in a pipeline.  The pipeline works much like Unix, however piping objects gives you the added flexibility of getting all the properties and methods of those objects.

Line one on the code above calls New-Item to create a file.  Once created, a System.IO.FileInfo object will be passed down the pipeline.  I call AppendText on the FileInfo to open a StreamWriter, and lastly, save that into a variable "a".

You can see that I can use $a in my future statements, because the stream is open and in that variable.  When I'm done, I dispose it as normal, and get-content (equivelent to "type") of the file I created.  Cool!

Leave a Comment

(required) 

(required) 

(optional)

(required)