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?

4

1 回答 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
于 2016-11-08T10:35:50.203 回答