Heuristic
Heuristic

Reputation: 169

Running powershell from Perl and getting a return value

I am running a Perl script that calls a powershell script. Is there a way for me to get a return value from this? I've tried something similar to

my @output = "powershell.exe powershellscript.ps1;
foreach(@output)
{
   print $_;
}

and I get nothing out of it. Do I need to add something to the powershell script to push the return values?

Upvotes: 0

Views: 2958

Answers (3)

JRFerguson
JRFerguson

Reputation: 7516

Use backticks to run and collect the output:

my @output = ` ...`

If you want the return code (status) too, do (by example):

perl -e '@output=`/bin/date`;print $?>>8,"\n";print "@output"'

See system for more information on interpreting the return code.

ADDENDUM

In lieu of backticks, which can sometimes be annoying to read, you can use qx(STRING) as described in perlop. This is analogous to collecting process output in shell scripts where, in POSIX-compliant shells, capture may be done with the archaic backticks, or more readably, with OUTPUT=$(/bin/date).

Upvotes: 1

user2372262
user2372262

Reputation: 36

Try using a named pipe:

open(PWRSHELL, "/path/to/powershell.exe powershellscript.ps1 |") or die "can't open powershell: $!";
while (<PWRSHELL>) {
    # do something
}
close(PWRSHELL) or warn "can't close powershell: $!";

Upvotes: 1

mpapec
mpapec

Reputation: 50647

Try with backsticks,

my @output = `powershell.exe powershellscript.ps1`;
foreach (@output)
{
   print $_;
}

Upvotes: 3

Related Questions