Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping dollar signs in PowerShell path is not working

Tags:

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?

like image 930
Belac Avatar asked Jul 03 '13 15:07

Belac


People also ask

What does $? Mean in PowerShell?

$? Contains the execution status of the last command. It contains True if the last command succeeded and False if it failed. For cmdlets and advanced functions that are run at multiple stages in a pipeline, for example in both process and end blocks, calling this.

How does $_ work in PowerShell?

The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.

How do you escape a backslash in PowerShell?

Can you give us a bit more details about your code? (To escape the backslash you need to use double backslash : "\\" instead of "\".)


Video Answer


2 Answers

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$ 
like image 78
vonPryz Avatar answered Sep 21 '22 18:09

vonPryz


You can actually just use a tick mark to escape the $ like so:

`$ 

Example:

$number = 5 Write-Host "`$${number}" # Output: $5 
like image 44
barak m. Avatar answered Sep 20 '22 18:09

barak m.