Alex Rivera | Logout

how to output a string to variable and console at the same time

Asked 2011-08-17T02:07:34.807
12

is there an easy way in powershell to output a string to variable and console at the same time?

i want to capture the output of my script to a variable so i can analyze it in the end of the script, save it to a log file and also email to an operator.

my intent is to have a variable $output and add any output strings to it and also output to console immediately something like

$output="Process started"

$output=+"Doing step 1"
"Doing step 1"

$output=+"Doing step 2"
"Doing step 2"

so in the end I can save $output to a log file, email it and parse it.

I played with tee-object that might work for that purpose but unfortunately it would rewrite my $output variable instead of appending a string to it.

UPDATE This is the final solution I decided to go with - thanks to manojlds!

$script:output = ""

filter mylog {
    $script:output+= $_+"`n"
    return $_
}


"doing step {0}" -f 1 | mylog
"doing step {0}" -f 2 | mylog
"doing step {0}" -f 3 | mylog

#in the end of the script
$script:output
Edit
Report

1 Answer

1

I haven't messed with powershell enough to give a concrete answer, but if I were to do this in C I would exploit side effects.

//Psuedo-C
string con (oldString, newString) {
  print(newString);
  return oldString + newString;
}

Use function like so:

myString = con(myString, "Process started");

It would have the desired effect. (leaving aside correct C syntax and pedantry such as dealing with newlines) I don't know how to translate this to powershell.

What you want to do may be considered messy however. It might be clearer if you just explicitly output and log output and log one after the other in your code. Side effects inevitably come back to bite you. Keep things modular.

answered 2011-08-17T04:30:34.567

Your Answer