Josh Alcorn
Josh Alcorn

Reputation: 158

Formatting output in powershell

I'm attempting to write a powershell script and running into a problem that google can't seem to tell me how to fix. Basically, i have 4 variables:

$myDuration = $myObj.Duration
$mySubject = $myObj.Subject
$myStart = $myObj.Start
$myLocation = $myObj.Location

I'm trying to send an email where the body is:

"Your meeting ({0}) will begin {1}. It will be held at {2} and last approximately {3}."   -f $mySubject,$myStart,$myLocation,$myDuration

Now, if I ONLY include one variable, it works just fine. For example, "Your meeting {0}" -f $myLocation correctly outputs the value stored in $myLocation.

When I include more then one, my output for each variable is the exact string "System.Object[]". (IE "Your meeting (System.Object[]) will begin System.Object[]. It will be held at System.Object[] and last approximately System.Object[].") Any ideas why it bugs when I include more then one variable? From everything I've read about on Google there shouldn't be an issue.

Upvotes: 0

Views: 206

Answers (1)

alroc
alroc

Reputation: 28144

I suspect that one or more of the fields in $myObj is something other than a string and can't be converted to a string easily, and that's throwing the formatter off. Have a look at this code:

$myDuration = "Duration";
$mySubject = "Subject";
$myStart = "Starttime";
$myLocation = "Location";

"Your meeting ({0}) will begin {1}. It will be held at {2} and last approximately {3}."   -f $mySubject,$myStart,$myLocation,$myDuration

$myObj = @{"Duration"=[int32]123456;"Subject"="Subject2";"Starttime"=(get-date);"Location"="Location2"};
$myDuration = $myObj.Duration;
$mySubject = $myObj.Subject;
$myStart = $myObj.Starttime;
$myLocation = $myObj.Location;
"Your meeting ({0}) will begin {1}. It will be held at {2} and last approximately {3}."   -f $mySubject,$myStart,$myLocation,$myDuration

And my output is:

Your meeting (Subject) will begin Starttime. It will be held at Location and last approximately Duration.
Your meeting (Subject2) will begin 2/13/2014 10:30:39 PM. It will be held at Location2 and last approximately 123456.

It all works as expected.

Upvotes: 1

Related Questions