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

时间:2019-02-04 12:59:16

标签: powershell azure-devops azure-pipelines-release-pipeline

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

我在本地使脚本可以工作,但是要使其像嵌入式脚本一样在管道中工作并不是很好。

我使用默认参数构建脚本,因此可以使用输入在本地对其进行测试,但是当我在Azure中执行该脚本时,会收到错误消息

  

param:术语'param'不被视为cmdlet,函数,脚本文件或可运行程序的名称。检查名称的拼写,或者是否包含路径,请确认路径正确,然后重试。

我不允许在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
}

1 个答案:

答案 0 :(得分:0)

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

$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上对此进行了一些讨论。您还可以浏览一下代码,因为它是开源的。