PowerShell

# 查看 Powershell 版本信息
$PSVersionTable

基础语法

逻辑判断

$condition = $true
if ( $condition )
{
    Write-Output "The condition was true"
}

运算符

在 PowerShell 中, & 代表调用运算符 官方文档

// 使用示例
$print = "echo"

& $print "Hello World"

数组与循环

定义数组:

$arrayA = 1, 2, 3, 4
$arrayB = (1, 2, 3, 4)

循环数组:

# 普通循环
for($i; $i -le 10; $i++){
  # do something...
}

# 循环数组元素
# 注意是 Foreach
Foreach($el in $array){
  # do something...
}

命令

设置命令别名 (Alias)

官方文档

# 获取所有的命令别名
Get-Alias

# 为 Get-Content 设置一个名叫 cat 的别名
New-Alias -Name cat -Value Get-Content

为别名添加默认参数:

  1. 创建一个函数,在函数体当中添加命令和其参数
  2. 通过别名调用刚才声明的函数
  3. 调用命令别名
# 1.创建函数, 使函数打印 "Hi! The command with parameter!"
function print-something {echo "Hi! The command with parameter!"}

# 2.设置别名
New-Alias -Name sayHi -Value print-something

# 3.调用命令别名
sayHi

(Get-Content) cat

官方文档

可以用于查看文本文件

全称: Get-Content
简写: cat

# 输出结果的中文会是乱码
cat README.txt

# 指定编码, 将无乱码
cat -Encoding utf8 README.txt

通过设置别名, 默认带参 -Encoding utf8

function Get-Content-utf8 {

    param (
            $Path
        )

    Get-Content -Encoding utf8 $Path
}

# 注意这里添加了 "-Option AllScope" 参数
Set-Alias -Name cat -Value Get-Content-utf8 -Option AllScope

查找命令位置

# 获取命令实际路径
Get-Command -Name code

# 简写
Get-Command

路径操作

测试路径

Test-Path

# 测试路径是否存在
Test-Path -Path "路径"

# 测试是否为文件
Test-Path -PathType leaf -Path "路径" 

文件名操作

# 这里实际调用的是 C# 的 .net 的函数
# 修改文件后缀
[System.IO.Path]::ChangeExtension('D:\test\output1.jpg', 'mp4')
# 输出为 D:\test\output1.mp4 

# 获取文件后缀
[System.IO.Path]::GetExtension("路径")

# 获取文件名
[System.IO.Path]::GetFileName("路径")

命令行参数

参考: 脚本中的参数

powershell 中处理命令行参数较为简单, 只需在文件开头添加 param 部分即可:

  • [string] 代表字符串参数
  • [switch] 代表布尔参数

test.ps1 例:

param(
    [Parameter()]
    # 格式: [数据类型]$参数名
    [string]$参数1

    # 默认参数
    [string]$参数2 = "default value"

    # 布尔参数
    [switch]$force = $false
)

# 访问参数
echo "$参数1 $参数2"
[Parameter()] 用于保证命令行输入的参数为其声明后的指定参数

调用脚本:

./test.sh -参数1 Hello -参数2 World!

# 输出结果
Hello World!

除此之外, 还可以使用位置参数:

# 第一个参数, 以此类推
$args[0]

# 参数数量
$args.count

powershell 调用 .net

power!!!

比如你想调用 .net 的输出函数:

// C#
Console.WriteLine("This is C#");
# 在 powershell 中调用 .net 输出函数

[Console]::WriteLine("This function is from .net")

杂项

换行

powershell 通过反引号换行 `

echo "Hi " `
"It's PowerShell!"

# 输出结果:
# Hi
# It's PowerShell!

ssh 下使用 vim, 如果点击鼠标右键进入了 visual 模式, 无法粘贴

可以尝试 Shift + 鼠标右键 来进行文本粘贴操作


有关输入重定向:

在windows上你不能直接把文件挂载到标准输入(stdin)里, 但可以通过 Get-Content 将文件内容输入到管道, 在输入到其他命令中

# 例:
cat ./test.sh | bash -s 

/dev/null

Windows 下可没这个东西 /dev/null

但 powershell 有 $null 这个变量

详见: 关于 $null 的各项须知内容
Write-Output "I don't want this message" > $null
最后修改:2024 年 12 月 18 日
如果觉得我的文章对你有用,请随意赞赏