$100 = "$env:APPDATA/somthing"
$iamhere = "C:/example"
$100 = $100 -replace "`$env:APPDATA\somthing", "$iamhere"
I want $100
replaced by $iamhere
of its contents (in text form) although I get this error.
Regular expression pattern is not valid: $env:APPDATA\somthing.
At line:1 char:1
$100 = $100 -replace "`$env:APPDATA\somthing", "$iamhere"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: ($env:APPDATA\somthing:String) [], RuntimeException
+ FullyQualifiedErrorId : InvalidRegularExpression
I think this is because I am trying to replace some text with a directory, but I want the text inside the variable of $iamhere
The -replace
operator will parse the input string you provide as a regular expression. The \
character is a special character in regular expressions and so if you want it to be treated literally, you need to escape it by adding a \
in front of it. Fortunately .NET provides a handy function for doing that for you:
# ~> [Regex]::Escape("$env:APPDATA/somthing")
C:\\Users\\username\\AppData\\Roaming/somthing
So just update your example like this:
$100 = $100 -replace [Regex]::Escape("$env:APPDATA/somthing"), $iamhere
Note that you don't need the quotes around $iamhere (but since it's a string, it doesn't make a difference).
you could use *.replace
instead
$100 = "$env:APPDATA/somthing"
$iamhere = "C:/example"
$100 = $100.replace("$env:APPDATA/somthing", "$iamhere")
it won't use regex then
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With