【发布时间】:2021-06-27 21:55:38
【问题描述】:
我正在尝试在 DevOps 管道中运行内联脚本(如下)。此脚本正在尝试使用特定凭据生成 PowerShell 会话,以便在目标 vm 上运行远程脚本。在上一步中,密码是从 KeyVault 获得的(下面脚本中的 $kvPw)。但是,密码包含一个特殊字符,在本例中为 $。 devops 步骤如下所示:
inlineScript: |
az vm run-command invoke --command-id RunPowerShellScript --name $(vmName) -g My-ResourceGroup --scripts `
"`$pw = ConvertTo-SecureString '$(kvPw)' -AsPlainText -Force" `
"`$cred = New-Object System.Management.Automation.PSCredential 'vmName\adminUser',`$pw" `
"Start-Process PowerShell -Cred `$cred -ArgumentList '-noexit','-File','C:\test\deploy.ps1'"
上面生成的在vm上存储和执行的PowerShell脚本是:
$pw = ConvertTo-SecureString 'PeGiewRY1MAQ8)>U?N,T]BLFkLp' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential 'vmName\adminUser',$pw
Start-Process PowerShell -Cred $cred -ArgumentList '-noexit','-File','C:\test\deploy.ps1'
devops 中的作业步骤运行成功,但是在仔细检查 View Raw Log 后,我可以看到脚本实际上没有运行,因为 访问被拒绝 错误。
2021-03-31T20:28:15.1300587Z {
2021-03-31T20:28:15.1301041Z "code": "ComponentStatus/StdErr/succeeded",
2021-03-31T20:28:15.1301577Z "displayStatus": "Provisioning succeeded",
2021-03-31T20:28:15.1302112Z "level": "Info",
2021-03-31T20:28:15.1303733Z "message": "Start-Process : This command cannot be run due to the
error: Access is denied.\nAt
C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\1.1.8\\Downloads\\script2.ps1:3
char:1\n+ Start-Process PowerShell -Cred $cred -ArgumentList '-noexit','-File', ...\n+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo :
InvalidOperation: (:) [Start-Process], InvalidOperationException\n + FullyQualifiedErrorId :
InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand\n ",
2021-03-31T20:28:15.1305283Z "time": null
2021-03-31T20:28:15.1305668Z }
这是因为最终出现在虚拟机脚本文件中的密码是
PeGiewRY1MAQ8)>U?N,T]BLFkLp //while the value stored in KeyVault is:
PeGiewRY1MAQ8)$R>U?N,T]BLFkLp
正在删除“$R”。如何在 DevOps 中构建内联脚本以防止这种情况发生?似乎我需要将 $(kvPw) 用双引号括起来,但这是不可能的,因为每行都以双引号开始/结束。
[编辑]:根据下面@user19702 的建议,我尝试使用双引号并将它们转义,但得到以下错误:
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft
SDKs\Azure\CLI2\wbin\az.cmd" account set --subscription xxxxxxxx-xxxx-xxxx-
xxxx-xxxxxxxxxxxx"
C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile
-NonInteractive -ExecutionPolicy Unrestricted -Command ".
'C:\agent\_work\_temp\azureclitaskscript1617226948158.ps1'"
The filename, directory name, or volume label syntax is incorrect.
##[error]Script failed with exit code: 1
这似乎是一个解析错误,因为 vm 上没有生成 powershell 脚本。
【问题讨论】:
-
您是否尝试过先用单引号括起来,然后用双引号括起来?
$pw = ConvertTo-SecureString '"$(kvPw)"' -AsPlainText -Force
标签: powershell azure-devops azure-powershell