[TOP]
数组
定义
# 定义数组
$myArray = @( “a”,”b”,”c”,”d”,”e”,”f”,”g”,”h” )
$myArray = “a”,”b”,”c”,”d”,”e”,”f”,”g”,”h”
$myArray = @(25)
$myArray = ,25
[int[]] $a = 1,2,3,4
# 生成数组
$a = ,2 * $length
[int[]]$a = [System.Linq.Enumerable]::Repeat(2, $length)
$a = foreach ($i in 1..$length) { 2 }
[int[]]$a = -split “2 ” * $length
$a = for ($i = 0; $i -lt $length; $i++) { 2 }
$a = 1..$length | %{ 2 }
$a = @(); for ($i = 0; $i -lt $length; $i++) { $a += 2 }
# 转格式
1,2,3 | % { “item $_” }
# 枚举
foreach ($item in “a”,”b”) { $item }
# 枚举时加入索引
v1′,’v2′,’v3’,’v4’| foreach {$i=1} { if ($i++ % 2) {$_} } {“done”}
# 将对象转为数组
$a = @(Get-Service | select -first 1) ; $a.length
比较
# 比较不同
compare (1..5) (4..1)
# 比较相同
diff (1..3) (3..1) -Sync 0
# 相同返回 $true, 不同返回 $false
@(compare (1..5) (5..1)).length -eq 0 # $true
@(compare (1..5) (4..1)).length -eq 0 # $false
索引
# 枚举时加入索引
v1′,’v2′,’v3’,’v4’| foreach {$i=1} { if ($i++ % 2) {$_} } {“done”}
# 按索引返回
(1,2,3,4,5)[0]
1..10 | select -index 0,4,9
(1..10)[1..4]
1..10 | select -index (1..4) # 前 n 个
$n = 2; 1,2,3,4,5 | select -first $n # 前 n 个
$n = 4; 1,2,3,4,5 | select -last $n # 后 n 个
1..10 | select -skip 3 -first 4 # 跳过前 n 个
$n = 2; 1,2,3,4,5 | select -skip $n # 跳过前 n 个
$n = 2; 1..5 | Select-Object -skip $n -last 100000 # 跳过后 n 个取全部 last 要取得大
$txt = any; $txt[0..($txt.length-n-1)] # 跳过后 n 个取
any | Skip-Object -Last n <<pscx>> # 中过后 n 个取全部, 这个优雅
相减
# 去除一个值
$a = @(1, 2, 3, 4, 5 )
$a = $a -ne 3 # 从数组中移除 3 ,相当于 $a = $a | ? { $_ -ne 5 }
# 去除一组值
$a = @(1, 2, 3, 4, 5 )
$b = @(1, 2, 3 )
$b | % { $a = $a -ne $_ } # $b 循环从 $a 中去除值
合并去重排序
# 合并数组
@(“apple”,”pear”) + @(“apple”,”orange”)
@(“apple”,”pear”) + @(“apple”,”orange”) | select -uniq # 合并数组后去重
$a = 1,2,3; $a += 4; $a # 合并
# 去重
@(1,2,5,9) | select -uniq | ? { @(2,4,9,16) -contains $_ } # 取指定项中有的值
1,2,3,4,2,3 | select -uniq |? { 1,3,4,5 -notcontains $_ } # 取指定项中没有的值
“abc”, “abc” , “Abc”, “def” | Get-Unique # 去重取唯一
“abc”, “Abc”, “def”, “abc” | sort -case | Get-Unique # 排序,去重
“abc”, “Abc”, “def”, “abc” | select -unique
# 对多个数组进行操作, 这里 $a, $b = 是一个给多变量同时赋值的操作
$a = @(“a”,”b”); $b = @(1,2);
$a,$b = $a,$b |% {,($_ += ‘foo’)}; “$a — $b”
# 排序
“ab12”, “ab1”, “ab103” | sort
“ab12”, “ab1”, “ab103” | sort { [int]($_ -replace ‘\D’) } # -replace 查找正则
ls \windows\system32\dwm*.dll | sort -property length | select name, length | ft -auto # 按指定项排序,并格式 table 输出
gc numbers.txt | sort { [int]$_ } # 强转为 int 进行排序
gc lines.txt | sort { [double](-split $_)[0] } # 强转格式进行排序
gc lines.txt | sort { [int](-split $_)[-1] }
类 linq 操作
Select # Get-Process | Select-Object -Property Name, WorkingSet, StartTime
Where # Get-ChildItem | Where-Object { $PSItem.Length -gt 1000 }
OrderBy # Get-ChildItem | Sort-Object -Property length -Descending
GroupBy # Get-Service | Group-Object Status
# 去重
Distinct
# 1. “abc”, “def”, “abc” | Sort-Object | Get-Unique
# 2. “abc”, “def”, “abc” | Sort-Object -unique
# 3. Get-ChildItem *.cs -r | Select-String “public.*void” | Select-Object -Unique Path
Take # Get-Process | Select-Object -First 5
Skip # Get-Process | Select-Object -Skip 5
Any, All # 原文使用 pwsh 函数,有点复杂,这里直接调用 linq 函数
$data = 0 .. 10
# https://stackoverflow.com/questions/38360545/can-linq-be-used-in-powershell
[System.Linq.Enumerable]::Where($data, [Func[object, bool]]{ param ($x) $x -gt 5 })
[System.Linq.Enumerable]::Any($data, [Func[object, bool]]{ param ($x) $x -gt 15 })
[System.Linq.Enumerable]::All($data, [Func[object, bool]]{ param ($x) $x -le 10 })
HashTable
定义
# 定义
@{ label = value; … }
@”
i1=bird
i2=256
i3=cat
“@ | ConvertFrom-StringData
# 从 csv 文件中导入
Import-Csv $file | foreach { $hash = @{} } { $hash[$_.key] = $_.value}
# 正则方法转为带 = 的多行文
(any -replace ‘,’, ‘=’) -join “`n” | ConvertFrom-StringData
# 使用 foreach, 读入文本是多行处理的吗?
$hash = @{};
Get-Content $file |
foreach { if ($_ -match $regex)
{ $hash[$matches[1]] = $matches[2] }
}
# 将对象转为 hashtable
any | Out-String | Invoke-Expression
# ps1 文件中是一个hashtable @{ x='x'; y = 'y' } 格式
variable = filespec.ps1
# 从 ini 文件中载入
$hash = Get-IniFile file # 调用 $ini[“Install”][“A”], $ini.Install.B
# 使用 .net 语法, 强类型
$dict = [System.Collections.Generic.Dictionary[int, string]]::new()
$dict[1] = "32"
取值
$hash[$key]
$hash.key
$hash.Item($key)
# 枚举
$hash.GetEnumerator() | foreach { … $_.Key … $_.Value …}
# 使用 key 进行枚举
$hash.Keys | foreach { … $_ … $hash[$_] … }
# key value 交换
$hash.Keys | foreach {$Rhash=@{}} { $Rhash[$hash[$_]] = $_ }
# 将某个值替换为新值
@($table.GetEnumerator()) |where {$_.Value -eq oldValue} | foreach { $table[$_.Key] = newValue }
字符串
拆分
# 默认应该是 空格 /t /n 进行拆分
-split string # -split “one two`tthree`nfour”
# 指定分拆字符
string -split delimiter # “one,two,three” -split “,”
# 使用正则进行拆分
[regex]::split(string, regex) # [regex]::split(“123#456#apple”, “#(?!\d)”)
string -split regex # “123#456#apple” -split “#(?!\d)”
[regex]::split(string, regex, options) # [regex]::split(“Apple_aPPle_APple”, “ppl”, “IgnoreCase”)
# 对字符串进行拆分, $_ 为每一个字符
string -split scriptBlock # “Brobdingnag” -split {$_ -eq “n” -or $_ -eq “o”}
# $_ 为每一个字符, 但是有一个动态的判断
# $i = 5; “a,b#c!d” -split { if ($i -gt 3) {$_ -eq “,”} else {$_ -eq “#”} }
# 使用 \r\n 进行拆分
string -split “`r`n” # (Get-Content test.txt | Out-String) -split “`r`n”
# 使用 \n 拆分 ,去掉前后空格,去掉空行
$data -split “`n” | % { $_.Trim() } | ? { $_.Length -gt 0 }
# .net 语法
'1`n2`n'.Split('`n', [System.StringSplitOptions]::RemoveEmptyEntries)
字符串拼接
# 调用 -join
-join array # $a = “abc”,”def”; -join $a
array -join delimiter # “abc”,”def”,”ghi” -join ',' # 指定分隔符
# 直接定义时拼接
$a = “abc”,”def”; “$a”
# 默认使用 \r\n 进行拼接
array | Out-String # “abc”,”def”,”ghi”| Out-String
# .net 语法
[string]::join(delimiter, array)
字符串搜索
# 使用正则搜索并替换
'xxx' -replace regex, replacement }
# 使用 select-string 创建正则结果
any | Select-String “(pattern)” | foreach { $_.Matches[0].Groups[1].Value }
# 输出搜索结果
any | Select-String ‘(?<=pattern)(.*)’ | select -expa matches | select -expa value | foreach { $_.trim() }
# 每一行取指定位置的内容
any | % { $_.substring(int,int) }
# 使用 csv 文件或格式
Import-Csv file| select -ExpandProperty name
any | ConvertFrom-Csv -Header nameList | select -ExpandProperty name
Import-Csv file | foreach { formatString -f $_.name1, $_.name2, … }
any | ConvertFrom-Csv -Header names | foreach { formatString -f $_.name1, $_.name2, … }
Import-Csv file -Header field-list -Delimiter delimiter | select – ExpandProperty field # 指定了 csv 的分隔符
# 过滤
any | Where { $_ }
文件搜索
# 列出文件,载入根据正则选出行
ls filespec | Select-String pattern # ls . -Recurse *.cs | Select-String “public.*void”
# 列出文件,载入根据正则先出行,统计行数
(ls filespec | Select-String pattern).Line # (ls . -r *.cs | sls “public.*void”).Line
# 列出文件并过滤
ls -r *.html
ls -r *.xml | ? { $_.name -match “abc{0,3}.*\.xml” }
ls -r *.xml | ? { $_ -match “this\\sub\\path” }
ls -r *.xml | sls home | group path | select count,name | ft -auto