如何在 Azure PowerShell 的错误消息中隐藏敏感值?

Posted

技术标签:

【中文标题】如何在 Azure PowerShell 的错误消息中隐藏敏感值?【英文标题】:How to hide sensitve values in error messages in Azure PowerShell? 【发布时间】:2021-09-16 21:17:21 【问题描述】:

在 azure Powershell 中,我使用命令“az vm run-command invoke”对虚拟机执行脚本,问题是由于某种原因它不起作用时,它会在错误消息中打印所有参数的值清除,并且这些参数是敏感数据,出于安全原因,我不必在错误消息中打印。

这是我尝试执行的:

az vm run-command invoke -g $ResourceGroupName -n $VMname[-1] --command-id RunPowerShellScript --scripts @$pathScript --parameters "param1=$($Data1)" `
    "param2=$($Data2)" 

在我的情况下,Data1 可能是敏感的,我从不在代码中打印该值,但在错误消息中,该值以清晰的形式显示,我不必允许这样做。

请记住,当我添加正确的参数时,@$pathScript 中定义并在机器中执行的脚本运行良好。

我尝试将代码放入 try catch 块中,但这仍然会抛出错误消息,并且不会打印在 catch 部分中添加的消息

try
    az vm run-command invoke -g $ResourceGroupName -n $VMname[-1] --command-id RunPowerShellScript --scripts @$pathScript --parameters "param1=$($Data1)" `
    "param2=$($Data2)" 
catch
    Write-Error "Error : Please check if your are passing the good arguments - Check the code if you need and debug it"

我错过了什么?

【问题讨论】:

param1 是否在您的脚本中定义为安全字符串? 好点@Thomas,我会检查一下 【参考方案1】:

由于这是一个外部应用程序,您将无法使用 try/catch 捕获错误。您可以尝试将错误流重定向到 $null (2>$null) 以便看不到它,然后检查 $LASTEXITCODE。下面我只是大致检查 $LASTEXITCODE 是否不等于 0 并生成错误,但您可能想检查您得到的确切退出代码是什么,然后只写错误。

az vm run-command invoke -g $ResourceGroupName -n $VMname[-1] --command-id RunPowerShellScript --scripts @$pathScript --parameters "param1=$($Data1)" `
    "param2=$($Data2)" 2>$null
if ($LASTEXITCODE) 
    Write-Error 'Error : Please check if your are passing the good arguments - Check the code if you need and debug it'

【讨论】:

以上是关于如何在 Azure PowerShell 的错误消息中隐藏敏感值?的主要内容,如果未能解决你的问题,请参考以下文章

Azure devops powershell 任务问题

Powershell 停止 Azure 备份

在 Azure PowerShell 中显示自定义错误消息并退出

Azure PowerShell - CurrentStorageAccountName 错误处理办法

Azure 应用服务Azure Function 中运行Powershell 脚本,定位 -DefaultProfile 引发的错误

Azure Service Fabric 从 Visual Studio 发布升级 - PowerShell 脚本错误