Powershell Notes
文章目录
教程
Cheat Sheet
获取对象信息 Get-Member
- 别名 gm
- eg: ls | gm
注释
- 单行注释
<# … #>
- 多行注释
Powershell
快捷键模式
使用 emacs-like 快捷键 https://stackoverflow.com/questions/43295639/update-powershell-keyboard-bindings-to-be-emacs-style-like-bash-shell
https://docs.microsoft.com/en-us/powershell/module/psreadline/about/about_psreadline?view=powershell-7 MS 官方文档
1Set-PSReadLineOption -EditMode Emacs
后台运行任务—-Job 相关命令
https://blog.csdn.net/litterfrog/article/details/104001641
https://www.jb51.net/article/136289.htm 详细
工具
Start-Job
- 启动后台工具
alias: sajb
1 2Start-Job -ScriptBlock {emacs -q} # 效果和 runemacs -q 类似
Get-Job
- 查看启动的后台任务
alias: gjb, ps
1Get-Job
Stop-Job
1 2Stop-Job -Id 3 # id 可以由 Get-Job 查看Remove-Job
1Remove-Job -Id 3
查找帮助
Get-Help
alias: man
1 2man -Online man man Get-Job
中止任务,类似 linux Ctrl + C
正则匹配
| |
正则语法
匹配 match
1'your_string' -match 'your_pattern'提取结果
1$matches # --> matches[0]
连接成字符串
类似 python str.join
1 2 3 4$my_ports -join ',' # output 1,2,3
列表长度
length 属性
1$my_ports.length
iex 把字符串当作命令执行
- Invode-Expression
- 类似 bash -c "your command"
预定义变量
| |
变量
例子
1 2$myVar = 3 $name="Lucy"语法
- “声明” 和 “使用” 都要加上 $
赋值等号“=”前后,空格有无都可以
- 不同于 bash, 必须没有空格
获取类型
- $var.GetType()
数据结构
数组
元素类型
- 任意类型,因为 powershell 是动态语言
格式
元素分隔符
- 逗号 ","
- @(, , , …)
创建
1$my_array = @(elem0, elem1, elem2, ...)索引
zero-indexed
1 2 3 4 5echo $my_array[0] # 给定元素 echo $my_array[1] echo $my_array # 整个数组 $my_array[0] = 12 # 元素赋值
拼接 数组
使用加号 "+" 和 "+="
1 2 3 4$arr = @(1, 2, 3) + @(4, 5, 6) # arr --> @(1, 2, 3, 4, 5, 6) $arr += @(11, 22)
列表
输入语法
1 2 3 4 5 6 7$my_ports = @(1, 2, 3); $my_ports # output 1 2 3- 注
- 空格,可以省略,没有影响
哈希表 (Hashtable, dict, map)
语法
元素分割
- 分号 ";" 或者 换行
- @{ ; ; ; …}
创建
1$myDict = @{key01 = value01; key02 = value02; ...}索引
1 2 3 4 5$dict = ${score=30, 1=1000} echo $dict['score'] echo $dict[1] echo $dict.score注意
- 键是字符串类型,一定要用引号
- 键是数字类型,无特别
拼接 哈希表
使用加号 "+" 和 "+="
1 2$dict = @{score=3} + @{name="lucy"} $dict += @{id=1111}
控制结构
简述
分支
if else
1 2 3 4 5 6 7 8 9 10 11 12If ( 条件 ) { 语句 } ElseIf ( 条件 ) { 语句 } Else { 语句 }switch
1 2 3 4 5 6 7 8switch (<表达式>) { <测试值> { <语句>; break} ... Default { <语句>} }
循环
For
1 2 3 4 5# <> 代表语句 For (<>; <>; <>) { <> }ForEach
1 2 3ForEach (<elem> in <collection>) { <statements> }While
1 2 3 4While (<测试条件>) { ... }Do While
1 2 3 4Do { ... } While(<条件>)Do Untile
1 2 3 4Do { ... } Until (<条件>)
if else
例子
1 2 3 4 5 6 7 8 9 10$var = 3 if ($var -gt 0) { echo "positive" } else { echo "negative or zero" }
switch
例子
1 2 3 4 5 6 7 8 9 10$var = 7 echo $_ switch ($var) { 3 {echo "this is 3: $_"; break} {$_ -gt 3} {echo "greater than 3: $_"; break} default {echo "other number: $_"} }注意
- switch 内部的条件
复杂测试条件
- 使用花括号 "{}" 包起来
for
例子
1 2 3 4for ($i = 0; $i -lt 10; i++) { ... }
ForEach
例子
1 2 3 4ForEach ($elem in $arr) { ... }
While
例子
1 2 3 4While ($var -gt 3) { ... }
Write-Host Vs Write-Output
Write-Output
- 即 echo 命令 cmdlet
ref:
- https://dotnet-helpers.com/powershell/difference-between-write-host-and-write-output-in-powershell/#:~:text=Write-Output%20sends%20the%20output%20to%20the%20pipeline.%20From,host%20and%20nothing%20has%20to%20send%20forward%20
例子
1 2 3 4 5 6$a = 'Testing Write-OutPut' | Write-Output $b = 'Testing Write-Host' | Write-Host Get-Variable a,b # a --> "Testing Write-Output" # b --> ""- 单独使用,基本没区别
区别体现
- 在 pipeline 管道使用中
- Write-Host 不在管道中传输,只输出到主机
- Write-Output 还可以传输到管道 pipeline 中
在字符串中使用变量
类似 bash
- 双引号,变量被替换成变量内容
- 单引号,原样输出,不作处理
使用 .Net 类
创建类 New-Object
| |
访问类
| |
类型转换
| |
定义类
| |
定义 枚举类型
| |
注意
- 使用方括号把枚举类,包起来
命令记录
Get-Member
- 获取对象信息
别名 alias
- gm
调用方法
1get-location | gm
New-Object
- 创建对象
用法
1New-Object <类型名> <构造函数-参数>例子
1 2 3 4 5$version = New-Object System.Version # 默认构造 $version = [System.Version]::New() $version = New-Object System.Version 3, 6 # 重载的构造 $version = [System.Version]::New(3, 6)
命令历史访问
参考:
方法:
获取保存历史文件目录
(Get-PSReadlineOption).HistorySavePath
查看历史
cat (Get-PSReadlineOption).HistorySavePath
Pipeline
代码组成
Begin { … }
- 只会在开始的时候执行一次
- 处理对象:所有数据为一个整体
Process { … }
- 对每个元素各执行一次
- 对于每个元素,以 "$_" 表示
End { … }
- 在结束的时候执行一次
- 处理对象:所有数据为一个整体
ForEach-Object 命令 cmdlet
别名
- foreach
- %
作用
- 迭代对象
选项参数
- -Begin
- -Process
- -End
特殊用法
1'You', 'He' | ForEach-Object {"Say $_"}只有一个参数
- 默认传给 -Process
Where-Object 命令
参考
别名
- ?
- where
作用
- 根据给出判断条件,筛选 pipeline 传输过来的 Object 列表
- 筛选满足条件的对象
特殊用法
1'you', 'he' | Where-Object {$_ -match 'u'}- 后面跟的表达式,返回结果应当为 True 和 False
用法
先取出属性操作
1 2Get-Process | Where-Object {$_.ProcessName -Match "^p.*"} Get-Process | Where-Object ProcessName -Match "^p.*解说
- where 后面 直接跟 $_ 的属性名称
- 再对这个属性的值进行过滤操作
Select-Object
别名
- Select
作用
- 选择对象或对象的属性
选项参数
-First
eg: -First 5
- 选择前 5 个
- -Last
-Skip
- 要跳过的对象数量,与 -First 相对应
- -SkipLast
-Unique
- 设定,相同的对象,只处理一个
-Property
- 获取 属性的 (key, value) 对
ExpandProperty
- 只获取 属性的 value
字符串
-Match
作用
- 判断是否包含 给定字符串
例子
1 2'you' -match 'u' # output: True
-Replace
作用
- 搜索替换文本
- 支持正则表达式
格式
1'to render string' -Replace 'to find', 'relace with word'- 搜索文本和替换文本使用 "," 分隔
例子
1 2 3 4'i like tea' -replace 'tea', 'tree' # 正则 'i like tea' -replace '\s', '_'
-Join
作用
- 列表的连接,使用分隔符
例子
1 2 3 4 5('a', 'b', 'c') -join ',' # output: 'a,b,c' '127', '0', '0', '1' -join '.' # '127.0.0.1'格式
1(elem01, elem02, ...) -join 'seperator'特殊用法
- 直接拼接,没有分隔符
1 2 3 4 5-join (elem01, elem02, ...) # eg: -join (1, 2, 3) # --> '123'
自定义 cmdlet
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25param # 制定接收参数 { $ShowBuild } Process # 制定 pipeline 的 Process 代码块 { $version = [System.Version] $_ $os = switch ( $version.Major, $version.Minor -join '.') { '10.0' {'Windows 10'} '6.3' {'Windows 8.1'} default {'others'} } if ($ShowBuild) { $os, 'Build', $version.Build -join ' ' } else { $os } }用法
1 2'10.0.0.1', '6.3.0.1', '5.0.3.2' | ./myCmd '10.0.0.1', '6.3.0.1', '5.0.3.2' | ./myCmd -ShowBuild
定义接收的参数
使用 param {$argName}
- 逐个制定接收参数的名称
- 限定 param 类型
设置类型不满足的异常提示
1 2 3 4 5param { [typeName] $name = $(throw "Please input an string as name") [typeName] $age = $(throw "Please input an number as age") }
高级函数
作用
- 用于自定义 cmdlets
- 启用 powershell 的高级功能
格式
1 2 3 4[CmdletBinding(<启用功能>)] # eg: [CmdletBinding(SupportsShouldProcess)]
通用参数
位置参数
特点
- 不需要输入参数值
- 只要使用 -Verbose 就是启用了 verbose 功能
-Verbose
- 启用 命令 Write-Verbose 的输出
- 一般输出的打印结果支持 Write-Host
-Debug
- 启用 命令 Write-Debug 的输出
常用参数
特点
- 可以后跟参数值
-ErrorAction
作用
- 当出现错误时,是否继续执行
备选值
Continue
- 继续执行,正常显示错误
SilentlyContinue
- 继续执行,不显示错误
Inquire
- 明确询问,是否继续
- …
风险缓解参数
官方文档
作用
- 查看风险操作内容
- 确认是否执行风险任务
-WhatIf
- 用于测试风险语句
- 即查看有哪些操作,而不实际执行此操作
-Confirm
- 用于确认是否执行关键的任务,<有风险>
使用
- 启用 SupportsShouldProcess
需要在 CmdletBinding 的圆括号内明确指出
- 判断 ShouldProcess
1 2 3 4 5 6 7 8 9# + 明确制定 [CmdletBinding(SupportsShouldProcess)] # + 用来封闭关键代码块,如果制定了 -WhatIf, 就不会执行 If 下面的语句 # + 使用 -Confirm, 在用户确认后,将会执行 If 下面的语句 If($PSCmdlet.ShouldProcess(<目标>, <操作>)) { <关键语句> }注解
- 这里参数 <目标>,<操作> 用来生成提示信息
参数配置
目的
- 配置 cmdlet 接收参数的性质
- eg: 期望数据类型 等
配置项目
- [Parameter()] 属性
- [<Type>] 期望的类型
- $<Name> 参数名称
参数属性
[Parameter(Mandatory = <$true | $false>)]
- $false -> 这是可选参数
- $true -> 这是必需参数
作用
- 制定该参数,是否是必须要制定的
[Parameter(Position = <Int>)]
<Int>
- 从 0 开始
特点
- 无需明确制定形参来分配传递给实参
作用
- 制定 该参数 放置的默认位置
参考教程
- 写的很好,强烈建议看一看
https://powershellstation.com/2017/10/04/specifying-powershell-parameter-position/
1 2 3 4 5 6 7function Test-Position{ [CmdletBinding()] Param([parameter(Position=0)]$parm1, $parm2, $parm3, $parm4) }解说
- .\Test-Position -param1 MyValue
- .\Test-Position MyValue
- 对于上述 自定义 cmdlet, 上面的两种调用方式是等效的
- Position 0 意味着,$param1 被默认放到了 第 0 个 位置上
[Parameter(ValueFromPipeLine = <$false | $true>)]
- 作用
指定,是否接受从 Pipeline 传递过来的参数
- 备选值
$false: 不接受
- $true: 接受
参数验证
| |
powershell 模块
官方文档
导入模块
Import-Module
- -Force
- 强制刷新,覆盖已经导入的模块
导出模块
- Export-ModuleMember
编写声明文档
- New-ModuleManifest -Path <your_path/file.psd1> ….
参考
模块安装位置
- $env::PSModulePath
移除导入的模块
- Remove-Module
编写模块
- 保存文件 "*.psm1"
代码例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15# * 编写函数 function Show-Calendar { param( [DateTime] $start = [DateTime]::Today, [DateTime] $end = $start, $firstDayOfWeek, [int[]] $highlightDay, [string[]] $highlightDate = [DateTime]::Today.ToString() ) #actual code for the function goes here see the end of the topic for the complete code sample } # * 控制导出功能 Export-ModuleMember -Function Show-Calendar
字符串
转移字符
使用 backquote 表示转移
- `a –> \a
- `t –> \t
- `0 –> Null
Here Doc 多行文本
| |
输入 Read-Host
Read-Host
1$name = Read-Host "Please input your name"输入密码
-AsSecureString
1$passcode = Read-Host "Input your pass word"
替换 -Replace
-Replace
1'hello lucy' -replace 'lucy', 'Ray'-IReplace
- 忽略大小写
注意
- 默认情况 -Replace 也是忽略大小写的
-CReplace
- case sensitive
- 大小写敏感
判断相等 -eq
通配符匹配 -Like, -NotLike
例子
1 2"Like it" -like "L*it" "Like it" -NotLike "L*it"语法
- "*" 任意个任意字符
- "?" 单个任意字符
- "." 没有特殊意义
[xyz]
- 枚举字符
[x-z]
- 字符集
正则匹配 -Match, -NotMatch
例子
1 2"Hello" -match "[ao]" # output: True参考
搜索结果
存储位置:$Matches 变量
- $Matches
- 一个 Hashtable
格式化输出 -f
| |
注意
-f 右侧的数据
- 如果是表达式,必须包含在圆括号内
- 类似 其它语言的 format 方法
设置输出宽度
| |
注意
{0, -20}
- 对齐和宽度,变量顺序
- 这里使用逗号 "," 分割
数字格式
参考
例子
1 2 3 4 5 6 7 8# 使用小写字母d:格式化 "Date: {0:d}" -f (Get-Date) Date: 2013/5/31 # 使用大写字母D:格式化 "Date: {0:D}" -f (Get-Date) Date: 2013年5月31注意
{0:d}
- 数字格式,变量位置
- 使用冒号 ":" 分割
字符串方法 调用
参考
例子
1 2("Hello").IndexOf("l") "Hello".IndexOf("l")注意
- 上面两种写法都正确
String 类类方法
| |
Select-String
- powershell version grep
参考
作用
使用 regex 过滤输入文本数据
1Select-String -Path .\Command.txt -Pattern 'Get-Computer' -Context 2, 3-Context
- 选定内容的前面的两行和后面三行也打印出来
无输出,类似 linux /dev/null
打开 .ps1 文件
如何打开 ".ps1" 文件
| |
如何直接打开 ".ps1" 文件
- 创建快捷方式
在快捷方式的属性中设置“Target 输入框”
- 这输入框中输入要运行的命令
隐藏 prompt 窗口
参考
-WindowStyle hidden
1powershell -WindowStyle hidden {echo hello}
执行字符串命令
| |
加载 profile
类似 bash, 使用 "." 号
1. $profile
设置环境变量 Path
参考
暂时性设置
1 2 3 4 5 6$env:Path = "SomeRandomPath"; (replaces existing path) $env:Path += ";SomeRandomPath" (appends to existing path) $env:Path = "d:\soft\bin\" + $env:Path # * 删除 Remove-Item Env:\HTTP_PROXY
use set-content get-content
| |
单行命令设置环境变量
解释:类似 bash, myvar=my_value python hello.py
方法:
启动:eg:
$env:myvar="my_value" python hello.py- 注意: 这里的引号不可少,避免报错
删除使用的环境变量
- eg:
$env:myvar='' - eg:
Remove-Item Env:\myvar
- eg:
heredoc
使用 Ctrl + j 换行
算数运算
- powershell 可以直接进行算术运算,不用借助外部工具
- 官方:about Arithmetic Operators - PowerShell | Microsoft Docs
例如:
1 2>> 6 + 2 8
打开文件
类型:html, txt, ….
- 无限制
打开程序
- 系统设置中关联的 格式对应软件
调用
1 2 3 4 5 6 7 8iex <file> . <file> Invode-Expresssion <file> # eg: . .\path\to\index.html
sudo 工具 —- gsudo
- 软件
gsudo 用途
- 在普通 Powershell 终端中,执行 Administration 终端中才能执行的命令
安装
scoop 为例
1scoop install gsudo
使用
格式
1 2 3 4gsudo <my-command> [options] rem 例子 gsudo wsl
时间测试 – 类似 linux time
命令 Measure-Command
用法
1Measure-Command {echo hello}
oh my posh
安装
1scoop install oh-my-posh配置
1 2oh-my-posh --print-shell oh-my-posh --init --shell pwsh --config $(Join-Path "$(scoop prefix oh-my-posh)\themes" "pure.omp.json") | Invoke-Expression注意
- 配置 要放到 profile.ps1 最前面
- 否则,conda 自动补全失效
路径操作
函数:
- Split-Path
- Join-Path
类似 sed 和 grep 工具
参考:
-replace
| |
-match
| |
encoding
参考:
修改 powershell 的命令输出内容编码格式
使用
chcp 65001命令- 优点:在 cmd 中也可以使用
确定:速度慢,会打印切换成功信息:
1 2 3~ ❯ chcp 65001 Active code page: 65001
powershell 命令
1$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
文章作者
上次更新 2024-01-05 (5c92d1c)