SoFunction
Updated on 2025-03-10

Methods for directly outputting escaped characters or variable names in PowerShell

This article introduces how to prevent a part of a string from being escaped or part of a character is treated as a variable in a PowerShell string, that is, let all characters in the string be output as it is.

In PowerShell, escape characters are some special characters starting with characters (·), which can be used to implement functions such as line breaks and TAB. The variable starts with a symbol ($) and represents a value. In previous articles, we introduced escape characters and also introduced the inclusion of variables in strings. Interested friends can learn about it.

In PowerShell, you can use a pair of double quotes to cause a string, or a pair of single quotes to cause a string. The biggest difference between single quotes and double quotes is that a string caused by double quotes is called an extensible string, while a string caused by single quotes is called a literal string. That is, strings caused by single quotes, whether they appear with escaped characters or variables, will be ignored, and everything will be displayed literally.

Copy the codeThe code is as follows:

PS C:\Users\spaybow> $p="PowerShell"
PS C:\Users\spaybow> $str="Hello`t$p"
PS C:\Users\spaybow> $str1='Hello`t$p'
PS C:\Users\spaybow> $str
Hello   PowerShell
PS C:\Users\spaybow> $str1
Hello`t$p

The above example clearly shows the difference between single quotes and double quotes. `t is an escape string representing the TAB key and $p is a string with a value of PowerShell.
When using double quotes to assign, the result of $str is "Hello   PowerShell", and when using single quotes to assign, the result of output is "Hello`t$p".

By assigning values ​​to a string using single quotes, we can forbid the string from containing uncertainties such as escaped characters or variables, thus obtaining a fixed string.

This article introduces so much about forbidden strings to include escaped characters or variables. I hope it will be helpful to you, thank you!