如何从操作系统将数组传递到PowerShell脚本

时间:2013-11-28 19:18:36

标签: powershell teamcity

以下命令行导致我的脚本因缺少参数而抛出。仅当-WebServerList参数包含用于表示数组的括号时才会出现此问题。

这是由TeamCity发起的,我假设它正在制作一个简单的Windows shell命令,因此shell / Windows可能会解释()

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -ExecutionPolicy ByPass -File E:\PowerShell\DeploySolution.ps1`
    -ProjectName Integro -BuildVersion "8.0.5 (build 27692) " -DeploymentType IIS`
    -WebServerList @("ws1", "ws2") -WebServerUserName TeamCityMSDeploy`
    -WebServerPassword yeahR1ght -WebPackagePath E:\WebDeployPackages\IntegroWebAPI_QA_MSDeploy_Package.zip`
    -WebServerDestination Integro-QA`
    -MSDeployPath "C:\Program Files\IIS\Microsoft Web Deploy V3"

但是,我尝试过DOS转义,例如^( ... ^)但这没有用。从Windows调用PowerShell脚本一直很辛苦,毕竟谁想做一个像这样疯狂的事情吧!

与此同时,我将更改我的脚本以在单个字符串中访问CSV并手动拆分,这样我就可以回家了,但是知道是否有正确的处理方法会很好此

2 个答案:

答案 0 :(得分:3)

似乎问题是操作系统无法正确定义阵列配置。您可以使用-Co​​mmand而不是-File:

来实现类似于您想要的内容
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -ExecutionPolicy ByPass `
-Command "& E:\PowerShell\DeploySolution.ps1 -ProjectName Integro`
-BuildVersion '8.0.5 (build 27692) ' -DeploymentType IIS  `
-WebServerList @('ws1', 'ws2') -WebServerUserName TeamCityMSDeploy`
-WebServerPassword yeahR1ght `
-WebPackagePath E:\WebDeployPackages\IntegroWebAPI_QA_MSDeploy_Package.zip `
-WebServerDestination Integro-QA `
-MSDeployPath 'C:\Program Files\IIS\Microsoft Web Deploy V3'"

干杯,克里斯。


我冒昧地编辑你的答案来演示结果,并证明它有效。

从DOS命令提示符:

C:\>c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -ExecutionPolicy ByPass -File c:\DATA\Git\PowerShell\Test-PassingArray.ps1 -Array milk
milk

C:\>c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -ExecutionPolicy ByPass -File c:\DATA\Git\PowerShell\Test-PassingArray.ps1 -Array @("milk", "cheese")
@(milk,

C:\>c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -ExecutionPolicy ByPass -Command "& c:\DATA\Git\PowerShell\Test-PassingArray.ps1 -Array @("milk", "cheese")"
At line:1 char:61
+ & c:\DATA\Git\PowerShell\Test-PassingArray.ps1 -Array @(milk, cheese)
+                                                             ~
Missing argument in parameter list.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingArgument


C:\>c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -ExecutionPolicy ByPass -Command "& c:\DATA\Git\PowerShell\Test-PassingArray.ps1 -Array @('milk', 'cheese')"
milk
cheese

C:\>

答案 1 :(得分:2)

你需要在TeamCity中解决这个问题,因为它传递的命令行项目用逗号分隔,逗号是Powershell中数组项的相同分隔符。将数组作为分号分隔的字符串传递,并在Powershell脚本中拆分它们。这是一个例子。

将此命令传递给命令行中的脚本(无论是文件还是普通脚本):

-WebServerList "ws1;ws2"

然后在脚本中使用它:

$WebServerList -split ";" | ForEach {
    $server = $_
    # do whatever you like here
}

注意:此解决方案适用于简单的数组对象,如字符串和数字,但不适用于复杂的对象。