Azure Devops 发布管道中的参数块问题

Problems with param block in a Azure Devops release pipeline

我正在编写自己的 Powershell 脚本,以在 Azure Devops 发布管道中通过 sFTP 上传一些文件。

我在本地使脚本正常工作,但要使其像内联脚本一样在管道中工作,效果并不理想。

我使用默认参数构建我的脚本,以便我可以使用输入在本地测试它,但是当我在 Azure 中执行它时,我收到错误消息

param : The term 'param' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

是否不允许我在 Azure 中使用 param()

param (
    $Localpath = $env:System_ArtifactsDirectory,
    $Remotepath = $env:sFTP_Remotepath,
    $Hostname = $env:sFTP_Host,
    $Username = $env:sFTP_Username,
    $Password = $env:sFTP_Password,    
    $HostKeyFingerprint = $env:sFTP_Hostkey,
    $WinSCPnetdllpath =  "$env:System_ArtifactsDirectory\WinSCPnet.dll"
)

try
{
    Write-Host "Hostname:" $Hostname
    Write-Host "Username:" $Username
    Write-Host "Password: ****"
    Write-Host "Remotepath:" $Remotepath
    Write-Host "Localpath:" $Localpath
    Write-Host "HostKeyFingerprint:" $HostKeyFingerprint
    Write-Host "WinSCPnetdllpath:" $WinSCPnetdllpath
    # Load WinSCP .NET assembly
    Add-Type -Path $WinSCPnetdllpath

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = $Hostname
        UserName = $Username
        Password = $Password
        SshHostKeyFingerprint = $HostKeyFingerprint
    }

    $session = New-Object WinSCP.Session

    try
    {
        # Connect
        $session.Open($sessionOptions)

        # Upload files, collect results
        $transferResult = $session.PutFiles($Localpath, $Remotepath, $False)

        Write-Host ("Found {0} of files to upload" -f $transferResult.Transfers.Count)

        # Iterate over every transfer
        foreach ($transfer in $transferResult.Transfers)
        {
            # Success or error?
            if ($transfer.Error -eq $Null)
            {
                Write-Host (" - Upload of '{0}' .. Success" -f $transfer.FileName)                              
            }
            else
            {
                Write-Host (" - Upload of '{0}' .. Failed: {1}" -f $transfer.FileName, $transfer.Error.Message)
            }
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

    exit 0
}
catch [Exception]
{
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1
}

在内联创建的 powershell 脚本周围放置了一些包装语句,这会导致错误。它目前似乎不支持内联调用的参数块。您可以改为直接引用您的参数。

$ErrorActionPreference = 'stop'
...
if (!(Test-Path -LiteralPath variable:\LASTEXITCODE)) {
    Write-Host '##vso[task.debug]$LASTEXITCODE is not set.'
} else {
    Write-Host ('##vso[task.debug]$LASTEXITCODE: {0}' -f $LASTEXITCODE)
    exit $LASTEXITCODE
}

这个github issue上有一些讨论。您还可以浏览一下代码,因为它是开源的。