更新记录
转载请注明出处。
2022年8月20日 发布。
2022年8月15日 从笔记迁移到博客。
本质就是 .NET System.String type
$myString = 'abcdefghijklmnopqrstuvwxyz' $myString[0] # This is a (the first character in the string) $myString[-1] # This is z (the last character in the string)
some string methods can be called on an array
The method will be executed against each of the elements in the array
('azzz', 'bzzz', 'czzz').Trim('z') ('a,b', 'c,d').Split(',')
$myString = 'abcdefghijklmnopqrstuvwxyz' $myString.Substring(20) # Start at index 20. Returns 'uvwxyz'
$myString = 'Surname,GivenName' $myString.Split(',')
设置分割移除空白内容
$string = 'Surname,,GivenName' $array = $string.Split(',', [StringSplitOptions]::RemoveEmptyEntries) $array.Count # This is 2
$string = 'This is the first example' $string.Replace('first', 'second') $string = 'Begin the begin.' $string -replace 'begin.', 'story, please.' $string.Replace('begin.', 'story, please.')
$string = " This string has leading and trailing white space " $string.Trim()
裁剪多个字符
$string = '*__This string is surrounded by clutter.--#' $string.Trim('*_-#')
裁剪尾部
$string = 'magnet.uk.net' $string.TrimEnd('.uk.net')
插入字符串
$string = 'The letter of the alphabet is a' $string.Insert(4, 'first ') # Insert this before "letter", include a trailing space
移除字符串
$string = 'This is is an example' $string.Remove(4, 3)
$string = 'abcdefedcba' $string.IndexOf('b') # Returns 1 $string.LastIndexOf('b') # Returns 9 $string.IndexOf('ed') # Returns 6
检测是否存在
$string = 'abcdef' if ($string.IndexOf('a') -gt -1) { 'The string contains an a' }
('one', 'two', 'three').PadRight(10, '.') ('one', 'two', 'three').PadLeft(10, '.')
'aBc'.ToUpper() # Returns ABC 'AbC'.ToLower() # Returns abc
检测包含
$string = 'I am the subject' $string.Contains('the') # Returns $true
$string = 'abc' $string.StartsWith('ab') $string.EndsWith('bc')
' ONe*? '.Trim().TrimEnd('?*').ToLower().Replace('o', 'O')
处理Base64编码(Working with Base64)
使用.NET System.Convert class的以下方法:
ToBase64String
FromBase64String
[Byte[]]$bytes = 97, 98, 99, 100, 101 [Convert]::ToBase64String($bytes)
转为base64 2
$bytes = [System.Text.Encoding]::ASCII.GetBytes('Hello world') [Convert]::ToBase64String($bytes)
$bytes = [Convert]::FromBase64String($base64String) [System.Text.Encoding]: :ASCII.GetString($bytes)
可以在PowerShell中直接使用带存储单位的数值,在内部会自动转为byte单位
支持的单位:
nKB: Kilobytes (n * 10241)
nMB: Megabytes (n * 10242)
nGB: Gigabytes (n * 10243)
nTB: Terabytes (n * 10244)
nPB: Petabytes (n * 10245)
实例:
1TB / 1GB 1PB / 1TB 1TB * 1024 -eq 1PB #True
2e2 # Returns 200 (2 * 102) 2e-1 # Returns 0.2 (2 * 10-1)
实例:
0x5eb
.NET System.Math class提供了很多有用的静态方法
[Math]::Round(2.123456789, 2) [Math]::Round(2.225, 2) # Results in 2.22 [Math]::Round(2.225, 2, [MidpointRounding]::AwayFromZero) # Results in 2.23
[Math]: :Abs(-45748)
[Math]::Sqrt(9) # Returns 3
[Math]::pi # π, 3.14159265358979
使用强制转换
[Int]"2" # String to Int32 [Decimal]"3.141" # String to Decimal [UInt32]10 # Int32 to UInt32 [SByte]-5 # Int32 to SByte
使用Convert类型
[Convert]::ToInt32('01000111110101', 2) # Returns 4597 [Convert]::ToInt32('FF9241', 16) # Returns 16749121
就是.NET中的List类型,System.Collections.Generic.List
创建泛型列表
$list = New-Object System.Collections.Generic.List[String]
创建ArrayList
$arrayList = New-object System.Collections.ArrayList
添加单个元素
$list.Add("David")
添加多个元素
$list.AddRange([String[]]("Tom", "Richard", "Harry"))
使用索引访问元素
$list[1]
$list.Insert(0, "Sarah") $list.Insert(2, "Jane")
$index = $list.FindIndex( { $args[0] -eq 'Richard' } )
$list.IndexOf('Harry', 2) # Start at index 2 $list.IndexOf('Richard', 1, 2) # Start at index 1, and 2 elements
移除指定索引的元素
$list.RemoveAt(1) # By Richard by index
移除指定的值
$list.Remove("Richard") # By Richard by value
移除所有值
$list.RemoveAll( { $args[0] -eq "David" } )
就是.NET中的Dictionary类型,System.Collections.Generic.Dictionary
$dictionary = New-Object System.Collections.Generic.Dictionary"[String,IPAddress]" $dictionary = New-Object "System.Collections.Generic.Dictionary[String,IPAddress]"
$dictionary.Add("Computer1", "192.168.10.222")
直接修改
$dictionary.Computer3 = "192.168.10.134"
$dictionary.Remove("Computer1")
$dictionary["Computer1"] # Key reference $dictionary.Computer1 # Dot-notation
$dictionary.Keys
$dictionary.Values
$dictionary.ContainsKey("Computer2")
$dictionary.ContainsValue("Computer2")
使用foreach遍历
foreach ($key in $dictionary.Keys) { Write-Host "Key: $key Value: $($dictionary[$key])" }
就是.NET中的Queue类型,System.Collections.Generic.Queue
$queue = New-Object System.Collections.Generic.Queue[String]
$queue.Peek()
$queue.Enqueue("Tom") $queue.Enqueue("Richard") $queue.Enqueue("Harry")
$queue.Dequeue() # This returns Tom
$queue.Count
$queue = New-Object System.Collections.Generic.Queue[String] $queue.Enqueue("Panda"); $queue.Enqueue("Dog"); foreach($item in $queue.GetEnumerator()) { Write-Host $item }
$queue.ToArray()
就是.NET中的Stack类型,System.Collections.Generic.Stack
$stack = New-Object System.Collections.Generic.Stack['string'];
$stack.Push("Panda");
从栈中移除元素之前记得,先检测栈是否为空
$stack.Pop() # This returns Under the bridge
注意:使用前记得检测栈是否为空
$stack.Peek()
$stack.Count
$stack.ToArray()
可以使用以下方法:
ParseExact TryParseExact
实例:
使用ParseExact
$string = '20170102-2030' # Represents 1st February 2017, 20:30 [DateTime]: :ParseExact($string, "yyyyddMM-HHmm', (Get-Culture)"
使用TryParseExact
$date = Get-Date 01/01/1601 # A valid DateTime object with an obvious date $string = '20170102-2030' if ([DateTime]::TryParseExact($string, 'yyyyddMM-HHmm', $null, 'None', [Ref]$date)) { $date }
(Get-Date) + (New-Timespan -Hours 6)
(Get-Date).Date (Get-Date).AddDays(1) # One day from now (Get-Date).AddDays(-1) # One day before now(Get-Date).AddTicks(1) (Get-Date).AddMilliseconds(1) (Get-Date).AddSeconds(1) (Get-Date).AddMinutes(1) (Get-Date).AddHours(1) (Get-Date).AddMonths(1) (Get-Date).AddYears(1) (Get-Date).ToUniversalTime() (Get-Date).ToUniversalTime().Date.AddDays(-7).ToString('dd/MM/yyyy HH:mm')
实例:
实例1
$date1 = (Get-Date).AddDays(-20) $date2 = (Get-Date).AddDays(1) $date2 -gt $date1
实例2
(Get-Date "13/01/2017") -gt "12/01/2017"
Everything we do in PowerShell revolves around working with objects
New-Object
实例:
创建一个空对象(Object)
$empty = New-Object Object
新建List类型的对象
$list = New-Object System.Collections.Generic.List[String]
新建TcpClient
$tcpClient = New-Object System.Net.Sockets.TcpClient $tcpClient.Connect("127.0.0.1", 135) $tcpClient.Close()
新建文件并将设置文件对象的创建时间
$File = New-Item NewFile.txt -Force $File.CreationTime = Get-Date -Day 1 -Month 2 -Year 1692
Add-Member
作用:将新成员添加到对象中
实例:
新建对象,并添加成员(键值对属性)
$empty = New-Object Object $empty | Add-Member -Name New -Value 'Hello world' -MemberType NoteProperty
新建对象,并添加成员(键值对属性)
$panda = New-Object Object $panda | Add-Member -Name 'PandaProperty' -Value "Panda666.com" -MemberType NoteProperty
新建对象,并添加成员(代码属性)
$dog = New-Object Object; #添加普通键值对属性 $dog | Add-Member -Name "p1" -Value "Panda666" -MemberType NoteProperty; #添加代码属性 $dog | Add-Member -Name "p2" -Value { $this.p1.Length } -MemberType ScriptProperty;
Get-Member
对象的成员类型:
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.psmembertypes?redirectedfrom=MSDN&view=powershellsdk-7.0.0
实例:
获得指定对象的成员
Get-Process -Id 3880 | Get-Member
指定成员类型
Get-Process -Id $PID | Get-Member -MemberType Property
获得对象成员
(Get-Process -Id $PID).StartTime
获得对象成员的成员
(Get-Process -Id $PID).StartTime.DayOfWeek
如果对象成员有空格,可以使用单引号、双引号、括号进行包裹
$object = [PSCustomObject]@{ 'Some Name' = 'Value' } $object."Some Name" $object.'Some Name' $object.{Some Name}
还可以使用变量作为成员名称
$object = [PSCustomObject]@{ 'Some Name' = 'Value' } $propertyName = 'Some Name' $object.$propertyName
注意:不要修改对象的只读属性,否则会报错
使用对象的方法(Using methods)
调用无参数的方法
<Object>.Method()
调用有参数的方法
<Object>.Method(Argument1, Argument2)
通过调用对象的属性修改对象状态
(Get-Date).Date.AddDays(-1).ToString('u')
ForEach-Object
提示:除了可以引用单个元素对象,还可以获得元素的单个属性或执行方法
实例:
给数组的元素自增1
$pandaArr = 1,2,3,4,5; $pandaArr | ForEach-Object { $_ + 1; };
获得进程的名称
Get-Process | ForEach-Object { Write-Host $_.Name -ForegroundColor Green }
直接调用元素的方法
$pandaArr = "Panda","Dog","Cat"; $pandaArr | ForEach-Object ToUpper`
等价于:
$pandaArr = "Panda","Dog","Cat"; $pandaArr | ForEach-Object { $_.ToUpper(); }
直接调用元素的方法2
(Get-Date '2020年9月22日' ), (Get-Date '01/01/2020') | ForEach-Object ToString('yyyyMMdd')
等价于:
(Get-Date '2020年9月22日'), (Get-Date '01/01/2020') | ForEach-Object { $_.ToString('yyyyMMdd'); }
直接调用元素的属性
$pandaArr = "Panda","Dog","Cat"; $pandaArr | ForEach-Object Length
等价于:
$pandaArr = "Panda","Dog","Cat"; $pandaArr | ForEach-Object { $_.Length }
Where-Object [-Property] <String> [[-Value] <Object>] -GT ...
提示:?(问号)是Where-Object Cmdlet的别名
实例:
筛选出启动时间在5点后的进程
Get-Process | Where-Object StartTime -gt (Get-Date 17:00:00)
也可以使用代码块结构
$pandaArr = 1,2,3,4,5 $pandaArr | Where-Object { $_ -gt 3 }
带有多个筛选条件
Get-Service | Where-Object { $_.StartType -eq 'Manual' -and $_.Status -eq 'Running' }
Select-Object
实例:
选择指定名称的成员
Get-Process | Select-Object -Property Name,Id,CPU
排除指定的字段
Get-Process | Select-Object -Property * -Exclude *Memory*
获得前10条数据
Get-Process | Select-Object -First 10
获得后10条数据
Get-Process | Select-Object -Last 10
跳过2条数据
Get-ChildItem C:\ | Select-Object -Skip 4 -First 1
不重复
1, 1, 1, 3, 5, 2, 2, 4 | Select-Object -Unique
Sort-Object
实例:
指定排序的key 使用对象的属性
Get-Process | Sort-Object -property VM Get-Process | Sort-Object -Property Id
降序排序
Get-Process | Sort-Object -property Comments -Descending
排除重复然后排序
1, 1, 1, 3, 5, 2, 2, 4 | Select-Object -Unique | Sort-Object
多字段排序
Get-ChildItem C:\Windows | Sort-Object LastWriteTime, Name
还可以使用代码块结构进行复杂的排序
$examResults = @( [PSCustomObject]@{ Exam = 'Music'; Result = 'N/A'; Mark = 0 } [PSCustomObject]@{ Exam = 'History'; Result = 'Fail'; Mark = 23 } [PSCustomObject]@{ Exam = 'Biology'; Result = 'Pass'; Mark = 78 } [PSCustomObject]@{ Exam = 'Physics'; Result = 'Pass'; Mark = 86 } [PSCustomObject]@{ Exam = 'Maths'; Result = 'Pass'; Mark = 92 } ) $examResults | Sort - Object { switch ($_.Result) { 'Pass' { 1 } 'Fail' { 2 } 'N/A' { 3 } } }
Group-Object
实例:
数组分组
6, 7, 7, 8, 8, 8 | Group-Object
不需要元素
6, 7, 7, 8, 8, 8 | Group-Object -NoElement
也可以使用代码块的方式使用
'[email protected]', '[email protected]', '[email protected]' | Group-Object { ($_ -split '@')[1] }
Measure-Object
常用于统计对象的内容
注意:When used without any parameters, Measure-Object will
return a value for Count
实例:
默认返回Count
1, 5, 9, 79 | Measure-Object
获得项数
3358,6681,9947,1156 | Measure-Object -Count
获得合计值
3358,6681,9947,1156 | Measure-Object -Sum
获得最大值
3358,6681,9947,1156 | Measure-Object -Max
获得最小值
3358,6681,9947,1156 | Measure-Object -Min
获得平均数
3358,6681,9947,1156 | Measure-Object -Average
指定多项目
1, 5, 9, 79 | Measure-Object -Average -Maximum -Minimum -Sum
获得单词数目
Get-Content -Path "D:/test.txt" | Measure-Object -Word
获得字符数量
Get-Content -Path "D:/test.txt" | Measure-Object -Character
获得行数(不包括空行)
Get-Content -Path "D:/test.txt" | Measure-Object -Line
Compare-Object
实例:
对比文本
Compare-Object "D:/test.csv" "D:/test2.csv"
对比文件内容
Compare-Object (Get-Content "D:\test.csv") (Get-Content "D:\test2.csv")
显式带参数方式
Compare-Object -ReferenceObject 1, 2 -DifferenceObject 1, 2
显示相同点和不同点(默认只显示不同点)
Compare-Object -ReferenceObject 1, 2, 3, 4 -DifferenceObject 1, 2 -IncludeEqual