在Powershell中如何将数组作为参数传递,这是Start-Process -ArgumentList的多个参数之一

时间:2016-02-18 14:42:49

标签: powershell

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"

在这种情况下,$stringArray被视为包含一个元素的数组:

screen capture of script run output

我尝试了多个传递$stringArray参数的变体:

-StringArray $stringArray

-StringArray @($stringArray)

-StringArray @(,@($stringArray))

每个都有相同的错误: 无法找到接受参数'String2'

的位置参数

据我所知,ArgumentList值周围的双引号导致任何被解析的变量。有可能防止这种情况发生吗?或者有替代方法吗?

我的用例涉及尝试使用提升的权限重新运行Powershell脚本以卸载Windows更新,这就是我将Start-Process-Verb RunAs一起使用的原因。

2 个答案:

答案 0 :(得分:0)

我从双引号中逃脱了,似乎工作正常:

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

答案 1 :(得分:0)

这是一种方式。 # l shape: [batch_size, 32, 32, 4] output_shape = [self.batch_size, 8, 8, 128] filter_shape = [7, 7, 128, l.get_shape()[-1]] strides = [1, 2, 2, 1] with tf.variable_scope("g_h1"): w = tf.get_variable('w', filter_shape, initializer=tf.random_normal_initializer(stddev=0.02)) h1 = tf.nn.conv2d_transpose(l, w, output_shape=output_shape, strides=strides, padding='SAME') h1 = tf.nn.relu(h1) output_shape = [self.batch_size, 16, 16, 128] filter_shape = [7, 7, 128, h1.get_shape()[-1]] strides = [1, 2, 2, 1] with tf.variable_scope("g_h2"): w = tf.get_variable('w', filter_shape, initializer=tf.random_normal_initializer(stddev=0.02)) h2 = tf.nn.conv2d_transpose(h1, w,output_shape=output_shape, strides=strides, padding='SAME') h2 = tf.nn.relu(h2) output_shape = [self.batch_size, 32, 32, 3] filter_shape = [5, 5, 3, h2.get_shape()[-1]] strides = [1, 2, 2, 1] with tf.variable_scope("g_h3"): w = tf.get_variable('w', filter_shape, initializer=tf.random_normal_initializer(stddev=0.02)) h3 = tf.nn.conv2d_transpose(h2, w,output_shape=output_shape, strides=strides, padding='SAME') h3 = tf.nn.tanh(h3)

ScriptCallingStartProcess.ps1

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

ScriptToInvoke.ps1

(即,将逗号分隔的字符串作为第一个参数传递,然后在第二个脚本中分割)