I have a PS Profile that I'd like to share with some other users, and ideally it will send them to their home directories automatically on loading. However, I've noticed that users like to change the name of the home variable to suit their preferences (Fair enough).
Due to this, I've added a RegEx pattern to the end of the Profile that selects this profile line and extracts the path defined for that variable regardless of the variable name. It looks like this:
$profileHome = gc $PSCommandPath
If ($profileHome[7] -notMatch '\s*# *\$' -and $profileHome[7] -match '\$\w \s*=\s*['"]?[A-Z]:[\\/]\w ' ) {...}
This way I can forcibly send them to their directory no matter the variable name, if that variable is set to a sensible path.
Unfortunately, I've tested the RegEx on the command line, and everything works except for the ['"] pattern, which I cannot seem to escape.
I'm aware of this similar post, but unfortunately I wasn't able to get its solutions to work. I've tried various alternatives:
[`'"]
[\`'"]
[\[char\]0x27"]
[[char]0x27"]
And a few other variations that look too silly to type here.
This can be tested via:
PS>"`$home = 'C:/users'`r`ntest" > test.ps1
PS>$test = gc test.ps1
PS>If ($test[0] -match '\$\w \s*=\s*.?[A-Z]:[\\/]\w ' ) {echo 'hello'}
PS>hello
PS>If ($test[0] -match '\$\w \s*=\s*[`'"]?[A-Z]:[\\/]\w ' ) {echo 'hello'}
#This command is line wrapped into:
PS>If ($test[0] -match '\$\w \s*=\s*[`'
>> "]?[A-Z]:[\\/]\w ' ) {echo 'hello'}
In the successful echo above, I replace the ' with a . to accept any character. In the second attempt, I leave the ' in, and I am unable to escape it. After some testing, I noticed it's possible by wrapping the statement in double quotes " " and using ['`"], where apparently `" is correctly escaped. This is a reasonable workaround, but I'm still curious if it's the only way.
Question: Is it not possible to escape the ' character for a RegEx wrapped in ' '?
PS(5.1.19041)
CodePudding user response:
Some examples of string quoting and using '
in the regex:
# All of these should match and return True
$single_quote = "'"
$single_quote -match "'" # using double quote
$single_quote -match '''' # doubling single quote
$single_quote -match @"
'
"@ # double-quoted here-string
$single_quote -match @'
'
'@ # single-quoted here-string
$single_quote -match '\x27' # using character code