Powershell string parameter validation

2019-09-25 07:07发布

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条回答
迷人小祖宗
2楼-- · 2019-09-25 07:31

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
)
查看更多
登录 后发表回答