Escaping dollar signs in PowerShell path is not working - powershell

Why doesn't this work?
$drvrInstFilePath = "$sharePath\$imageName\ISO`$OEM$`$1\RPKTools\RPKDriverInst.bat"
echo $drvrInstFilePath
$drvrInstContent = Get-Content -LiteralPath "$sharePath\$imageName\ISO`$OEM$`$1\RPKTools\RPKDriverInst.bat" | Out-String
The echo shows the right path, but the Get-Content command expands the $oem and $1 to blank strings, even though they are escaped. Why?

Instead of messing around with escaping dollar signs, use single quotes ' instead of double quotes ". It prevents PowerShell expanding $ into a variable. Like so,
$p = "C:\temp\Share\ISO$OEM$"
# Output
C:\temp\Share\ISO$
$p = 'C:\temp\Share\ISO$OEM$'
# Output
C:\temp\Share\ISO$OEM$
If you need to create a path by using variables, consider using Join-Path. Like so,
$s = "Share"
join-path "C:\temp\$s" '\ISO$OEM$'
# Output
C:\temp\Share\ISO$OEM$

You can actually just use a tick mark to escape the $ like so:
`$
Example:
$number = 5
Write-Host "`$${number}"
# Output: $5

You used double quotes with a single backtick. This is an incorrect combination. In fact, I am not sure that a single backtick alone is sufficient in any case. Your successful options to escape the dollar sign ($) in PowerShell are to use double quotes with a backslash-backtick combination ("\`$find"), or instead to use single quotes with a simple backslash ('\$find'). [However, note the exception at the end about function call parameters.] See below for examples.
Also, for those unfamiliar with the distinction, it is important not to confuse the backtick character (`) with the single-quotation character (') in these escapes.
[SUCCESS] Double quotes as container with backslash-backtick as escape:
PS C:\Temp> 'What is $old?' | ForEach-Object {$_ -replace "\`$old", "(New)"}
What is (New)?
PS C:\Temp>
[FAIL] Double quotes as container with backslash-apostrophe as escape:
PS C:\Temp> 'What is $old?' | ForEach-Object {$_ -replace "\'$old", "(New)"}
What is $old?
PS C:\Temp>
[SUCCESS] Single quotes as container with simple backslash as escape:
PS C:\Temp> 'What is $old?' | ForEach-Object {$_ -replace '\$old', "(New)"}
What is (New)?
PS C:\Temp>
[FAIL] Single quotes as container with backslash-backtick as escape:
PS C:\Temp> 'What is $old?' | ForEach-Object {$_ -replace '\`$old', "(New)"}
What is $old?
PS C:\Temp>
Overall, the easiest option may be to use single quotes as the container and a single backslash as the escape: '\$old'
Update: As if the above were not confusing enough, when you use a function call instead of a command, single quotes are needed without an escape. Trying to use an escape on the function call parameter will not work:
[FAIL] Using an escape in a function parameter:
PS C:\Temp> 'What is $old?' | ForEach-Object {$_.ToString().Replace('\$old', "(New)");}
What is $old?
PS C:\Temp>
[SUCCESS] Using plain single quotes without an escape in a function parameter:
PS C:\Temp> 'What is $old?' | ForEach-Object {$_.ToString().Replace('$old', "(New)");}
What is (New)?
PS C:\Temp>

In my case I needed to escape some $'s used in a string but not others that are variables.
For example, my SSRS instance name has a $ sign:
[ReportServer$SSRS]
To escape the $ sign I use single quotes. Otherwise I use the -join statement to concatenate variables with the strings containing actual $ signs.
$sql = -join('ALTER DATABASE [ReportServer$', $instanceName,'TempDB]
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
USE [master]
RESTORE DATABASE [ReportServer$', $instanceName,'TempDB] FROM DISK = N''C:\temp\ReportServerTempDB.BAK'' WITH FILE = 1,
MOVE N''ReportServerTempDB'' TO N''', $sqlDataDrive + "\data_" + $instanceName, '\ReportServer$', $instanceName,'TempDB.mdf'',
MOVE N''ReportServerTempDB_log'' TO N''', $sqlLogDrive + "\log_" + $instanceName, '\ReportServer$', $instanceName,'_TempDBlog.LDF'', NOUNLOAD, REPLACE, RECOVERY, STATS = 5
GO
ALTER DATABASE [ReportServer$', $instanceName,'TempDB]
SET MULTI_USER;
GO
')

Related

Import Certificate using Powershell script: The specified network password is not correct [duplicate]

Simple questions that's been bugging me: In powershell, I can define strings like so:
$s1 = "Boogety boo"
or
$s2 = '.net rocks'
Is there a difference to the interpreter?
Double quotes allow variable expansion while single quotes do not:
PS C:\Users\Administrator> $mycolor="red"
PS C:\Users\Administrator> write-output -inputobject 'My favorite color is $mycolor'
My favorite color is $mycolor
Source: http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences
(I know version 1.0 but the principle is still the same)
This is not trying to be a better answer. Just another way to say it.
The variable expansion between apostrophes and quotes are the same as on UNIX shells (sh, ksh, bash). Using apostrophes will take the character string as-is, without processing any escapes.
PS C:\Users\lit> $x = "`t"
PS C:\Users\lit> $x
PS C:\Users\lit> Write-Output "now${x}is"
now is
PS C:\Users\lit> $x = '`t'
PS C:\Users\lit> $x
`t
PS C:\Users\lit> Write-Output "now${x}is"
now`tis
PS C:\Users\lit> $word = "easy"
PS C:\Users\lit> "PowerShell is $word"
PowerShell is easy
PS C:\Users\lit> 'PowerShell is $word'
PowerShell is $word
This question has a direct answer in the about_Quoting_Rules article of the PowerShell docs:
Double-quoted strings
A string enclosed in double quotation marks is an expandable string. Variable names preceded by a dollar sign ($) are replaced with the variable's value before the string is passed to the command for processing.
For example:
$i = 5
"The value of $i is $i."
The output of this command is:
The value of 5 is 5.
Single-quoted strings
A string enclosed in single-quotation marks is a verbatim string. The string is passed to the command exactly as you type it. No substitution is performed. For example:
$i = 5
'The value of $i is $i.'
The output of this command is:
The value of $i is $i.
In other words, use single quotes if you want your string to remain as written. Use double quotes, if you want to insert variables ($myVariable), results of command executions and other evaluations ($($myList -join ', ')) or special characters (`r, `n, `t, `a, etc.).

add quotation mark to a text file powershell

I need to add the quotation mark to a text file that contains 500 lines text.
The format is inconsistent. It has dashes, dots, numbers, and letters. For example
1527c705-839a-4832-9118-54d4Bd6a0c89
16575getfireshot.com.FireShotCaptureWebpageScreens
3EA2211E.GestetnerDriverUtility
I have tried to code this
$Flist = Get-Content "$home\$user\appfiles\out.txt"
$Flist | %{$_ -replace '^(.*?)', '"'}
I got the result which only added to the beginning of a line.
"Microsoft.WinJS.2.0
The expected result should be
"Microsoft.WinJS.2.0"
How to add quotation-mark to the end of each line as well?
There is no strict need to use a regex (regular expression) in your case (requires PSv4+):
(Get-Content $home\$user\appfiles\out.txt).ForEach({ '"{0}"' -f $_ })
Array method .ForEach() processes each input line via the script block ({ ... }) passed to it.
'"{0}"' -f $_ effectively encloses each input line ($_) in double quotes, via -f, the string-format operator.
If you did want to use a regex:
(Get-Content $home\$user\appfiles\out.txt) -replace '^|$', '"'
Regex ^|$ matches both the start (^) and the end ($) of the input string and replaces both with a " char., effectively enclosing the input string in double quotes.
As for what you tried:
^(.*?)
just matches the very start of the string (^), and nothing else, given that .*? - due to using the non-greedy duplication symbol ? - matches nothing else.
Therefore, replacing what matched with " only placed a " at the start of the input string, not also at the end.
You can use regex to match both:
The beginning of the line ^(.*?)
OR |
The End of the line $
I.e. ^(.*?)|$
$Flist = Get-Content "$home\$user\appfiles\out.txt"
$Flist | %{$_ -replace '^(.*?)|$', '"'}

Powershell strings with double and single quotes [duplicate]

Simple questions that's been bugging me: In powershell, I can define strings like so:
$s1 = "Boogety boo"
or
$s2 = '.net rocks'
Is there a difference to the interpreter?
Double quotes allow variable expansion while single quotes do not:
PS C:\Users\Administrator> $mycolor="red"
PS C:\Users\Administrator> write-output -inputobject 'My favorite color is $mycolor'
My favorite color is $mycolor
Source: http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences
(I know version 1.0 but the principle is still the same)
This is not trying to be a better answer. Just another way to say it.
The variable expansion between apostrophes and quotes are the same as on UNIX shells (sh, ksh, bash). Using apostrophes will take the character string as-is, without processing any escapes.
PS C:\Users\lit> $x = "`t"
PS C:\Users\lit> $x
PS C:\Users\lit> Write-Output "now${x}is"
now is
PS C:\Users\lit> $x = '`t'
PS C:\Users\lit> $x
`t
PS C:\Users\lit> Write-Output "now${x}is"
now`tis
PS C:\Users\lit> $word = "easy"
PS C:\Users\lit> "PowerShell is $word"
PowerShell is easy
PS C:\Users\lit> 'PowerShell is $word'
PowerShell is $word
This question has a direct answer in the about_Quoting_Rules article of the PowerShell docs:
Double-quoted strings
A string enclosed in double quotation marks is an expandable string. Variable names preceded by a dollar sign ($) are replaced with the variable's value before the string is passed to the command for processing.
For example:
$i = 5
"The value of $i is $i."
The output of this command is:
The value of 5 is 5.
Single-quoted strings
A string enclosed in single-quotation marks is a verbatim string. The string is passed to the command exactly as you type it. No substitution is performed. For example:
$i = 5
'The value of $i is $i.'
The output of this command is:
The value of $i is $i.
In other words, use single quotes if you want your string to remain as written. Use double quotes, if you want to insert variables ($myVariable), results of command executions and other evaluations ($($myList -join ', ')) or special characters (`r, `n, `t, `a, etc.).

how to replace string using powershell

I have the following string: $str = '"FirstName":"first name","LastName":"Last name","AskCatalog":false,"Nuteres":61","ZipCode":"1234"'
and I need to replace value of ,for example, FirstName:"first name" with a variable like this
"FirstName":"$strFristname"
Can anyone show me how can I do that in PowerShell?
Thank you.
Like this:
$str -replace '("FirstName":)".*?"', "`$1`"$strFirstname`""
The pattern ("FirstName":)".*?" matches the string "FirstName": followed by a double quote and the shortest match of any character (.*?) up to the next double quote. The parentheses create a group that can be referenced by $1 in the replacement string. Due to the double quotes around the replacement string that reference must be escaped (`$1). The same goes for the nested double quotes (`").
If you want the variable instead of its value to show up in the result, you need to escape the $ of the variable as well:
$str -replace '("FirstName":)".*?"', "`$1`"`$strFirstname`""
Demonstration:
PS C:\> $str = '"FirstName":"first name","LastName":"Last name"'
PS C:\> $strFirstname = 'Joe'
PS C:\> $str -replace '("FirstName":)".*?"', "`$1`"$strFirstname`""
"FirstName":"Joe","LastName":"Last name"
PS C:\> $str -replace '("FirstName":)".*?"', "`$1`"`$strFirstname`""
"FirstName":"$strFirstname","LastName":"Last name"

What's the difference between single quote and double quote to define a string in powershell

Simple questions that's been bugging me: In powershell, I can define strings like so:
$s1 = "Boogety boo"
or
$s2 = '.net rocks'
Is there a difference to the interpreter?
Double quotes allow variable expansion while single quotes do not:
PS C:\Users\Administrator> $mycolor="red"
PS C:\Users\Administrator> write-output -inputobject 'My favorite color is $mycolor'
My favorite color is $mycolor
Source: http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences
(I know version 1.0 but the principle is still the same)
This is not trying to be a better answer. Just another way to say it.
The variable expansion between apostrophes and quotes are the same as on UNIX shells (sh, ksh, bash). Using apostrophes will take the character string as-is, without processing any escapes.
PS C:\Users\lit> $x = "`t"
PS C:\Users\lit> $x
PS C:\Users\lit> Write-Output "now${x}is"
now is
PS C:\Users\lit> $x = '`t'
PS C:\Users\lit> $x
`t
PS C:\Users\lit> Write-Output "now${x}is"
now`tis
PS C:\Users\lit> $word = "easy"
PS C:\Users\lit> "PowerShell is $word"
PowerShell is easy
PS C:\Users\lit> 'PowerShell is $word'
PowerShell is $word
This question has a direct answer in the about_Quoting_Rules article of the PowerShell docs:
Double-quoted strings
A string enclosed in double quotation marks is an expandable string. Variable names preceded by a dollar sign ($) are replaced with the variable's value before the string is passed to the command for processing.
For example:
$i = 5
"The value of $i is $i."
The output of this command is:
The value of 5 is 5.
Single-quoted strings
A string enclosed in single-quotation marks is a verbatim string. The string is passed to the command exactly as you type it. No substitution is performed. For example:
$i = 5
'The value of $i is $i.'
The output of this command is:
The value of $i is $i.
In other words, use single quotes if you want your string to remain as written. Use double quotes, if you want to insert variables ($myVariable), results of command executions and other evaluations ($($myList -join ', ')) or special characters (`r, `n, `t, `a, etc.).