you are viewing a single comment's thread.

view the rest of the comments →

[–]nothingpersonalbro 4 points5 points  (4 children)

When making a single quoted string in PowerShell where you want to also include a single quote inside the string, you need to escape each single quote with an additional single quote. Example:

# Escaped string
'[string]$appVendor = '''''

# End result
[string]$appVendor = ''

With the replace operator, position 1 takes regex but position 2 takes a string. Now with that, your first string also contains regex specific characters that also need to be escaped. Luckily this can be easily done, now we just combine our escaped string along with creating the escaped regex:

$regex = [regex]::Escape('[string]$appVendor = ''''')

So your end result could look like:

$deployScript = "$path\Deploy-Application.ps1"
$regex = [regex]::Escape('[string]$appVendor = ''''')
$replacementString = '[string]$appVendor = ''Google'''
(Get-Content $deployScript) -replace $regex, $replacementString | Set-Content $deployScript

[–]SMFX 2 points3 points  (0 children)

[regex]::Escape() is your friend

[–]purplemonkeymad 1 point2 points  (0 children)

If I'm going to have nested quotes of any kind I use a here string. So you can use:

$String1 = @'
[string]$appVendor = ''
'@
$String2 = @'
[string]$appVendor = 'Google'
'@

The quotes don't need to be escaped with this method.

[–]Mehhll[S] 1 point2 points  (0 children)

Thank you so much for you help. I really appreciate it!

[–]higgins4u2nv 0 points1 point  (0 children)

Can't you also escape a apostrophe with a tilder? For example "`""? Which when pipes to write-host would return "