如何使用 powershell 脚本调用开关语句中的函数



我使用的PowerShell版本是5.0。我遇到需要使用函数并在 switch 语句中调用它的情况。我的工作涉及做几个操作。

简而言之,我的方案是switch语句的输入是两个 A 和 B。我必须在开关"条件B"中调用在开关"条件 A"中声明的函数,我的意思是执行同一组操作。

例外:

安装程序无法识别为 cmdlet、函数、脚本文件的名称, 或可操作的程序。检查名称的拼写,  CategoryInfo : ObjectNotFound: (regupgrade:String( [], CommandNotFoundException  FullQualifiedErrorId : CommandNotFoundException
$condi = Read-Host -Prompt "Enter the input"
switch ($condi) {
    A {
        function installsw() {
            Write-Host "install necessary sw" 
            install some s/w using "Start-Process" Command 
        }
        installsw
    }
    B {
        Write-Host "s/w upgrade"
        installsw
        $logs = Copy-Item -Path"D:/var" -Destination "D:/Temp"
    }
}

在切换之前定义安装。 除非$condi是"A",否则不会定义 installsw 函数。

顺便说一句,您可以在第一条交换机线路内运行任何管道:

 switch (Read-Host -Prompt "Enter the input") {

最新更新