PowerShell常用的基本操作

更新于 2025-10-03

正则表达式

$match = [System.Text.RegularExpressions.Regex]::Match($line, "^(\?|!)(?:\s+)(.+)$")
if(!$match.Success){
    continue;
}

运算符

逻辑运算符
-and
-or
-xor
-not
!
等式


-eq、-ieq、-ceq - 等于
-ne、-ine、-cne - 不等于
-gt、-igt、-cgt - 大于
-ge、-ige、-cge - 大于或等于
-lt、-ilt、-clt - 小于
-le、-ile、-cle - 小于或等于
匹配
-like、-ilike、-clike - 字符串匹配通配符模式
-notlike、-inotlike、-cnotlike - 字符串与通配符模式不匹配
-match、-imatch、-cmatch - 字符串匹配正则表达式模式
-notmatch、-inotmatch、-cnotmatch - 字符串与正则表达式模式不匹配
替代功能
-replace,-ireplace,-creplace - 替换与正则表达式模式匹配的字符串
包含
-contains、-icontains、-ccontains - 集合包含值
-notcontains、-inotcontains、-cnotcontains - 集合不包含值
-in - 值位于集合中
-notin - 值不在集合中
类型
-is - 这两个对象的类型相同
-isnot - 对象类型不相同

输入

$password = Read-Host "Please input password" -MaskInput
$text = Read-Host "Please input username"

数组

$array = @(1, 2, 3)
$text = $array -join ' '
$array -contains 1
$array -notcontains 1
$array = @("lilith", "malier")
$array -ccontains "lilith"
$array -ccontains "Lilith"

字符串

$string = "hello world"
$string.IndexOf(' ')
$string.Split(' ')
$string.ToLower()
$string.ToUpper()
$string.Trim()
$string.TrimStart()
$string.TrimEnd()

日期

$start = (Get-Date);

$end = (Get-Date);
$timeUsed = "{0:0.00}" -f ($end - $start).TotalSeconds

文件读写

Set-Content -Path "xxxx" -Value "Hello, World!"
Add-Content -Path "xxxx" -Value "Hello again!"
"Hello, World!" | Out-File -FilePath "xxxx" -Encoding UTF8

$stream = [System.IO.StreamWriter] "xxxx"
$stream.WriteLine("Hello, World!")
$stream.Close()

#将文本文件数据读取到数组中
Get-Content -Path $PROFILE

IO


Get-Location
Set-Location -Path C:\Windows
Set-Location -Path C:\Windows -PassThru
Push-Location -Path "Local Settings"
Pop-Location

Get-ChildItem -Path C:\ -Force -Recurse
Copy-Item -Path $PROFILE -Destination $($PROFILE -replace 'ps1$', 'bak') -Force

Copy-Item C:\temp\test1 -Recurse C:\temp\DeleteMe
Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination C:\temp\text
New-Item -Path 'C:\temp\New Folder' -ItemType Directory
Remove-Item -Path C:\temp\DeleteMe -Recurse
浙ICP备19039918号-1