简体   繁体   English

将cmd行参数传递给powershell脚本-如果没有争论,如何退出

[英]passing cmd line arguments to powershell script - how to exit if no arguements

So far I have my .ps1 file with this 到目前为止,我已经有了我的.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."
}

I would like to make it so if there is no arguments in the cmd line then it exits right away, instead it just asks me to keep adding elements into the array if I did not include arguements in the command (The command I am running in cmd line is powershell -noexit path\\script.ps1) I'm not very good with Powershell or scripts in general but I know the error is with the if statement. 我想这样做,以便如果cmd行中没有参数,那么它会立即退出,相反,如果我在命令中未包含任何争论(我正在运行的命令),它只是要求我继续向数组中添加元素cmd行是powershell -noexit path \\ script.ps1)一般来说,我对Powershell或脚本不太满意,但我知道错误在于if语句。 Help would be appreciated 帮助将不胜感激

Edit: I tried taking out the Write-Mandatory=$True but it now gives me an error when I dont pass any arguements 编辑:我试图取出Write-Mandatory = $ True,但是当我不通过任何争论时,它现在给我一个错误

Take out Mandatory=$True and add a missing brace at the end of foreach.. line. 取出Mandatory=$True并在foreach..行的末尾添加一个缺少的括号。 In the future use indents and format your code as you will find it easier to spot these errors(or use a tool like PowerGUI( http://www.quest.com/powergui-freeware )) 将来使用缩进并格式化代码,因为您会发现这些错误更容易(或使用类似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."
    }

I changed 2nd line to if ($appPoolArray -eq $null){ as it shows your intentions more clearly but your original statement will work too. 我将第二行更改为if ($appPoolArray -eq $null){因为它可以更清楚地显示您的意图,但您的原始语句也可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM