0

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.

EiEiGuy
  • 1,447
  • 5
  • 18
  • 32

2 Answers2

2

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 '[\\/]',''
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
1

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
MK_007
  • 26
  • 4