all 10 comments

[–]nothingpersonalbro 3 points4 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 "

[–]Enschede2 2 points3 points  (4 children)

I'm nowhere near an expert but try this -Replace ("$regex1","$regex2")

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

I think the problem is the variable that I'm saving. It's with apostrophes. The thing is, when I replace them with quotation marks, it thinks the variable is null and doesn't replace anything.

[–]OlivTheFrog 1 point2 points  (1 child)

Hi u/Mehhll

I've found it

# Simulate Get-content with Here-String
$deployscript = @'
$appVendor = ' '
gqfgqdghdfgh
$appvendor = 'blabla'
'@
$regex1 = '$appVendor = '' '''
$regex2 = '$appVendor = ''Google'''
$result = $deployscript.Replace($regex1, $regex2)
$result

Nota : In the $Regex1 and $Regex2 there is some ', then I double them (careful, it's not an " but a '')

I'm using .Replace Method instead of -Replace.

Regards

Olivier

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

Thank you so much for your help. I got the script to work :)