gpt4 book ai didi

powershell - 开关语句未处理

转载 作者:行者123 更新时间:2023-12-02 23:39:55 25 4
gpt4 key购买 nike

我正在尝试使用switch语句控制PowerShell脚本中的流,但是根本没有处理该开关。如果以交互方式运行它(在ISE中高亮显示+ F8),它将正常运行。我验证了该论点,并进行了彻底的测试。 If(){}语句正常处理。 switch语句是否存在某种奇怪的错误?甚至Default参数也不会被触发。

[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[ValidateSet('Install','Uninstall','Verify','Enable','Disable')]
[String]$Switch
)

**FUNCTIONS**

[Int]$R = 324
Start-Transcript 'Path\ESD.log' -Append -Force

Switch ($Switch)
{
"VERIFY" { $R = Verify; Break }
"INSTALL" { $R = Install; Break }
"UNINSTALL" { $R = Uninstall; Break }
"ENABLE" { $R = Enable; Break }
"DISABLE" { $R = Disable; Break }
Default { Write-Host "Unable to match: $Switch" -BackgroundColor Red }
}

Write-Host "Exiting with: $R"
Stop-Transcript
EXIT $R

输出:
PS Path\EnterpriseSiteDiscovery> .\ESD verify
Transcript started, output file is Path\ESD.log
Exiting with: 324
Transcript stopped, output file is Path\ESD.log

PS Path\EnterpriseSiteDiscovery> $LASTEXITCODE
324

日志内容:
**********************
Windows PowerShell transcript start
Start time: 20170705154435
**SYSTEMINFO**
**********************
Transcript started, output file is Path\ESD.log
Exiting with: 324
**********************
Windows PowerShell transcript end
End time: 20170705154436
**********************

最佳答案

It turns out when you are inside a Switch construct, the variable $Switch value is redefined (presumably by the switch construct itself) as an empty variable of type System.Collections.IEnumerator. The value is set to $null. This won’t be a problem if you’re not using a variable with the name $Switch. Unfortunately I was because I was working with a set to Virtual Switches so $Switch seemed like a fair choice of variable name.


  • https://dscottraynsford.wordpress.com/2015/09/08/powershell-dont-of-the-week-switch-in-a-swtich/
  • 关于powershell - 开关语句未处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44934912/

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