简体   繁体   中英

In Powershell how can I pass an array as an argument, which is one of multiple arguments to Start-Process -ArgumentList

ScriptToInvoke.ps1:

[CmdletBinding()]
param (
    [Parameter(Mandatory=$True)]
    [string[]]$StringArray,
    [ValidateSet('Mode1', 'Mode2', 'Mode3')]
    [string]$Mode = 'Mode1'
)

$count = $StringArray.Count
Write-Verbose ("String array count ($count): $StringArray")

ScriptCallingStartProcess.ps1:

$stringArray = @('String1','String2','String3')
Start-Process powershell -Verb RunAs
-ArgumentList "-NoExit -File ScriptToInvoke.ps1 -StringArray ""$stringArray"" -Mode Mode3 -Verbose"

In this case the $stringArray is treated as an array containing one element:

screen capture of script run output

I have tried multiple variations passing the $stringArray argument:

-StringArray $stringArray

-StringArray @($stringArray)

-StringArray @(,@($stringArray))

each with the same error: A positional parameter cannot be found that accepts argument 'String2'

As I understand it the double quotes around the ArgumentList value result in any variable being parsed. Is it possible to prevent this from happening? Or is there an alternative approach?

My use case involves attempting to re-run the Powershell script with elevated permissions to uninstall a Windows update, which is why I use Start-Process with -Verb RunAs .

我对双引号进行了转义,似乎可以正常工作:

Start-Process powershell -Verb RunAs -ArgumentList "-NoExit -File test.ps1 -StringArray `"$stringArray`" -Mode Mode3 -Verbose"

Here's one way. ScriptCallingStartProcess.ps1 :

$stringArray = @('String1','String2','String3')
$OFS=","
Start-Process powershell.exe -Verb Runas "-NoExit -File \ScriptToInvoke.ps1 $stringArray -Mode Mode3 -Verbose"

ScriptToInvoke.ps1 :

[CmdletBinding()]
param (
  [Parameter(Mandatory=$True)]
  [String] $InputData,
  [ValidateSet('Mode1', 'Mode2', 'Mode3')]
  [string]$Mode = 'Mode1'
)

$StringArray = $InputData -split ','
$count = $StringArray.Count
Write-Verbose ("String array count ($count): $StringArray")

(that is, pass a comma-delimited string as first parameter, then split inside second script)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM