3

I got a PowerShell script that starts another script and passes parameters to it. I do this with Start-Job as I do not want to wait until the second script is finished:

ScriptA:

start-job -name EnableAutoUnlock -scriptblock {Invoke-Command -script { C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "\\Path\To\Script\EnableAutoUnlock.ps1" $VolumeDriveLetter }}

ScriptB:

    [CmdletBinding()]
Param (
    [Parameter(Position=0)]
    [string]$drive
)
<do stuff with $drive here>

$VolumeDriveLetter is just a Drive Letter that gets processed i.e. "C:"

Unfortunately the passing of the Parameter by variable does not work although $VolumeDriveLetter has the expected Value but typing it does work correctly.

Works:

start-job -name EnableAutoUnlock -scriptblock {Invoke-Command -script { C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "\\Path\To\Script\EnableAutoUnlock.ps1" C: }}

Does not Work

$VolumeDriveLetter = "C:"

start-job -name EnableAutoUnlock -scriptblock {Invoke-Command -script { C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "\\Path\To\Script\EnableAutoUnlock.ps1" $VolumeDriveLetter }}

EDIT: ScriptB Outputs the passed Variable as empty

What am I missing to get passing of the Variable to work?

1 Answer 1

4

You can use the using prefix to access the value within a scriptblock:

$VolumeDriveLetter = "C:"

start-job -name EnableAutoUnlock -scriptblock {Invoke-Command -script { C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "\\Path\To\Script\EnableAutoUnlock.ps1" $using:VolumeDriveLetter }}

Or you use the -ArgumentList parameter and pass the parameter to the scriptblock:

start-job -name EnableAutoUnlock -scriptblock { 
    Param($VolumeDriveLetter) 
    Write-Host $VolumeDriveLetter 
} -ArgumentList $VolumeDriveLetter
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer but I just tried that and unfortunately it does not work (same as before, the Parameter recieved by scriptB is just empty)
Thanks alot, i used the edited answer and it worked perfectly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.