0

I have a powershell script that has an input parameter of $OutputFolder

An example value of $OutputFolder is '\\\\SHD-D-EDIAPP01\\H2FileRepository\\Dev\\CommonDev\\reports\\HRF605\\'

This is fine for use in JSON to pass to a web service call.

I'm keen to output the folder path in a write-host command that displays the value but with the \\ replaced by \

I have tried this (but it doesn't work):

$myOutputFolder = $OutputFolder
$myOutputFolder.Replace("\\\\","\\")
write-host "Parameter OutputFolder is ..... : $myOutputFolder"

Any help/guidance/suggestions most appreciated. If I work out a solution I will reply to own question.

Allan F
  • 2,110
  • 1
  • 24
  • 29

2 Answers2

1

This seems to work:

$myOutputFolder = $OutputFolder.Replace("\\","\")
write-host "Parameter OutputFolder is ..... : $OutputFolder"
write-host "Parameter OutputFolder calc ... : $myOutputFolder"
Allan F
  • 2,110
  • 1
  • 24
  • 29
  • 2
    Yes that’s a string replace. The -replace uses regex so you need to escape the backslash with a backslash. That means for 2 you need another 2 for escaping both. -replace ‘\\\\’,’\’ – Doug Maurer Dec 01 '20 at 06:06
1

I guess that somewhere along the line the script that outputs the $OutputFolder is misbehaving and directly peeking in a serialized Json file.

General rule:

Don't peek and/or poke directly in serialized files (as e.g. Json or XML files) using string methods (such as Select-String and .Replace), instead use the related parsers (e.g. [XML]$MyXML) and/or cmdlets (e.g. ConvertFrom $MyJson)

What's the catch?

In this case, there is a potential pitfall that there are other escaped characters (with a backslash).
Your sample path:

'\\SHD-D-EDIAPP01\H2FileRepository\Dev\CommonDev\reports\HRF605\' | ConvertTo-Json
"\\\\SHD-D-EDIAPP01\\H2FileRepository\\Dev\\CommonDev\\reports\\HRF605\\"

Although very unlikely in a in a path, Json string values could contain other escaped characters:

'Hello
"World"' | ConvertTo-Json
"Hello\n\"World\""

In other words, to un-escape your Json string, you better do this:

$OutputFolder = '\\\\SHD-D-EDIAPP01\\H2FileRepository\\Dev\\CommonDev\\reports\\HRF605\\'
("{""Value"":""$OutputFolder""}" | ConvertFrom-Json).Value
\\SHD-D-EDIAPP01\H2FileRepository\Dev\CommonDev\reports\HRF605\

Or just use ConvertFrom-Json from the start (in your script that has an input parameter of $OutputFolder).

iRon
  • 20,463
  • 10
  • 53
  • 79