Strings.ps1
1<#
2.SYNOPSIS
3 PowerShell strings
4.DESCRIPTION
5 Things to know about PowerShell strings
6#>
7
8'We can write a literal within single quotes'
9
10'If we want to include an apostrophe in it''s string, just use two single quotes'
11
12"If we use double quotes, we can include variables. I swear this is $true"
13
14"We can also include expressions. Like everyone knows two plus two is $(2 + 2)"
15
16@'
17If we don't want to escape quotes, we can use a "here-string".
18
19These start with @' and end with '@, but only if the closing '@ is at the start of the line
20'@
21
22@"
23If we want to use variables or expressions, and don't want to escape quotes, we can use a double "here-string".
24
25Then we know $true is $true, $false is $false, and 2+2 = $(2 +2).
26"@
27
28
29"We can add strings in many ways"
30
31"'String A'" + ' + ' + "'String B'"
32
33"Or", "We", "Could", "Join", "Strings" -join ' '
34
35"We", "Can", "Join", "By", "Any", "String" -join '...'
36
37"We can also multiply strings"
38
39"That way we don't have to"
40
41"Repeat ourselves. " * 3
42
43$myString = "Strings are objects, so we can find the last index of :"
44
45$myString + $myString.LastIndexOf(':')
46
47"We also have a bunch of regular expression operators"
48
49"We can also split a string" -split '\s'
50
51"We can replace something in a string" -replace "something", "anything"
52
53"We can do some interesting string comparisons:"
54
55"We can see if a string is -like a wildcard" -like '*like*'
56
57"We can see if a string matches a pattern" -match 'pattern'
58
59"If a pattern matches, then we will have matches in a $($matches) called `$matches"
60
61"`$matches.0 will contain the $($matches.0) match"
62
63@(
64
65 "We can make strings out of lists of things"
66
67 "Just emit the items one by one"
68
69 "And, optionally -join them together"
70
71) -join [Environment]::NewLine
72
73@(
74 "<p>This is actually a great way to make tags</p>"
75)
76
77@(
78 "// it's also a good way to make classes"
79 "class Foo {"
80 "public void Bar() {"
81 "}"
82 "}"
83) -join [Environment]::NewLine
84
85"Last but not least, we can convert strings into things"
86
87"<a>string that is xml can be coerced to xml with -as</a>" -as [xml]
88
89[xml]"<or>we can cast it to xml by prefixing the type</or>"
90
91"A string can become a number"
92
93"The answer to life, the universe, and everything is:"
94
95"42" -as [double]