Eggins.com
Powershell, .Net, Visual Studio, Team Foundation Server, Windows Communication Foundation

Converting the results of a Cmdlet to a formatted string

There are times that you may want to store the results of a Cmdlet as a string instead of the usual collection of objects. This is handy to create a textual report.

The following command stores the contents of C:\Windows into a varialble.
  $Result = dir c:\windows

The $Result variable is a collection of System.IO.DirectoryInfo and System.IO.FileInfo objects as you will see by executing:
  $Result | Get-Member

Now if you try the following command, which tries to send that result to an email address using the Powershell Comunity Extensions Send-SmptEmail Cmdlet, this command does not work:
 send-smtpmail -smtpHost localhost -to receiver@abc123.com -from sender@abc123.com -Subject "Directory" -body $Report

It crashes with the Message:
  Send-SmtpMail : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Body'. Specified method is not supported.

How do you convert the $Result variable to a string? The following command converts it to a string.
  $Report | Out-String
 
So you can now email the results using:
  send-smtpmail -smtpHost localhost -to receiver@abc123.com -from sender@abc123.com -Subject "Directory" -body $($Report | Out-String)

You will get the string result in the same format as is displayed to you on the screen when you execute
  Dir C:\Windows


Posted Aug 17 2007, 12:00 PM by David
Filed under: , ,

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Copyright eggins.com, 1998 - 2008
Powered by Community Server (Non-Commercial Edition), by Telligent Systems