I’ve previously posted on how to call use a PowerShell script to call another PowerShell script, even with a variable passed! What about returning a value to the calling PowerShell script? This is actually pretty easy and intuitive for a single variable. In my case, I want to know if the called script failed or not.
This first script simply calls the second script, test2.ps1 and sets its result to $return. Then I echo back the $return value to make sure it stuck.
script1:
$return = & “c:\script2.ps1”
$return
This second script simply prints text to prove it was called, then returns back $true.
script2:
Write-Host “Hello World!” -back yellow -fore green
return $true
And this is the result:
PS > ./test1.ps1
Hello World!
True
PS >
There are no doubt more sophisticated means to return multiple values and even objects back, which may or may not be the same thing as I’ve given above, but this sufficed to meet a need I had to just pass back a complete/fail variable.
That is a good start. Can you set it up in a nested configuration to return complex variables after several results are collected?
BakSla5h-
Looks like it! I added more values to $return to turn it into an array of values, and all of them got passed back into the first script. That kinda tells me objects and other data can also be passed back.
The one problem so far would be trying to pass back data piece by piece. With this method, I have to collect all the data I want into $return, and then pass it all back at once at the end. Like messing with global variables, perhaps.