Escape $ in powershell - powershell

I use the following to quickly login to RDP:
echo "Connecting to 192.168.1.100"
$Server="192.168.1.100"
$User="Administrator"
$Password="Admin$Password"
cmdkey /generic:TERMSRV/$Server /user:$User /pass:$Password
mstsc /v:$Server
Unfortunately AdminPassword does contain '$' character which breaks the thing. Is there a way to make it work?

Instead of using " " who take $x for a variable. Use ' ' and everything in it will be a character.

You can use the backtick character ` (to the left of the 1 key on US keyboards) to escape special characters - see About Special Characters.
This escapes the dollar sign as well, so your code would become:
$Password="Admin`$Password"

Related

How to get around using apostrophe in double quotes with Powershell

I am working with Powershell. My issue is that my file path (which does not exist on a local computer) has an apostrophe in it. Powershell is seeing this as a single quote, so it is giving me the following error: The string is missing the terminator: '. I thought that I could escape the single quote using a backtick, but that gave me the same error.
The error does not occur when I am doing the first line of code, and I don't even need the backtick for that part. I can even see that the contents of the variable matches up with the file path that I am using. It is only when I am doing the invoke-expression part that it is giving me the error.
I am using https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7, so I don't think the second line of the code is the problem.
My code is listed below:
$code = "\\example\example\John_Doe`'s_Folder\example.ps1"
invoke-expression -command $code
I have also tried wrapping the entire file path in double-quotes and single-quotes, but my program did not like that either. I can't remove the apostrophe as we have over a hundred of systems that are directing to John_Doe's_Folder.
Invoke-Expression should generally be avoided; definitely don't use it to invoke a script or external program.
In your case, simply use &, the call operator to invoke your script via the path stored in variable $code (see this answer for background information), in which case the embedded ' needs no escaping at all:
$code = "\\example\example\John_Doe's_Folder\example.ps1"
& $code
As for what you tried:
"\\example\example\John_Doe`'s_Folder\example.ps1" turns into the following verbatim string content:
\\example\example\John_Doe's_Folder\example.ps1
That is, the ` was removed by PowerShell's parsing of the "..." string literal itself, inside of which ` acts as the escape character; since escape sequence `' has no special meaning, the ` is simply removed.
For the ` to "survive", you need to escape the ` char. itself, which you can do with ``:
"\\example\example\John_Doe``'s_Folder\example.ps1"

Execute Windows Powershell command copy text to clipboard (incl. `r`n ')

I am trying to execute a powershell command to copy text to the windows clipboard including carriage returns and ALL special characters. I can execute the command ok using:
powershell.exe -command Set-Clipboard 'TEXT'
This is not in the powershell console directly so syntax differs.
I was using double quotes around text, substituting carriage returns in original text with `r`n and escaping all other special characters with `
It worked up until I got to a single ' which I understand is used by powershell to mean a literal text string.
So I changed approaches and wrapped un-escaped text in single quotes (except substituting 1 ' for 2 ''). Of course `r`n within the single quoted text are interpreted literally so doesn't work. I have tried stringing them together outside single quoted text like:
'some text here' "`r`n" 'more text here'
This works in the console but not in the command. Tried adding + either side but still does not work.
User "TessellatingHeckler" suggested -EncodedCommand but unfortunately I am unable to produce any version of base 64 encoded strings (to include in the command) which match the same string encoded via the PS console. So that is not going to work.
I have been attempting to simply substitute carriage returns in the original text with an obscure string, wrap the text in single quotes (literal) and then substitute it back to `r`n within PS. I have gotten the substitution to work in the console directly but cannot figure out how to actually send it as a command.
powershell.exe -command Set-Clipboard $Str = 'this is a test--INSERT_CRLF_HERE--1234'; $Car = '--INSERT_CRLF_HERE--'; $clr = "`r`n"; $Str = $Str -replace $Car, $clr
Can the above command be modified to work? Is it possible to achieve the intended outcome without writing to a temp file? It is preferable to be able to use single quoted text blocks as it is more robust and lightweight than trying to escape everything (even spaces) in the original text.
I was informed about a rather tidy solution by Rob Simmers on another forum, which I am currently employing.
Original Text:
Test text
!##$%^&*()_+-=[]\{}|;':",./<>?
String with 5x characters substituted ({ = {{, } = }}, ' = '', crlf = {0}, " = {1}):
Test text{0}!##$%^&*()_+-=[]\{{}}|;'':{1},./<>?
Powershell.exe command:
powershell.exe -command "$str = 'Test text{0}!##$%^&*()_+-=[]\{{}}|;'':{1},./<>?' -f [System.Environment]::NewLine, [Char] 0x22 ; Set-Clipboard $str"
Output (literal text placed on the clipboard) - same as the input, as desired:
Test text
!##$%^&*()_+-=[]\{}|;':",./<>?
As an aside: A fully robust solution that works in any invocation scenario would indeed require use of -EncodedCommand with a string that is the Base64 encoding of the command string's UTF16-LE byte representation - but you've stated that creating such a string is not an option for you.
If you were to call from PowerShell, you could more simply use a script block (see bottom).
Update: The OP's own answer now contains a robust, if nontrivial, solution based on careful string substitutions.
The answer below may still be of interest for simpler scenarios and for background information on quoting requirements and pitfalls.
Using the scenario from your question, this simpler solution should do (verified from cmd.exe - we still don't know where you're calling PowerShell from, but I expect it to work if there's no shell involved):
powershell.exe -command "Set-Clipboard \"this is`r`na test\""
As for other special characters:
' can be embedded as-is - no escaping needed
" requires escaping as `\"
$ as `$, but only if you want it to be treated as a literal (the same escaping that would apply in a regular double-quoted PowerShell string)
If your use case requires passing an arbitrary preexisting string, you'd have to employ string substitution to perform the above escaping - including replacing embedded newlines with literal `r`n.
If there is no shell involved (such as with subprocess.check_output() from Python), the above rules should suffice and make for a robust solution (assuming you only use printable characters and there are no character-encoding issues).
From cmd.exe, however, a fully robust solution that doesn't use -EncodedCommand requires extra, nontrivial work, due to its lack of proper parsing of embedded double quotes:
The following cmd.exe metacharacters typically require ^-escaping, but sometimes the mustn't be escaped:
& | < >
In the following example, & requires ^-escaping:
powershell.exe -command "Set-Clipboard \"this is`r`na ^& test\""
However, if your string also has embedded (and escaped) " chars., whether these characters require^-escaping depends on their placement relative to the embedded "; note how in the following example & need not be ^-escaped and indeed must not be, because the ^ would then become part of the string:
powershell.exe -command "Set-Clipboard \"this is`r`na 3`\" & test\""
Anticipating these variations algorithmically is a nontrivial undertaking.
Additionally, if your string had %...% tokens that look like cmd.exe-style environment variables - e.g., %FOO% - but you want to treat them as literals, the % cannot be escaped.
There is a workaround that may work, but it again depends on the presence and placement of embedded " chars.
In the following example, the "^ disrupter" trick can be used to prevent expansion of %OS%:
powershell.exe -command "Set-Clipboard \"do not expand: %^OS%\""
However, if an embedded " precedes it, the workaround becomes ineffective (the ^ is retained), and there's no direct fix that I know of in this scenario:
powershell.exe -command "Set-Clipboard \"do not expand: 3`\" %^OS%\""
You'd have to split the string into multiple pieces to break the %OS% token apart and concatenate the pieces via a PowerShell expression:
powershell.exe -command "Set-Clipboard (\"do not expand: 3`\" %\" + \"OS%\")"
Algorithmically, you could use placeholder chars. that you then replace as part of the PowerShell command, a technique you've used in your own answer.
As an aside:
Extra escaping would be required if you wanted to execute this from PowerShell:
powershell.exe -command "Set-Clipboard \`"this is`r`na test\`""
However, from PowerShell it's not hard to construct a Base64-encoded string to pass to
-EncodedCommand, but there's an even easier method: use a script block to pass your command; no extra quoting requirements apply in that case, because -EncodedCommand is then automatically used behind the scenes (along with -OutputFormat Xml).
Do note that this only works from within PowerShell.
powershell.exe -command { Set-Clipboard "this is`r`na test" }

How to escape “*” character inside script

We have a powershell script that requires escaping the * character.
PS C:\test> .\jre\bin\java.exe -cp .\test.jar com.test.a123 h256 *
I want to escape above star....
Unable to get any clue in google, any idea on this please?
The generic PowerShell escape character is a grave (`), although I must admit, I can't think of a use case where you would need to escape an asterisk. Remember you can always use string literals too:
#'
String literal here
'#

Searching for backslash in a string with Powershell

I need to search for the amount of backslashes in a string to determine some file path parameters. I have not worked out a way to seach for a backslash without Powershell thinking it is an escapee character.
([regex]::Matches($FilePath, "\" )).count
Or
$a -match "\"
These both come up with an error "Illegal \ at end of pattern"
Thanks!
You can escape a backslash with a backslash:
[Regex]::Matches($FilePath, "\\").Count

How to escape "<" character in password inside PowerShell script

Here's my script:
#rasdial "My VPN" "user#domain" 'my<password'
My password contains < character. This, without # works when entered into PowerShell console.
I know ` is the quoting character, but obviously it doesn't work with <.
My password contains many special characters so it has to be quoted. But it doesn't work when double quotes are used. How to escape the password properly? Is there a way to import it from an external file? BTW, rasphone.exe remembers my password, maybe is there a way to use it?
Here's the solution I found working. I used double quotes instead of single quotes. It didn't work at the first time, because there was also % in my real password, which needed to be quoted with %%.
So, inside .cmd script: 'my%`<password' won't work, but "my%%<password" will.
Can anyone confirm he used string like '...`<...' inside .cmd script and it worked? Does it behave differently in different PowerShell versions? Mine is from Windows 8 x64.
I had a similar issue and it took me a while to get to the bottom of it. In my case I had a password similar to this
}K)/]j..|{?*&%($#7}e$%0>;._#
Putting it in double quotes allows for variable expansion so obviously that wont work.
Putting it in single quotes is supposed to work but didn't for me. Escaping problem characters with the back tick also didnt work for me.
What worked for me was to surround with single quotes first and then double quotes
'"}K)/]j..|{?*&%($#7}e$%0>;._#"'
Have you tried:
'my`<password'
` <--- The tilde key backquote is the Powershell escape character.
I would also encourage using -AsSecureString
Testing in the PS console:
PS C:\Users\Athomsfere> $pw = 'my<password'
PS C:\Users\Athomsfere> write-host $pw
my<password
So its not the character by itself.
It still woks like this too: (As a script)
'#rasdial', "My VPN", "user#domain", 'my<password' |`
ForEach
{
Write-Host $_
}