Catalyst

PowerShell 备忘

PowerShell 该用还是得用啊。

编码

如果输出中文乱码,注意脚本文件是否是带 BOM 的 UTF-8(……)

变量相关

定义变量:$<变量名>=<值>

连接字符串:使用+号。

字符串中转义双引号:

  • 在单引号引住的字符串中,内中变量不代换,字符不转义,如果打单引号则重复一次单引号。
  • 在双引号引住的字符串中,如果打双引号则重复一次双引号。

输入输出

获取程序输出,例,程序名为 app:

# 输出将输入到管道后。
app | <下一个命令>

# 内容将输出到文件
app > file.txt

# 内容将输出到变量
$output=app

# 放弃命令的输出
app | Out-Null

命令行参数输入:存在$Args数组中,例:$Args[0]

内容处理

正则:

$line="abcd.msi3421"
$reg="\S+\.msi"
if($line -match $reg){
	$Matches[0] #abcd.msi
}

替换

$line="abcd.msi3421"
# 注意中间的逗号
$line -replace "\d+","替换后的内容" #abcd.msi替换后的内容

系统操作

操作文件

# 创建文件 file.toml | New-Item 可以简写成 ni
New-Item file.toml

# 创建文件夹 file.toml
New-Item file.toml -Type directory

# 删除文件 | Remove-Item 可以简写成 rm
Remove-Item file.toml

# 写入文件 $content 是写入的内容
$content | Out-File -FilePath <路径> -Encoding utf8

# 读取文件,不加 Out-String 获取的是 object,加了获得字符串
Get-Content $path | Out-String

按文件名搜索文件:

# 简单用法
Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse]

例,搜索所有文件夹下文件名带~的文件:

Get-ChildItem -Path ./ -Filter "*~"
# 用管道删除查询出来的文件
Get-ChildItem -Path ./ -Filter "*~" | Select -exp Name | rm

遍历文件夹下所有文件,举例:批量转换文件格式为 mp3

Get-ChildItem -Path ./ -Filter *.mkv | ForEach-Object -Process{
if($_ -is [System.IO.FileInfo])
	{
        # .name 带扩展名, .BaseName 不带扩展名
        $nf=$_.BaseName+".mp3"
		ffmpeg -i $_.name $nf
	}
}

返回获取的第 1 个结果

Get-ChildItem -Path $path -Filter *.exe -Name | Select-Object -First 1

测试路径

# 路径是否存在
if (Test-Path -Path ("./resources")){}

# 路径是文件夹
if($_ -is [System.IO.DirectoryInfo]){}

# 路径是文件
if($_ -is [System.IO.FileInfo]){}

参考链接:FileInfo Class

语法

函数

# 定义
function My-Func{
    <内容>
}

# 使用
My-Func

# 带参数
function My-FuncB($arg){
    <内容>
}

# 使用
My-FuncB arg

脚本参数

给自己写的 ps1 文件设置参数

Param(
	[Parameter()]
	$ParameterName
)

例,在脚本开头指定:

# test.ps1
# [int] 可以不要
Param([int]$a,[int]$b)
Write-Host "$a,$b"

运行 ./test -a 1 -b 2 输出 1,2

参数的详细设定如:

Param([int(Mandatory=$true)]$a,[int]$b) # Mandatory 表示 a 为必须有的参数
Write-Host "$a,$b"

或者

Param([switch]$option) #switch表示参数不需要设值(靠出现与否设定布尔值)

更多见此

指定帮助内容:文档

# test.ps1
Param([int]$a,[int]$b)
Write-Host "$a,$b"

<#
.SYNOPSIS
	描述:测试用脚本
.PARAMETER <a>
	a 的数值
.PARAMETER <b>
	b 的数值
#>

输入 Get-Help ./test 时就会出现完整的帮助界面。(中文乱码请确定文件编码是否为UTF8-BOM

参考资料