2015-01-13 54 views
0

如何通过PowerShell脚本验证如果由用户共享名输入c $而没有其他内容?从\\主机名\例如提取共享名C $验证共享名

$sharename = Read-Host "Enter path" 
if ($sharename -eq "c$") 
    { 
    "execute script" 
    } 
else 
    { 
    "ShareName must be c$" 
    } 

回答

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 
+0

非常感谢! – kekimian

+0

您可能希望将'$'添加到模式的末尾。这将防止任何结尾字符。 – iCodez