如何在没有给出参数的情况下在powershell中显示Get-Help

时间:2015-09-29 16:44:39

标签: powershell

好的,我试着四处寻找并弄清楚如何做到这一点,但无法弄明白。这就是我想要做的。

# Run script normally
.\myscript.ps1 "blah" "yo" 

这些应该做同样的事情

Get-Help .\myscript.ps1
.\myscript.ps1

我希望能够使用Get-Help语法,但不想使用参数switch语句在某处重复它。如果在其他地方已经回答了这个问题,请随时指出我。

2 个答案:

答案 0 :(得分:3)

您可以将以下代码添加到脚本的顶部:

if($args.Count -eq 0) {
    Get-Help $MyInvocation.MyCommand.Definition
    return
}

答案 1 :(得分:1)

$ PSBoundParameters.Values.Count将为您提供在脚本中使用param()时传递的参数计数。然后,您可以使用$ args查找这些参数之外的其他任何输入内容。因此,如果您在使用param时都对它们进行了测试,则可以获得帮助响应。

示例参数test.ps1

param([string]$val1,$val2,[switch]$val3)
if ( $PSBoundParameters.Values.Count -eq 0 -and $args.count -eq 0 ) {
    Get-Help $MyInvocation.MyCommand.Definition
    return 
    }
if ( $PSBoundParameters.Values.Count -eq 0 ){ 
    Write-Output ("No parameters passed")     
    return
    }
else {     write-output("val1=$val1 val2=$val2 val3=$val3") }
if ( $args -and $args.count -gt 0 ) {
    Write-Output ("Found Args $args")  }
if ( $PSBoundParameters.Values.Count -eq 0 -and  $args -and $args.count -eq 0

示例输出

powershell-文件parametertest.ps1

parametertest.ps1 [[-val1] <字符串>] [[-val2] <对象>] [-val3]

powershell-文件parametertest.ps1 sometest 123

val1 =最重要的val2 = 123 val3 =假

powershell-文件parametertest.ps1 -val1内容-val2 123 -val3

val1 =东西val2 = 123 val3 =真

powershell-文件parametertest.ps1-未知参数

未传递参数

找到了Args-未知参数