在Powershell 5中,从字符串

时间:2017-07-27 16:52:45

标签: powershell powershell-v4.0

我接受ServerName和Share的脚本文件的参数。我想确保用户不添加任何前导或尾随斜杠或反斜杠。

目前,我正在这样做......

function validateServerShare($a_server, $a_share)
{

    $a_server = $a_server -replace'\\',''
    $a_server = $a_server -replace'/',''
    $a_share = $a_share -replace'\\',''
    $a_share = $a_share -replace'/',''

    $Path = "\\$a_server\$a_share"

    if(-not (Test-Path $Path)) 
    {
        haltError
    }
    return $Path
}

但我不喜欢我必须拥有多个替换线的方式。是否存在更清晰的方法或更简单的方法从字符串中去除正斜杠和反斜杠?

提前感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:2)

您可以链接-replace来电:

$a_server = $a_server -replace '\\','' -replace '/',''

或使用字符类来匹配任何一个:

$a_server = $a_server -replace '[\\/]',''

答案 1 :(得分:1)

过去,输入一个正则表达式来保存要在变量中替换的条件,然后替换该条件的每个匹配项:

$a_server = "\\\sql2016\"
$a_share = "\temp\"

$criteria = "(/|\\*)" --criteria you want to replace


    $a_server = ($a_server -replace $criteria,'')
    $a_share = ($a_share -replace $criteria,'')


    $Path = "\\$a_server\$a_share"
    ## $path is now \\sql2016\temp