【问题标题】:How to call a function in a Switch Statement using powershell script如何使用 powershell 脚本在 Switch 语句中调用函数
【发布时间】:2019-08-06 14:38:59
【问题描述】:

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

简而言之,我的场景是switch语句的输入是两个A和B。我必须在switch“conditionB”中调用在switch“condition A”中声明的函数,我的意思是执行同一组操作.

例外:

installsw 未被识别为 cmdlet、函数、脚本文件的名称, 或可运行的程序。检查名字的拼写, CategoryInfo : ObjectNotFound: (regupgrade:String) [], CommandNotFoundException fullyQualifiedErrorId: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"
    }
}

【问题讨论】:

    标签: function switch-statement powershell-5.0


    【解决方案1】:

    在切换之前定义 installsw。除非 $condi 为 'A',否则不会定义 installsw 函数。

    顺便说一句,您可以在第一条开关线内运行任何管道:

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

    【讨论】:

    • 你好@js2010,你说要声明为全局函数,所以可以随时调用。
    • 是的,或者至少在同一个脚本中。除非 $condi 是 'A',否则它不会被定义。
    • 嗨@js2010 是否可以在开关条件A中创建函数并再次将其用于条件B?
    • 如果你真的想,你可以在这两种情况下定义它。
    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2019-08-04
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多