我遇到一个奇怪的问题,在设置“Set-PSDebug -Trace 2”时我会遇到不同的行为。
我追溯到一个没有正确执行的switch语句,并且能够在Powershell V3上重现它,但不能在Powershell V2或Powershell V1上重现(按预期工作)
采用以下简单功能:
function DoTest {
$result = "Switch Case Not Executed"
$VendorName = "Microsoft"
switch ($VendorName)
{
"Microsoft" { $result = "Switch Case Executed" }
}
Write-host "Switch: $($VendorName) -> $result"
}
现在运行以下命令:
#Works as expected
Set-PSDebug -Off; DoTest;
#Doesn't work as expected
Set-PSDebug -Trace 2; DoTest;
使用PSDebug Trace的PosH V3的结果
DEBUG: 3+ Set-PSDebug -Trace 2; >>>> DoTest;
DEBUG: 1+ function DoTest >>>> {
DEBUG: ! CALL function 'DoTest'
DEBUG: 2+ >>>> $result = "Switch Case Not Executed"
DEBUG: ! SET $result = 'Switch Case Not Executed'.
DEBUG: 3+ >>>> $VendorName = "Microsoft"
DEBUG: ! SET $VendorName = 'Microsoft'.
DEBUG: ! SET $switch = 'Microsoft'.
DEBUG: 4+ switch ( >>>> $VendorName)
DEBUG: ! SET $switch = ''.
DEBUG: 9+ >>>> Write-host "Switch: $($VendorName) -> $result"
DEBUG: 9+ Write-host "Switch: $( >>>> $VendorName) -> $result"
Switch: Microsoft -> Switch Case Not Executed
DEBUG: 11+ >>>> }
在PoSH版本3中,即使是调试跟踪也表明该值已设置,但它似乎完全跳过了switch语句。我甚至试过了Set-StrictMode
,一切都运行良好。只有当我启用PSDebug跟踪时才会这样。这种行为是否打算?
答案 0 :(得分:2)
经过详尽的调查后,它似乎是Powershell中的一个错误。 $switch
变量在调试模式下被破坏,最终成为某种数组枚举器,在空数组或类似的东西上。我建议在http://connect.microsoft.com
解决方法1:
# Pro: No scoping differences between if statement blocks and function
# Con: big piles of If ... else if ... else if ... can get really annoying to code and maintain
# Con: Statements are limited to single execution, pipeline is lifted to function level instead of statement level
... same code as before but using an if instead of switch ...
if($VendorName = 'Microsoft') { $result = "Switch Case Executed" }
else { $result = "FAIL!" }
解决方法2:
# Pro: Each script block is self-contained and has private scope
# Pro: "cases" can be added without modifying DoIt function, and even passed into the function
# Pro: "cases" can be used in a pipeline
# Con: Indirect script blocks can be difficult to understand at first
function DoTest {
$result = "Switch Case Not Executed"
$VendorName = "Microsoft"
$SwitchHack = @{
Microsoft = { "Microsoft Case Executed" }
Default = { "Default Case Executed" }
}
if($SwitchHack.Keys -contains $VendorName) {
$result = $SwitchHack."$VendorName".InvokeReturnAsIs()
} else {
$result = $SwitchHack.Default.InvokeReturnAsIs()
}
'Switch: {0} -> {1}' -f $VendorName, $result | Write-Host
}
Set-PSDebug -Trace 2
DoTest
因为我很无聊,我写了一个解决方法3,只有2,Switch转移到一个函数
function Switch-Object {
param(
[Parameter(Mandatory=$true)]
[String]$In,
[Parameter(Mandatory=$true)]
[hashtable]$Actions
)
try {
$Actions."$In".InvokeReturnAsIs()
}
catch {
throw "Unknown Action Label"
}
}
function DoTest {
$result = "Switch Case Not Executed"
$VendorName = "Microsoft"
$VendorActions = @{
Microsoft = { "Microsoft Case Executed" }
}
$result = Switch-Object -On:$VendorName -Actions:$VendorActions
'Switch: {0} -> {1}' -f $VendorName, $result | Write-Host
}
Set-PSDebug -Trace 2
DoTest