如何在 Jenkins 中使用 PowerShell 参数

How to use PowerShell parameter in Jenkins

我正在使用 PowerShell 在 Azure 中自动化 VM start/stop。但是,当我设置 $OPTION 参数时,它什么也没做。我有 if/elseif/else 个语句。

查看下面的代码:

Add-AzureRmAccount -Credential $psCred -TenantId <removed> -ServicePrincipal

Get-AzureRmSubscription -SubscriptionName "<removed>"

#Get VMs using Tags
$vms = (Find-AzureRmResource | Where-Object {($_.tags.Project -eq "DevOps") -And ($_.tags.Test -eq "ernest")} | Select Name, ResourceGroupName)
$vms

Write-Output "Number of Virtual Machines: $($vms.Name.Count)"

foreach($VM in $vms)
{
    if ($OPTION -eq "start" -And $VM.ResourceType -eq "Microsoft.Compute/virtualMachines") 
    {
        Write-Output "Starting :- $VM.Name in $VM.ResourceGroupName"
        Start-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Verbose
        Write-Output $VM.Name "has started successfully"

        Write-Output "Writing output to workspace"
        Get-AzureRmVM -Status | Where-Object {($_.tags.Project -eq "DevOps") -And ($_.tags.Test -eq "ernest")} | Select Name, ResourceGroupName, PowerState > VM_Start_Info-$(get-date -f yyyy-MM-dd).tsv 
    }

    elseif ($OPTION -eq "stop" -And $VM.ResourceType -eq "Microsoft.Compute/virtualMachines") 
    {
        Write-Output "Deallocating :- $VM.Name in $VM.ResourceGroupName"
        Stop-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Force -Verbose
        Write-Output $VM.Name "has been deallocated successfully"

        Write-Output "Writing output to workspace"
        Get-AzureRmVM -Status | Where-Object {($_.tags.Project -eq "DevOps") -And ($_.tags.Test -eq "ernest")} | Select Name, ResourceGroupName, PowerState > VM_Stopped_Info-$(get-date -f yyyy-MM-dd).tsv
    }
    else
    {
       Write-Output "No option selected, select an option"
    }
}
Write-Output "Script complete"

我必须将 $env:OPTION 参数添加到 Execute Powershell window。现在有效