gpt4 book ai didi

PowerShell 错误记录为空/不正确 'InvocationInfo'

转载 作者:行者123 更新时间:2023-12-02 22:48:04 25 4
gpt4 key购买 nike

我在 Azure DevOps 中运行 PowerShell 脚本,如果命令失败,我需要记录警告,以便观察者可以看到脚本没有按预期运行。

作为警告的一部分,我希望输出脚本的路径和发生异常的行号/偏移量。

为此,我在 catch 或 try/catch block 中使用了 $_ 变量。

$command = "New-AzCosmosDBAccountKey -Name {0} -ResourceGroupName {1} -KeyKind {2}" -f $Name, $ResourceGroupName, $keyKind
Write-Verbose ("##[command] {0}" -f $command)
try {
Invoke-Expression $command
}
catch
{
Write-Host ("##[warning] {0}" -f $_.Exception.Message -replace "`r`n", ". ")
Write-Host ("##vso[task.logissue type=warning;sourcepath={0};linenumber={1};columnnumber={2};]{3}" -f $_.InvocationInfo.ScriptName, $_.InvocationInfo.ScriptLineNumber, $_.InvocationInfo.OffsetInLine, $_.Exception.Message -replace "`r`n", ". ")
}

但是,由于某些原因,在 $_.InvocationInfo 中,ScriptName 为空,并且 ScriptLineNumberOffsetInLine 设置为 1

如果我输出 $_.ScriptStackTrace,我看到有三个消息,并且大概 $_ 依赖堆栈跟踪中的最后一条消息。

at <ScriptBlock>, <No file>: line 1
at <ScriptBlock>, C:\pathTo\My-Script.ps1: line 40
at <ScriptBlock>, <No file>: line 1

我不明白的是堆栈跟踪中的这些消息来自哪里,以及为什么它们不包含脚本名称、行号等。

最佳答案

在对 OP 发表评论说我的问题是由于使用 Invoke-Expression 并建议我不要使用该 cmdlet 之后,我调查了其他可能的解决方案,然后发现了勇敢的新世界(对我来说!)splatting .

遗憾的是没有Format-Splat 函数,所以我不得不写一点,但由于它会在脚本中多次使用,所以我并不太在意。希望这是 MS 将来添加的内容。

令人高兴的是,使用下面的代码片段意味着现在可以为 Azure DevOps 正确编写警告 -

##vso[task.logissue type=warning;sourcepath=C:\pathTo\My-Script.ps1;linenumber=60;columnnumber=17;]Something went wrong.

using namespace System.Collections.Specialized

function Format-Splat
{
param([Parameter(Mandatory=$true)][OrderedDictionary]$Hashtable)

$output = @()
foreach ($key in $Hashtable.Keys)
{
$output += "-{0} {1}" -f $key, $Hashtable[$key]
}
Write-Output ($output -join " ")
}

$parameters = [Ordered]@{ Name = $Name; ResourceGroupName = $ResourceGroupName; keyKind = $keyKind }
Write-Verbose ("##[command]New-AzCosmosDBAccountKey {0}" -f (Format-Splat $parameters))
try {
$null = New-AzCosmosDBAccountKey @parameters
}
catch
{
Write-Output ("##vso[task.logissue type=warning;sourcepath={0};linenumber={1};columnnumber={2};]{3}" -f $_.InvocationInfo.ScriptName, $_.InvocationInfo.ScriptLineNumber, $_.InvocationInfo.OffsetInLine, $_.Exception.Message -replace "`r`n", ". ")
}

关于PowerShell 错误记录为空/不正确 'InvocationInfo',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63797191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com