验证共享名称

时间:2015-01-13 18:13:27

标签: regex powershell

如果用户共享名称输入的是c $且没有其他内容,我如何验证powershell脚本?例如,从\\ hostname \ c $

中提取共享名称
$sharename = Read-Host "Enter path"
if ( $sharename -eq "c$")
  {
    "execute script"
  }
else 
  {
    "ShareName must be c$"
  }

1 个答案:

答案 0 :(得分:1)

使用-match运算符表示正则表达式,或-like表示通配符,如此,

if ( $sharename -match "\\\\\w+\\c\$") {
    "execute script"
  }

正则表达式是这样构建的,

\\ -> \
\\ -> \
\w+ -> at least one word character
\\ -> \
c  -> letter 'c'
\$ -> dollar sign

测试用例

$sharename = '\\nomatter\c$'
$sharename -match "\\\\\w+\\c\$"
True


$sharename = '\\nomatter\C$'
$sharename -match "\\\\\w+\\c\$"
True


$sharename = '\\nomatter\d$'
$sharename -match "\\\\\w+\\c\$"
False

$sharename = '\\nomatter\cee$'
$sharename -match "\\\\\w+\\c\$"
False