我的第一个参数未传递给我的函数

时间:2019-06-18 12:32:14

标签: powershell

我有一个Jenkins作业,它调用带有某些参数的PowerShell脚本。参数始终是启动/停止,然后是多个硒测试机以打开/关闭电源。例子:

powershell.exe -File gridControl.ps1 start grid1 grid2 grid3
powershell.exe -File gridControl.ps1 stop grid4 grid6 grid7

该脚本最近运行良好,直到我们被要求为其添加超时,因为有时该脚本的一部分已挂起。问题是要添加超时,我们将整个内容封装在一个函数中,以便可以将其作为作业运行并对其计时。

这意味着我们还需要将参数解析到函数中。我是按照Powershell pass variable to start-job

这样做的

我的问题是我的第一个变量丢失了。这是代码(不包括实际的机器启动/停止。它只是连接到VCS并尝试打印出我的参数):

Write-Host " gridControl - Started"
$timeoutSeconds = 60
$code =  
{
    param($args)
    $vcenter = "vc-3dc-v01.redacted.local"
    $delaysec = 120
    $toolsdelayCheck = 30
    $looprepeats = 10
    $toolsrunningDelay = 60
    $emailTo = @('redacted@zetta.bg', 'redacted@finanalytica.com')

    Write-Host " Connecting to VCenter..."

    Add-PSSnapin VMware.VimAutomation.Core -WarningAction SilentlyContinue | Out-Null
    Connect-VIServer -Server $vcenter -WarningAction SilentlyContinue -Verbose

    if(!$?){
        Write-Host "Could not connect to VCenter"
    }
    else{
        Write-Host "Successfully connected to vCenter"
    }

    Write-Host $args[0]
    Write-Host $args[1] $args[2] $args[3]

    Write-Host " gridControl - Ready to finish"
    Disconnect-VIServer -Server $vcenter -Confirm:$false -Force:$true -WarningAction SilentlyContinue -ErrorAction SilentlyContinue

    Write-Host " VIServer Disconnected"
    Remove-PSSnapin VMware.VimAutomation.Core
}
$j = Start-Job -ScriptBlock $code -Arg $args

Write-Host " cp2"
if (Wait-Job $j -Timeout $timeoutSeconds) { Receive-Job $j }
Write-Host " cp3"

Remove-Job -force $j
Write-Host " gridControl - Terminate"

重要的是我从中得到的输出

Write-Host $args[0]
Write-Host $args[1] $args[2] $args[3]

哪个是

15:05:49 grid1
15:05:49 grid2 grid3 

应该在什么时候

15:05:49 start
15:05:49 grid1 grid2 grid3

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:5)

直接引用$args数组中的项目。您不需要脚本顶部的param($args)语句。

简化示例...

$things = @(1, 2, 3);
$script = {
    Write-Host $args[0]
    Write-Host $args[1]
}

foreach ($thing in $things) {
    Start-Job -ScriptBlock $script -ArgumentList $thing, ($thing * 3) -Name "Job-${thing}"
}

Receive-Job -Name "Job-1"
Receive-Job -Name "Job-2"
Receive-Job -Name "Job-3"

如果在shell中运行此命令,则会看到我同时获得了两个参数。

enter image description here