gpt4 book ai didi

powershell - Set-PSDebug -Trace 2导致我的powershell代码抛出了一个错误,如果不进行跟踪就不会发生

转载 作者:行者123 更新时间:2023-12-02 23:59:31 38 4
gpt4 key购买 nike

想象一个脚本test.ps1,如下所示:

Param (
[ValidateNotNullOrEmpty()]
$VMHost,

[switch]
$trace
)

$ErrorActionPreference = "Stop"
Set-StrictMode -Version 2

trap {
Set-PSDebug -Trace 0
$_.InvocationInfo
break
}

if ($trace) {
Set-PSDebug -Trace 2
}

if ($VMHost) {
$VMHost = @(@($VMHost) | % {
$h = $_
Switch ($h.GetType().Name) {
'String' {
"isastring"
}
default {
Write-Error -Category InvalidType -TargetObject $h -ErrorAction Stop -Message 'VMHost argument must be a String or a VMHost object.'
}
}
})
}

正常运行时,它会执行以下操作:
PS> & .\test.ps1 -VMHost "foo"
foo

当使用 -trace参数运行时,它将执行以下操作:
PS> & .\test.ps1 -VMHost "foo" -trace
DEBUG: 21+ if ( >>>> $VMHost) {
DEBUG: 22+ >>>> $VMHost = @(@($VMHost) | % {
DEBUG: 22+ $VMHost = @( >>>> @($VMHost) | % {
DEBUG: 22+ $VMHost = @(@( >>>> $VMHost) | % {
DEBUG: 22+ $VMHost = @(@($VMHost) | % >>>> {
DEBUG: ! CALL function '<ScriptBlock>' (defined in file 'path...\test.ps1')
DEBUG: 23+ >>>> $h = $_
DEBUG: ! SET $h = 'foo'.
DEBUG: ! SET $switch = 'String'.
DEBUG: 24+ Switch ( >>>> $h.GetType().Name) {
DEBUG: ! SET $switch = ''.
DEBUG: 35+ >>>> })
DEBUG: ! SET $VMHost = ''.
DEBUG: 13+ >>>> Set-PSDebug -Trace 0
DEBUG: ! CALL function '<ScriptBlock><trap>' (defined in file
'path...\test.ps1')


MyCommand :
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 23
OffsetInLine : 19
HistoryId : -1
ScriptName : path...\test.ps1
Line : $VMHost = @(@($VMHost) | % {

PositionMessage : At path...\test.ps1:23 char:19
+ $VMHost = @(@($VMHost) | % {
+ ~~~~~~~
PSScriptRoot : C:\Users\ereisner\TenableAppliancePackaging
PSCommandPath : C:\Users\ereisner\TenableAppliancePackaging\test.ps1
InvocationName :
PipelineLength : 0
PipelinePosition : 0
ExpectingInput : False
CommandOrigin : Internal
DisplayScriptPosition :

The variable cannot be validated because the value System.Object[] is not a valid value for the VMHost variable.
At path...\test.ps1:22 char:19
+ $VMHost = @(@($VMHost) | % {
+ ~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ValidateSetFailure

跟踪调试如何导致这样的错误?

powershell在这里做什么?

可以清楚地重写此过滤器/分配以避免此问题(错误吗?)?

Powershell版本信息:
PS> $PSVersionTable
Name Value
---- -----
PSVersion 3.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.42000
BuildVersion 6.2.9200.16481
PSCompatibleVersions {1.0, 2.0, 3.0}
PSRemotingProtocolVersion 2.2

最佳答案

没有完整的答案,但看来这是Powershell版本3的错误。

问题似乎在于在这种情况下switch的行为方式。它似乎在给定的单个字符串参数的末尾“循环”了一个。

在PS 4下运行的相同代码按预期工作。

关于powershell - Set-PSDebug -Trace 2导致我的powershell代码抛出了一个错误,如果不进行跟踪就不会发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33875618/

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