【问题标题】:passing cmd line arguments to powershell script - how to exit if no arguements将 cmd 行参数传递给 powershell 脚本 - 如果没有参数如何退出
【发布时间】:2014-07-22 18:02:43
【问题描述】:

到目前为止,我有我的 .ps1 文件

Param([Parameter(Mandatory=$true,ValueFromPipelin=$true)][string[]] $appPoolArray)
$zero = 0
if ($appPoolArray.length -eq $zero){
Write-Output "no app pools where selected"
exit
}
else {
foreach ($elem in $appPoolArray)
$appPool = Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool" | Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$elem"}
$appPool.Recycle()
Write-Output "Recycled."
Start-Sleep -Second 60
}
Write-Output "Done."
}

我想这样做,如果 cmd 行中没有参数,那么它会立即退出,相反,如果我在命令中没有包含参数,它只会要求我继续将元素添加到数组中(命令 I我在 cmd 行中运行的是 powershell -noexit path\script.ps1) 我对 Powershell 或一般脚本不是很好,但我知道错误与 if 语句有关。帮助将不胜感激

编辑:我尝试取出 Write-Mandatory=$True 但现在当我没有通过任何争论时它会给我一个错误

【问题讨论】:

    标签: arrays powershell if-statement cmd powershell-2.0


    【解决方案1】:

    取出Mandatory=$True 并在foreach.. 行的末尾添加一个缺少的大括号。将来使用缩进并格式化您的代码,因为您会发现更容易发现这些错误(或使用 PowerGUI(http://www.quest.com/powergui-freeware) 之类的工具)

    Param([Parameter(ValueFromPipeline=$true)][string[]] $appPoolArray)
        if ($appPoolArray -eq $null){
            Write-Output "no app pools where selected"           
        }
        else {
            foreach ($elem in $appPoolArray){
                $appPool = Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool" | Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$elem"}
                $appPool.Recycle()
                Write-Output "Recycled."
                Start-Sleep -Second 60
            }
        Write-Output "Done."
        }
    

    我将第 2 行更改为 if ($appPoolArray -eq $null){,因为它更清楚地表明了您的意图,但您的原始陈述也可以。

    【讨论】:

    • 谢谢!我尝试取出 Mandatory=$True 但它仍然不起作用,我什至没有意识到我错过了左括号。感谢您的帮助。
    猜你喜欢
    • 2020-11-26
    • 2011-08-01
    • 2022-01-05
    • 1970-01-01
    • 2019-07-07
    • 2020-11-19
    • 2020-09-04
    • 2012-05-05
    相关资源
    最近更新 更多