0

I have a running PS1-script (start-webserver.ps1) running as a "web server" that is listening for http calls that executes a script (example: script2.ps1) executed in the call to the "web server". I am executing the script with Start-Job. How can I in the executed script (script2.ps1) access variables in start-webserver.ps1?

Start-WebServer.ps1

$allObjects = @()
foreach ($item in $items) {
    $objectUID = $item.Attributes.Value                          
    $propertiesHash = [ordered]@{UID = $objectUID}                           
    $properties = $items.ChildNodes
    foreach ($property in $properties.ChildNodes) {
        $propertyName = $property.Attributes.Value                               
        $propertyValue = $property.innerText                                 
        $propertiesHash.Add($propertyName, $propertyValue)
    }
    $object = New-Object PSObject -Property $propertiesHash                          
    $allObjects += $object
}
$job = Start-Job -Name "$identifier" -FilePath "Path\To\ScriptToExecute.ps1" -InputObject $allObjects -ArgumentList $propertiesHash

ScriptToExecute.ps1

'Script executed!' | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
$propertiesHash | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
$allObjects | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append

I end up with an "output.txt" with the following content:
Script executed!
Empty line

0

1 Answer 1

1

You need to define in ScriptToExecute that you are receiving params

By default it is set in the $args variable.

In your case, simply using $args[0] will be sufficient.

i.e.:

'Script executed!' | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
$args[0] | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append

If you want to also receive $allObjects, you need to modify Start-WebServer to this:

$job = Start-Job -Name "$identifier" -FilePath "Path\To\ScriptToExecute.ps1" -InputObject $allObjects -ArgumentList @($propertiesHash,$allObjects)

then do this:

'Script executed!' | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
$args[0] | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
$args[1] | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append

Nicer way of doing this is to specify the param in ScriptToExecute

i.e.:

param($propertiesHash, $allObjects)
'Script executed!' | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
$propertiesHash | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
$allObjects | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.