Powershell string parameter validation

本秂侑毒 提交于 2019-12-13 09:45:13

问题


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.


回答1:


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
)


来源:https://stackoverflow.com/questions/24652484/powershell-string-parameter-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!