Powershell 的基础使用II 双引号与单引号以及特殊处理

Powershell 的基础使用II 双引号与单引号以及特殊处理

前言

这里是相关基础知识的双引号与单引号以及特殊处理篇.

基本设计

见官方

基本分为模板形式(可扩展)与固定模式(逐字字符串).

用例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$a
Write-Host "$($null -eq $a)" # True
$a = "123"
Write-Host $a # 123
$a += "4"
Write-Host $a # 1234
# $ a= "$a5" # 错误
Write-Host "${a}5" # 12345
Write-Host "$($a)6" # 12346
Write-Host "$a 7" # 1234 7
Write-Host "$a_8"
Write-Host ("" -eq "$a_8")
Write-Host "`$a:$a" # $a:1234


Write-Host '>>>>>>>>>>>>>>>>>>>>>>>>'
$b = '11'
Write-Host $b # 1111
$b += '21' # 1121
Write-Host $b
$b += '$b'
Write-Host $b # 1121$b

# 打印 bc"d (双引号与单引号/特殊字符)
Write-Host '>>>>>>>>>>>>>>>>>>>>>>>>'
Write-Host 'abc"d'
Write-Host "abc""d"
Write-Host "abc`"d"

# 打印 abc'd (双引号与单引号/特殊字符)
Write-Host '>>>>>>>>>>>>>>>>>>>>>>>>'
Write-Host 'abc''d'

# 打印 abc`d (双引号与单引号/特殊字符)
Write-Host '>>>>>>>>>>>>>>>>>>>>>>>>'
Write-Host 'abc`d'
Write-Host "abc``d"

一些小结

  • 字符串可以使用 + 连结
  • '对包裹的字符串不参与任何处理
  • "对包裹的字符串
    • 涉及运算需要用 $()包裹, 内多层使用 ()包裹
    • 特殊字符需要使用符号 ` 转义
    • 如果需要输出 `** 本身, 需要两个 **` 符号
    • 如果需要输出 " 本身, 需要两个 " 符号, 或者使用 `"
  • '对包裹的字符串
    • 如果需要输出 ' 本身, 需要两个 ' 符号

Here-string

类似于模板语法

语法规则

1
2
3
@"<Enter>
<string> [string] ...<Enter>
"@

1
2
3
@'<Enter>
<string> [string] ...<Enter>
'@

见官方 另见

用例1

1
2
3
4
5
6
@"
first line: symbo `` is taken account, but ' and " is not, `" or `' is acceptable and here is double "" not single
second line: is blank`nthird line: and then a new line
last: ${env:PUBLIC} is also taken account
btw: your timezone is $((Get-TimeZone).DisplayName)
"@

输出为:

1
2
3
4
5
first line: symbo ` is taken account, but ' and " is not, " or ' is acceptable and here is double "" not single
second line: is blank
third line: and then a new line
last: C:\Users\Public is also taken account
btw: your timezone is (UTC+08:00) 北京,重庆,香港特别行政区,乌鲁木齐

用例2

1
2
3
4
5
6
@'
first line: symbo ``, ' and " is not taken account, neither `" nor `' but here is double "" / '' not single
second line: is not blank`nthird line: is in fact second line
last: ${env:PUBLIC} is used to get public foldeer
btw: $((Get-TimeZone).DisplayName) is used to get TimeZone
'@

输出为:

1
2
3
4
5
6
@'
first line: symbo ``, ' and " is not taken account, neither `" nor `' but here is double "" / '' not single
second line: is not blank`nthird line: is in fact second line
last: ${env:PUBLIC} is used to get public foldeer
btw: $((Get-TimeZone).DisplayName) is used to get TimeZone
'@

一些小结

  • 使用双引号@"
    • 换行遵循书写输出
    • 符号 保持不变
    • 转义符 ` 按照其在普通双引号字符串的规则发挥作用
    • 诸如 $()${} 等语法按照其在普通双引号字符串的规则发挥作用
  • 使用单引号@'
    • 换行遵循书写输出
    • 所有内容不参与处理