Powershell字符串参数验证 [英] Powershell string parameter validation

查看:463
本文介绍了Powershell字符串参数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与SQL Server相关的powershell脚本,它要求用户只能以这种格式传递一个字符串:machineName \ instanceName。例如,MYMACHINE \MYINST。如果参数不是这种格式,脚本应该显示使用语法。有人可以提供脚本。提前致谢。

/heyscriptingguy/archive/2011/05/15/simplify-your-powershell-script-with-parameter-validation.aspxrel =nofollow>参数验证。在脚本的开始部分放置这样的内容:
$ b

  [CmdletBinding()] 
参数(
[Parameter()]
[ValidateScript({
if($ _ -match'。+ \\。+'){
$ true
$ else $
Write-Host'参数的格式必须为MACHINE \ STATS。'
$ false
}
})]
[string] $实例


I have a powershell script related to SQL Server which requires the user to pass a string only in this format : machineName\instanceName. For eg., MYMACHINE\MYINST. If the argument is not in this format, the script should display the usage syntax. Can someone please provide script. Thanks in advance.

解决方案

You're looking for parameter validation. Put something like this at the beginning of your script:

[CmdletBinding()]
Param(
  [Parameter()]
  [ValidateScript({
    if ($_ -match '.+\\.+') {
      $true
    } else {
      Write-Host 'Parameter must have the form MACHINE\INSTANCE.'
      $false
    }
  })]
  [string]$Instance
)

这篇关于Powershell字符串参数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆