Reputation: 1547
I am accepting arguments to a script file for ServerName and Share. I want to make sure that the user does not add any leading or trailing forward slashes or backslashes.
Currently, I am doing this...
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
}
But I do not like the way I have to have multiple -replace lines. Is there a cleaner way or simpler way to strip forward and back slashes from a string, if they exist?
Thanks in advance for any help you can offer.
Upvotes: 1
Views: 1640
Reputation: 26
In the past, enter a regex to hold the criteria to be replaced in a variable and then replace each occurrence of that criteria:
$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
Upvotes: 1
Reputation: 174690
You can either chain your -replace
calls:
$a_server = $a_server -replace '\\','' -replace '/',''
Or use a character class to match any of both:
$a_server = $a_server -replace '[\\/]',''
Upvotes: 3