I'm trying to send just the result I want from a called PowerShell script back to the calling script.
So the script testcaller.ps1
$Result = Invoke-Expression "$PSScriptRoot\testcalled"
$LogMessage = "TestCalled ended with Result $Result"
Write-Output $LogMessage
Calls the script testcalled.ps1
$TestMessage = "this is a test"
Write-Output $TestMessage
$Level = 1
exit $Level
When run it produces this...
TestCalled ended with Result this is a test 0
I have two problems. I get the testmessage passed back to my calling script and the level past back is 0 when it should be 1. What I want to see is...
TestCalled ended with Result 1
CodePudding user response:
Given testcalled.ps1
'hello world'
function Say-Hello { 'hello!' }
exit 1
If you want to run this external script from another script you can either dot source
it:
The functions, variables, aliases, and drives that the script creates are created in the scope in which you are working. After the script runs, you can use the created items and access their values in your session.
$Result = . "$PSScriptRoot\testcalled.ps1"
$Result # => hello world
Say-Hello # => 'hello!'
$LASTEXITCODE # => 1
Or use the call operator &
:
The call operator executes in a child scope.
Meaning that, functions, variables, aliases, and drives will not be available on the current scope.
$Result = & "$PSScriptRoot\testcalled.ps1"
$Result # => hello world
Say-Hello # => SayHello: The term 'SayHello' is not recognized as a name of a cmdlet, function....
$LASTEXITCODE # => 1
As you can see, on both cases, you can use the automatic variable $LASTEXITCODE
.
Last, but not least, it is not recommended to use Invoke-Expression
. See https://devblogs.microsoft.com/powershell/invoke-expression-considered-harmful/