Powershell字符串参数验证(Powershell string parameter validation)

其他开发 IT屋
问 题

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
)

本文地址:IT屋 » Powershell string parameter validation

问 题

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

/heyscriptingguy/archive/2011/05/15/simplify-your-powershell-script-with-parameter-validation.aspx“rel =”nofollow“>参数验证。在脚本的开始部分放置这样的内容:
$ b
  [CmdletBinding()] 
参数(
[Parameter()]
[ValidateScript({
if($ _ -match'。+ \\。+'){
$ true
$ else $
Write-Host'参数的格式必须为MACHINE \ STATS。'
$ false
}
})]
[string] $实例


本文地址:IT屋 » Powershell字符串参数验证