PowerShell教程 - 编程结构(Program Struct)- 第二部分

更新记录
转载请注明出处。
2022年8月20日 发布。
2022年8月15日 从笔记迁移到博客。

字符串(String)

说明#

本质就是 .NET System.String type

使用字符串的索引(Indexing into strings)#

$myString = 'abcdefghijklmnopqrstuvwxyz'
$myString[0] # This is a (the first character in the string)
$myString[-1] # This is z (the last character in the string)

在数组中使用字符串方法(String methods and arrays)#

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(',')

子串(Substring)#

$myString = 'abcdefghijklmnopqrstuvwxyz'
$myString.Substring(20) # Start at index 20. Returns 'uvwxyz'

分割(Split)#

$myString = 'Surname,GivenName'
$myString.Split(',')

设置分割移除空白内容

$string = 'Surname,,GivenName'
$array = $string.Split(',', [StringSplitOptions]::RemoveEmptyEntries)
$array.Count # This is 2

替换(Replace)#

$string = 'This is the first example'
$string.Replace('first', 'second')

$string = 'Begin the begin.'
$string -replace 'begin.', 'story, please.'
$string.Replace('begin.', 'story, please.')

裁边(Trim, TrimStart, and TrimEnd)#

$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')

插入和移除(Insert and remove)#

插入字符串

$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)

查找(IndexOf and LastIndexOf)#

$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'
}

扩充(PadLeft and PadRight)#

('one', 'two', 'three').PadRight(10, '.')
('one', 'two', 'three').PadLeft(10, '.')

大小写转换(ToUpper, ToLower, and ToTitleCase)#

'aBc'.ToUpper() # Returns ABC
'AbC'.ToLower() # Returns abc

检测包含(Contains, StartsWith, and EndsWith)#

检测包含

$string = 'I am the subject'
$string.Contains('the') # Returns $true

检测结尾和开头存在#

$string = 'abc'
$string.StartsWith('ab')
$string.EndsWith('bc')

链式调用(Chaining methods)#

' ONe*? '.Trim().TrimEnd('?*').ToLower().Replace('o', 'O')

字符串编码转换(Converting strings)#

说明#

处理Base64编码(Working with Base64)
使用.NET System.Convert class的以下方法:
ToBase64String
FromBase64String

转为base64#

[Byte[]]$bytes = 97, 98, 99, 100, 101
[Convert]::ToBase64String($bytes)

转为base64 2

$bytes = [System.Text.Encoding]::ASCII.GetBytes('Hello world')
[Convert]::ToBase64String($bytes)

base64转为数据#

$bytes = [Convert]::FromBase64String($base64String)
[System.Text.Encoding]: :ASCII.GetString($bytes)

数值(Number)

大字节单位(Large byte values)#

可以在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

次方(Power of 10)#

2e2 # Returns 200 (2 * 102)
2e-1 # Returns 0.2 (2 * 10-1)

十六进制前缀(Hexadecimal)#

实例:

0x5eb

使用Math类型(Using System.Math)#

说明#

.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

将字符串转为数值(Converting strings into numeric values)#

使用强制转换

[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

列表(Lists)

说明#

就是.NET中的List类型,System.Collections.Generic.List

创建列表(Creating a list)#

创建泛型列表

$list = New-Object System.Collections.Generic.List[String]

创建ArrayList

$arrayList = New-object System.Collections.ArrayList

添加元素到列表(Adding elements to the list)#

添加单个元素

$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

移除元素(Removing elements from the list)#

移除指定索引的元素

$list.RemoveAt(1) # By Richard by index

移除指定的值

$list.Remove("Richard") # By Richard by value

移除所有值

$list.RemoveAll( { $args[0] -eq "David" } )

字典(Dictionary)

说明#

就是.NET中的Dictionary类型,System.Collections.Generic.Dictionary

创建字典(Creating a dictionary)#

$dictionary = New-Object  System.Collections.Generic.Dictionary"[String,IPAddress]"
$dictionary = New-Object "System.Collections.Generic.Dictionary[String,IPAddress]"

添加元素(Adding elements in a dictionary)#

$dictionary.Add("Computer1", "192.168.10.222")

修改元素(Changing elements in a dictionary)#

直接修改

$dictionary.Computer3 = "192.168.10.134"

移除元素(Removing elements from a dictionary)#

$dictionary.Remove("Computer1")

获得元素的值#

$dictionary["Computer1"] # Key reference
$dictionary.Computer1 # Dot-notation

获得所有键#

$dictionary.Keys

获得所有值#

$dictionary.Values

检测是否包含指定的键#

$dictionary.ContainsKey("Computer2")

检测是否包含指定的值#

$dictionary.ContainsValue("Computer2")

遍历字典(Enumerating a dictionary)#

使用foreach遍历

foreach ($key in $dictionary.Keys) {
 Write-Host "Key: $key Value: $($dictionary[$key])"
}

队列(Queues)

说明#

就是.NET中的Queue类型,System.Collections.Generic.Queue

创建队列(Creating a queue)#

$queue = New-Object System.Collections.Generic.Queue[String]

获得队列头部元素#

$queue.Peek()

入队操作(Adding elements to the queue)#

$queue.Enqueue("Tom")
$queue.Enqueue("Richard")
$queue.Enqueue("Harry")

出队操作(Removing elements from the queue)#

$queue.Dequeue() # This returns Tom

获得元素个数#

$queue.Count

遍历队列(Enumerating the queue)#

$queue = New-Object System.Collections.Generic.Queue[String]
$queue.Enqueue("Panda");
$queue.Enqueue("Dog");
foreach($item in $queue.GetEnumerator())
{
  Write-Host $item
}

转为数组#

$queue.ToArray()

栈(Stacks)

说明#

就是.NET中的Stack类型,System.Collections.Generic.Stack

创建栈(Creating a stack)#

$stack = New-Object System.Collections.Generic.Stack['string'];

添加元素到栈(Adding elements to the stack)#

$stack.Push("Panda"); 

从栈中移除元素(Removing elements from the stack)#

从栈中移除元素之前记得,先检测栈是否为空

$stack.Pop() # This returns Under the bridge

获得栈顶元素#

注意:使用前记得检测栈是否为空

$stack.Peek()

获得栈中元素的个数#

$stack.Count 

转为数组#

$stack.ToArray()

遍历栈(Enumerating the stack)#

日期(DateTime)

解析日期字符串#

可以使用以下方法:

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)

使用DateTime的方法#

(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')

日期的比较(Comparing dates)#

实例:

实例1

$date1 = (Get-Date).AddDays(-20)
$date2 = (Get-Date).AddDays(1)
$date2 -gt $date1

实例2

(Get-Date "13/01/2017") -gt "12/01/2017"

对象管理(Working with Objects)

说明#

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

也可以使用代码块的方式使用

'one@one.example', 'two@one.example', 'three@two.example'  | 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

作者:重庆熊猫

出处:https://www.cnblogs.com/cqpanda/p/16589954.html

版权:本作品采用「不论是否商业使用都不允许转载,否则按3元1字进行收取费用」许可协议进行许可。

posted @   重庆熊猫  阅读(256)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示