Cheat Sheet

获取对象信息 Get-Member

  • 别名 gm
  • eg: ls | gm

注释

    • 单行注释
  • <# … #>

    • 多行注释

Powershell

快捷键模式

后台运行任务—-Job 相关命令

https://blog.csdn.net/litterfrog/article/details/104001641

https://www.jb51.net/article/136289.htm 详细

  • 工具

    • Start-Job

      • 启动后台工具
      • alias: sajb

        1
        2
        
        Start-Job -ScriptBlock {emacs -q}
        # 效果和 runemacs -q 类似
    • Get-Job

      • 查看启动的后台任务
      • alias: gjb, ps

        1
        
        Get-Job
    • Stop-Job

      1
      2
      
      Stop-Job -Id 3
      # id 可以由 Get-Job 查看
    • Remove-Job

      1
      
      Remove-Job -Id 3

查找帮助

  • Get-Help

    • alias: man

      1
      2
      
      man -Online man
      man Get-Job

正则匹配

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# raw input: inet 172.22.118.80  netmask 255.255.240.0  broadcast 172.22.127.255
#            inet6 .......
# * grep 'inet ' --> this specifically include whitespace
$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"   # ---> find inet 172 ... line

# * string regex
# ** execute matching
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
# ** extract match result
$matches[0]
  • 正则语法

    • 匹配 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
3
4
$null  # 空
$true  # True
$false # False
$_     # 当前处理的元素

变量

  • 例子

    1
    2
    
    $myVar = 3
    $name="Lucy"
  • 语法

    • “声明” 和 “使用” 都要加上 $
    • 赋值等号“=”前后,空格有无都可以

      • 不同于 bash, 必须没有空格

获取类型

  • $var.GetType()

数据结构

数组

  • 元素类型

    • 任意类型,因为 powershell 是动态语言
  • 格式

    • 元素分隔符

      • 逗号 ","
    • @(, , , …)
  • 创建

    1
    
    $my_array = @(elem0, elem1, elem2, ...)
  • 索引

    • zero-indexed

      1
      2
      3
      4
      5
      
      echo $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
    12
    
    If ( 条件 )
    {
        语句
    }
    ElseIf ( 条件 )
    {
        语句
    }
    Else
    {
        语句
    }
  • switch

    1
    2
    3
    4
    5
    6
    7
    8
    
    switch (<表达式>)
    {
        <测试值> { <语句>; break}
        ...
        Default { <语句>}
    
    
    }

循环

  • For

    1
    2
    3
    4
    5
    
    # <> 代表语句
    For (<>; <>; <>)
    {
        <>
    }
  • ForEach

    1
    2
    3
    
    ForEach (<elem> in <collection>) {
        <statements>
    }
  • While

    1
    2
    3
    4
    
    While (<测试条件>)
    {
    ...
    }
  • Do While

    1
    2
    3
    4
    
    Do
    {
        ...
    } While(<条件>)
  • Do Untile

    1
    2
    3
    4
    
    Do
    {
        ...
    } 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
    4
    
    for ($i = 0; $i -lt 10; i++)
    {
    ...
    }

ForEach

  • 例子

    1
    2
    3
    4
    
    ForEach ($elem in $arr)
    {
    ...
    }

While

  • 例子

    1
    2
    3
    4
    
    While ($var -gt 3)
    {
    ...
    }

Write-Host Vs Write-Output

在字符串中使用变量

  • 类似 bash

    • 双引号,变量被替换成变量内容
    • 单引号,原样输出,不作处理

使用 .Net 类

创建类 New-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)

访问类

1
2
3
4
5
6
7
8
9
# 访问
[System.Version]

# 类型转换
[System.Version] "1.0.3.4"

# 访问类静态元素
[System.Version]::New()    # 方法
[System.ConsoleColr]::Red  # 枚举常量

类型转换

1
2
3
4
5
6
[Int] 1.7
# output: 2
# 转换成 Int 类型

[System.Version] "1.0.3.4"
# 把 "1.0.3.4" 转换成 System.Version 对象

定义类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class <ClassName>
{
<hidden | static> [typeName] $<fieldName>

<hidden | static> <ConstructFunctionName> (<arg>, <arg>, ...)
{ ... }

<hidden | static> [typeName] <functinName> (<arg>, <arg>, ...)
{ ... }
}

定义 枚举类型

1
2
3
4
5
6
7
8
9
enum MyColor
{
Red = 1
Green = 2
}


# 使用
[MyColor]::Red
  • 注意

    • 使用方括号把枚举类,包起来

命令记录

Get-Member

  • 获取对象信息
  • 别名 alias

    • gm
  • 调用方法

    1
    
    get-location | gm

New-Object

  • 创建对象
  • 用法

    1
    
    New-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)

命令历史访问

参考:

方法:

  1. 获取保存历史文件目录

    (Get-PSReadlineOption).HistorySavePath
    
  2. 查看历史

    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
      2
      
      Get-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
    25
    
    param    # 制定接收参数
    {
    $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
    5
    
    param
    {
    [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> 参数名称

参数属性

  1. [Parameter(Mandatory = <$true | $false>)]

    • $false -> 这是可选参数
    • $true -> 这是必需参数
    • 作用

      • 制定该参数,是否是必须要制定的
  2. [Parameter(Position = <Int>)]

    • <Int>

      • 从 0 开始
    • 特点

      • 无需明确制定形参来分配传递给实参
    • 作用

      • 制定 该参数 放置的默认位置
    • 参考教程

      • 写的很好,强烈建议看一看
      • https://powershellstation.com/2017/10/04/specifying-powershell-parameter-position/

        1
        2
        3
        4
        5
        6
        7
        
        function Test-Position{
        [CmdletBinding()]
        Param([parameter(Position=0)]$parm1,
                     $parm2,
                     $parm3,
                     $parm4)
        }
        • 解说

          • .\Test-Position -param1 MyValue
          • .\Test-Position MyValue
          • 对于上述 自定义 cmdlet, 上面的两种调用方式是等效的
          • Position 0 意味着,$param1 被默认放到了 第 0 个 位置上
  3. [Parameter(ValueFromPipeLine = <$false | $true>)]

    • 作用
  4. 指定,是否接受从 Pipeline 传递过来的参数

    • 备选值
  5. $false: 不接受

    • $true: 接受

参数验证

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# * 枚举可能值,  还可提供自动补全
[ValidateSet(<元素>, <元素>, ...)]
# * 长度范围
[ValidateLength(<min>, <max>)]
# * 取值范围
[ValidateRange(<min>, <max>)]
# * 评估表达式,返回 true 和 false
[ValidateScripte({<表达式>})]
# * 正则匹配
[ValidatePattern(<正则表达式>)]

powershell 模块

编写模块

  • 保存文件 "*.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 多行文本

1
2
3
4
@" one line
next line
finally
"@

输入 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

格式化输出 -f

1
2
3
4
5
6
"{0} pile of books" -f 500
# -> 500 pile of books

# * 包含表达式
"{0} pile of books" -f (500/10)
# -> 50 pile of books
  • 注意

    • -f 右侧的数据

      • 如果是表达式,必须包含在圆括号内
  • 类似 其它语言的 format 方法

设置输出宽度

1
2
3
4
5
6
7
8
9
PS> dir | ForEach-Object { "{0,-20} = {1,10} Bytes" -f $_.name, $_.Length }
Virtual Machines     =            Bytes
VirtualBox VMs       =            Bytes
a                    =      12022 Bytes
a.csv                =        986 Bytes
a.ps1                =         18 Bytes
a.txt                =        946 Bytes
funshion.ini         =       6798 Bytes
PUTTY.RND            =        600 Bytes
  • 注意

    • {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}

      • 数字格式,变量位置
      • 使用冒号 ":" 分割

字符串方法 调用

String 类类方法

1
2
$array = $(1, 2, 3)
[String]::Join(",", $array)

Select-String

打开 .ps1 文件

如何打开 ".ps1" 文件

1
powershell -File "/path/to/file.ps1"

如何直接打开 ".ps1" 文件

  • 创建快捷方式
  • 在快捷方式的属性中设置“Target 输入框”

    • 这输入框中输入要运行的命令

隐藏 prompt 窗口

执行字符串命令

1
powershell -Command "& {your_script}"

加载 profile

  • 类似 bash, 使用 "." 号

    1
    
    . $profile

设置环境变量 Path

use set-content get-content

1
2
Set-Content -Path Env:\HTTP_PROXY -Value "http://localhost:7890"
Get-Content -Path Env:\HTTP_PROXY

单行命令设置环境变量

解释:类似 bash, myvar=my_value python hello.py

方法:

  1. 启动:eg: $env:myvar="my_value" python hello.py

    • 注意: 这里的引号不可少,避免报错
  2. 删除使用的环境变量

    • eg: $env:myvar=''
    • eg: Remove-Item Env:\myvar

heredoc

使用 Ctrl + j 换行

算数运算

打开文件

  • 类型:html, txt, ….

    • 无限制
  • 打开程序

    • 系统设置中关联的 格式对应软件
  • 调用

    1
    2
    3
    4
    5
    6
    7
    8
    
    iex <file>
    
    . <file>
    
    Invode-Expresssion <file>
    
    # eg:
    . .\path\to\index.html

sudo 工具 —- gsudo

  • 软件 gsudo
  • 用途

    • 在普通 Powershell 终端中,执行 Administration 终端中才能执行的命令

安装

  • scoop 为例

    1
    
    scoop install gsudo

使用

  • 格式

    1
    2
    3
    4
    
    gsudo <my-command> [options]
    
    rem 例子
    gsudo wsl

时间测试 – 类似 linux time

  • 命令 Measure-Command

    • 用法

      1
      
      Measure-Command {echo hello}

oh my posh

  • 安装

    1
    
    scoop install oh-my-posh
  • 配置

    1
    2
    
    oh-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

1
2
3
4
5
6
# 语法
<input> -replace <regular-expression>, <substitute>


"book" -ireplace "B", "C" # Case insensitive
"book" -creplace "B", "C" # Case-sensitive; hence, nothing to replace

-match

1
2
3
4
5
6
7
# Partial match test, showing how differently -match and -like behave
"PowerShell" -match 'shell'        # Output: True
"PowerShell" -like  'shell'        # Output: False

# Regex syntax test
"PowerShell" -match    '^Power\w+' # Output: True
'bag'        -notmatch 'b[iou]g'   # Output: True

encoding

参考:

修改 powershell 的命令输出内容编码格式

  1. 使用 chcp 65001 命令

    • 优点:在 cmd 中也可以使用
    • 确定:速度慢,会打印切换成功信息:

      1
      2
      3
      
      ~
      ❯ chcp 65001
      Active code page: 65001
  2. powershell 命令

    1
    
    $OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding