在 Powershell 5 中,从字符串中解析正斜杠和反斜杠的最佳方法是什么
In Powershell 5 what is the best way to parse forward slash and backslash from a string
我正在接受 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
}
但我不喜欢必须有多个 -replace 行的方式。是否有更简洁的方法或更简单的方法来从字符串中去除正斜杠和反斜杠(如果存在)?
在此先感谢您提供的任何帮助。
您可以链接您的 -replace
调用:
$a_server = $a_server -replace '\','' -replace '/',''
或者使用一个字符class来匹配两者中的任何一个:
$a_server = $a_server -replace '[\/]',''
过去,输入正则表达式以将要替换的条件保存在变量中,然后替换该条件的每个匹配项:
$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
我正在接受 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
}
但我不喜欢必须有多个 -replace 行的方式。是否有更简洁的方法或更简单的方法来从字符串中去除正斜杠和反斜杠(如果存在)?
在此先感谢您提供的任何帮助。
您可以链接您的 -replace
调用:
$a_server = $a_server -replace '\','' -replace '/',''
或者使用一个字符class来匹配两者中的任何一个:
$a_server = $a_server -replace '[\/]',''
过去,输入正则表达式以将要替换的条件保存在变量中,然后替换该条件的每个匹配项:
$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