如何抑制用户在没有参数参数的情况下调用我的powershell脚本时发生的错误

时间:2013-01-24 22:14:12

标签: powershell parameters arguments parameter-passing powershell-v2.0

例如,我的脚本可以像这样调用:

.\MyScript.ps1 -s <hostname1>

如果我在没有使用-s参数传递参数的情况下调用它,则会收到错误:

.\MyScript.ps1 -s

C:\MyScript.ps1 : Missing an argument for parameter 'sql'. Specify a pa
rameter of type 'System.String' and try again.
At line:1 char:18
+ .\MyScript.ps1 -s <<<<
    + CategoryInfo          : InvalidArgument: (:) [MyScript.ps1],     ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,MyScript.ps1

有没有办法来抑制此错误,或者出现自定义错误:

.\MyScript.ps1 -s

Please pass a hostname with the s argument:
.\MyScript.ps1 -s <hostname>

5 个答案:

答案 0 :(得分:1)

你可以做两件事中的一件。

将参数标记为必填参数,然后powershell将自动向用户查询:

PARAM(  [Parameter(Mandatory=$true)][string]$sql )
PROCESS
{
    "You entered: " + $sql
}

给出:

# C:\Temp> .\prompt.ps1 
cmdlet prompt.ps1 at command pipeline position 1
Supply values for the following parameters:
sql: asdsaa
You entered: asdsaa

或者您可以提供表达式作为查询用户输入的默认参数:

PARAM(  [string]$sql = (read-host "Enter a value for sql parameter") )

PROCESS
{
    "You entered: " + $sql
}

给出:

# C:\Temp> .\prompt.ps1 
Enter a value for sql parameter: hello
You entered: hello

修改

回应你的评论。我能想到的唯一可以获得所需行为的解决方法是不指定参数并自行处理$ args参数。或者您可以使用一个hack来推动作业将参数解析为单独的函数,然后捕获调用该函数时可能发生的任何错误。所以,你的脚本看起来像这样:

function parsePrompt ( [string]$sql)
{
    $sql
}

$cmd = "parsePrompt $($args -join " ")"
try
{
    $sql = invoke-expression $cmd
}
catch [System.Management.Automation.ParameterBindingException]
{
    $sql = read-host "Enter a value for sql parameter"
}
"You entered: " + $sql

给出:

# C:\Temp> .\Prompt.ps1 -s
Enter a value for sql parameter: dsfds
You entered: dsfds


# C:\Temp> .\Prompt.ps1 -s dfds
You entered: dfds

答案 1 :(得分:0)

您可以尝试使用陷阱处理程序在未传递参数时提供自定义消息,然后从那里继续。陷阱处理程序适用于当前作用域,因此您只需在脚本顶部定义它以处理错误。

e.g:

trap [ArgumentException] {
    write-host "Please pass a hostname with the s argument"
    break
}

您还可以通过设置

告诉PowerShell在此脚本中发生错误时不要发出警告

$ErrorActionPreference = SilentlyContinue

这将使PowerShell悄悄地抑制错误并尝试继续执行脚本。但是,由于显而易见的原因,抑制错误可能不是最佳选择。

答案 2 :(得分:0)

Param([参数(强制= $ true,helpmessage =“你傻山羊。”)] $ SQL)

原谅手机上的简洁;)

答案 3 :(得分:0)

如果我读了你的意图你想要错误,而不是提示......所以:

# MyScript
param (
    $sql = $(throw @"
    Oops!
    Dude, this script requires SQL parameter!
    Run it like that: .\MyScript -s <hostname>
"@)
)
    "Got $sql"
}

您可以使用v1“必需”参数。

答案 4 :(得分:0)

一种简单的MyScript.ps1方法:

Param( [switch]$sql, [string]$_ValueSql )
if ($_ValueSql){​​​​​​​
    [String]$sql=$_ValueSql
}​​​​​​​ else {​​​​​​​
    [String]$sql=""
}​​​​​​​
"sql=$sql"


Results:

.\MyScript.ps1
sql=

.\MyScript.ps1 -s
sql=

.\MyScript.ps1 -s abcd
sql=abcd