【问题标题】:How to correctly pass a string array as a parameter in a PowerShell 4.0 Invoke-Command -ScriptBlock如何在 PowerShell 4.0 Invoke-Command -ScriptBlock 中正确传递字符串数组作为参数
【发布时间】:2017-10-24 19:49:06
【问题描述】:

我正在使用 PowerShell 4.0,并且我正在尝试将字符串数组作为 Invoke-Command -ScriptBlock 的参数之一传递,我在其中调用远程服务器上的另一个 PowerShell 脚本。当我这样做时,字符串数组似乎被展平,因此它显示为单个字符串值,而不是字符串数组。

下面列出的是第一个脚本,它由提供初始参数的 Bamboo 部署服务器调用。

在 Debug 部分,$SupportFolders 字符串数组由 FlowerBoxArrayText 函数迭代,并按预期将两个文件夹路径正确写入控制台。

24-Oct-2017 14:59:33    *****************************************************************************
24-Oct-2017 14:59:33    **** E:\SRSFiles\SRSOutput
24-Oct-2017 14:59:33    **** E:\SRSFiles\SRSBad
24-Oct-2017 14:59:33    *****************************************************************************

这是第一个脚本文件的初始部分,显示了输入参数、字符串数组的创建以及我通过 Invoke-Command 调用远程脚本的位置;

 [CmdletBinding(DefaultParametersetName='None')]
 param (
    # Allows you to specify Install, Delete or Check.
    [ValidateSet("Install", "Delete", "Check")][string] $Action = "Check",
    # Allows you to specify the remote server name.
    [string] $ComputerName = "None",
    # Allows you to specify the username to use for installing the service.
    [string] $Username = "None",
    # Allows you to specify the password to use for installing the service.
    [string] $Password = "None",
    # Allows you to specify the location of the support folders for the service, if used. 
    [string] $SupportFoldersRoot = "None"    
)

Function CreateCredential() 
{
    $Pass = $Password | ConvertTo-SecureString -AsPlainText -Force
    $Cred = New-Object System.Management.Automation.PSCredential($Username, $Pass) 
    Return $Cred
}

Function FlowerBoxArrayText($TextArray, $TextColor="Yellow")
{
    Write-Host "*****************************************************************************" -ForegroundColor $TextColor
    foreach($TextLine in $TextArray) 
    {
        IndentedText $TextLine $TextColor
    }
    Write-Host "*****************************************************************************" -ForegroundColor $TextColor
}


Function IndentedText($TextToInsert, $TextColor="Yellow")
{
    Write-Host "**** $TextToInsert" -ForegroundColor $TextColor
}



$Credential = CreateCredential
[string[]] $ResultMessage = @()
[string] $Root = $SupportFoldersRoot.TrimEnd("/", "\")
[string[]] $SupportFolders = @("$Root\SRSOutput", "$Root\SRSBad")

#Debug
Write-Host "**** Starting debug in ManageAutoSignatureProcessorService ****"
FlowerBoxArrayText $SupportFolders -TextColor "Green"
Write-Host "**** Ending debug in ManageAutoSignatureProcessorService ****"
#End Debug

$ResultMessage = Invoke-Command -ComputerName $ComputerName -Credential $Credential -ScriptBlock {
    param($_action,$_username,$_password,$_supportFolders) &"C:\Services\ManageService.ps1" `
    -Action $_action `
    -ComputerName DEV `
    -Name DevProcessor `
    -DisplayName 'DevProcessor' `
    -Description 'DevProcessor' `
    -BinaryPathName C:\Services\DevProcessor.exe `
    -StartupType Manual `
    -Username $_username `
    -Password $_password `
    -ServicePathName C:\Services `
    -SupportFolders $_supportFolders `
    -NonInteractive } -ArgumentList $Action,$Username,$Password,(,$SupportFolders)

if ($ResultMessage -like '*[ERROR]*') 
{
    FlowerBoxArrayText $ResultMessage -textColor "Red"
} 
else 
{
    FlowerBoxArrayText $ResultMessage -textColor "Green"
}

然后,在远程服务器上的 ManageService.ps1 脚本文件中,我有以下内容;

[CmdletBinding(DefaultParametersetName='None')]
    param (
    # Allows you to specify Install, Delete or Check.
    [ValidateSet("Install", "Delete", "Check")][string] $Action = "Check",
    # Allows you to specify the name of the remote computer.
    [string] $ComputerName = "None",
    # Allows you to specify the service name.
    [string] $Name = "None",
    # Allows you to specify the service display name.
    [string] $DisplayName = "None",
    # Allows you to specify the service description.
    [string] $Description = "None",
    # Allows you to specify the path to the binary service executable file.
    [string] $BinaryPathName = "None",
    # Allows you to specify how the service will start, either manual or automatic.
    [ValidateSet("Manual", "Automatic")][string] $StartupType = "Manual",
    # Allows you to specify the domain username that the service will run under.
    [string] $Username = "None",
    # Allows you to specify the password for the domain username that the service will run under.
    [string] $Password = "None",
    # Allows you to specify the path to the service install scripts and service files on the remote server.
    [string] $ServicePathName = "None",  
    # Allows you to specify the location of the support folders for the service, if used. The default value is an empty array
    [string[]] $SupportFolders = @(),    
    # Disables human interaction, and allows all tests to be run even if they 'fail'.
    [switch] $NonInteractive
)


Function CreateCredential() 
{
    $Pass = $Password | ConvertTo-SecureString -AsPlainText -Force
    $Cred = New-Object System.Management.Automation.PSCredential($Username, $Pass) 
    Return $Cred
}


[bool] $OkToInstall = $False
[string[]] $ResultMessage = @()

#Debug
$ResultMessage = $ResultMessage += "[DEBUG] ***************************************"
$ResultMessage = $ResultMessage += "[DEBUG] SupportFolders: [$SupportFolders] ."

foreach ($Folder in $SupportFolders) 
{
    $ResultMessage = $ResultMessage += "[DEBUG] SupportFolders Item: $Folder."
}
$Count = @($SupportFolders).Count
$ResultMessage = $ResultMessage += "[DEBUG] SupportFolders Count: $Count ."
$ResultMessage = $ResultMessage += "[DEBUG] ***************************************"
#End Debug

线,

$ResultMessage = $ResultMessage += "[DEBUG] SupportFolders: [$SupportFolders] ."

显示返回给调用脚本的 $ResultMessage 值的以下结果;

**** [DEBUG] SupportFolders: [E:\SRSFiles\SRSOutput E:\SRSFiles\SRSBad] .

请注意,数组已展平。

随后的 foreach 循环也只打印出一个值,而不是两个;

"E:\SRSFiles\SRSOutput E:\SRSFiles\SRSBad"

我花了很多时间研究解决方案,但还没有找到答案。

有什么想法吗?

使用@Bacon Bits 建议编辑 1;

$Options = @{'Action' = $Action
        'ComputerName' = 'DEV'
        'Name' = 'DevProcessor'
        'DisplayName' = 'DevProcessor'
        'Description' = 'Generate daily processes'
        'BinaryPathName' = 'C:\Services\DevProcessor\DevProcessor.exe'
        'StartupType' = 'Manual'
        'Username' = $Username
        'Password' = $Password
        'ServicePathName' = 'C:\Services\DevProcessor'
        'SupportFolders' = $SupportFolders
}

$ScriptBlock = {
param($Options)
& {
    param(
        $Action,
        $ComputerName,
        $Name,
        $DisplayName,
        $Description,
        $BinaryPathName,
        $StartupType,
        $Username,
        $Password,
        $ServicePathName,
        $SupportFolders,
        $NonInteractive
    )
    &powershell "C:\Services\DevProcessor\ManageService.ps1 $Action $ComputerName $Name $DisplayName $Description $BinaryPathName $StartupType $Username $Password $ServicePathName $SupportFolders"
} @Options;
}

$ResultMessage = Invoke-Command -ComputerName $ComputerName -Credential $Credential -ScriptBlock $ScriptBlock -ArgumentList $Options

如果我运行上面列出的修改后的代码,我仍然会得到 $SuppportFolders 的扁平数组,并且 ManageService.ps1 脚本会在包含空格的参数上出错,即使在我分配它们时它们被引用。

将代码完全包装在 ManageService.ps1 中的选项,而不是简单地调用远程脚本实际上并不可行,因为 ManagedService.ps1 脚本相当广泛和通用,所以我可以从我的 30 多个自动化脚本中调用它部署服务器。

如果包装 ManageService 脚本可行,我相信 @Bacon Bits 的建议会起作用。

【问题讨论】:

标签: powershell powershell-4.0 powershell-remoting invoke-command


【解决方案1】:

要传递单个数组,您可以这样做:

Invoke-Command -Session $Session -ScriptBlock $ScriptBlock -ArgumentList (,$Array);

但是,这仅在您只需要传递一个数组时才有效。一旦你开始传递多个数组或多个复杂对象,它就会崩溃。

有时,这会起作用:

Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList (, $Array1), (, $Array2), (, $Array3);

但是,根据我的经验,它可能不一致。有时它会再次将数组展平。

你可以做的类似于this answer

{param($Options)& <# Original script block (including {} braces)#> @options }

基本上我们做的是:

  1. 将脚本包装在一个接受单个哈希表作为参数的脚本块中。
  2. 将所有参数放入哈希表中。
  3. 将传递的哈希表用作 splat 变量。

所以应该是这样的:

$Options = @{
    Action = 'Check';
    ComputerName = 'XYZ123456';
    Name = 'MyName';
    .
    .
    .
}

$ScriptBlock = {
    param($Options) 
    & {
        [CmdletBinding(DefaultParametersetName='None')]
        param (
        # Allows you to specify Install, Delete or Check.
        [ValidateSet("Install", "Delete", "Check")][string] $Action = "Check",
        # Allows you to specify the name of the remote computer.
        [string] $ComputerName = "None",
        # Allows you to specify the service name.
        [string] $Name = "None",
        .
        .
        .
        .
        #End Debug
    } @Options;
}

Invoke-Command -ComputerName RemoteServer -ScriptBlock $ScriptBlock -ArgumentList $Options;

这是一个简单的工作示例:

$Options = @{
    List1 = 'Ed', 'Frank';
    List2 = 5;
    List3 = 'Alice', 'Bob', 'Cathy', 'David'
}

$ScriptBlock = {
    param($Options) 
    & {
        param(
            $List1,
            $List2,
            $List3
        )
        "List1"
        $List1
        ''
        "List2"
        $List2
        ''
        "List3"
        $List3
    } @Options;
}

Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Options;

输出:

List1
Ed
Frank

List2
5

List3
Alice
Bob
Cathy
David

请注意,我在 PowerShell v5 上对此进行了测试。我不再有要测试的带有 PowerShell v4 的系统。

【讨论】:

  • 我看到从 PowerShell 3 开始支持飞溅,因此功能应该可以工作。我已经开始创建一个使用 splatted 参数的版本,但不确定如何使其与 Invoke-Command 一起使用。我会在早上测试你的建议。您是否知道这种方法存在任何问题,并且哈希表中的参数值有空格?
  • @EiEiGuy 我不确定我明白你在问什么。但是,如果参数中有空格,则通常需要将它们放在引号中。
  • 好的,据我了解,您是在建议我将远程服务器上的脚本(我的 OP 中的 ManageService.ps1 脚本)包装在此脚本的 $ScriptBlock 代码中(我的 OP 中的调用脚本)。我遇到的问题是 ManageService.ps1 脚本是一个相当广泛的服务安装脚本,被 30 多个自动化脚本重用,类似于我在帖子中描述的调用脚本。
  • 我确实有带引号的参数,就像在整个参数值周围的引号中一样...例如 $Description = "This is a description"。但是,当它在远程脚本中解析哈希表时,它仍然将引用的参数视为多个值。
猜你喜欢
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多