本篇着重收集在编写powershell脚本时经常用到的变量和方法等,会持续更新。
文件路径相关
获取脚本全路径
[String]$scriptPath = $MyInvocation.MyCommand.Path获取上一级目录
[String]$dirPath = Split-Path -Path $scriptPath获取指定后缀的所有文件
Get-ChildItem *.css -Name | ForEach-Object { $fileNames.Add($_) }
文件读写相关
读取txt文件内容
# -Raw 标签会将文本整体读取为一个字符串,不添加此标签会按行返回数组 Get-Content $file -Raw -Encoding utf8写入文本
# UTF-8编码 [System.IO.File]::WriteAllText($name, $content, (New-Object System.Text.UTF8Encoding($false)))
运行程序相关
获取退出代码
$exitCode = $LASTEXITCODE
正则表达式
选择第一个匹配项
([Regex]::Matches($contentStr, $regexStr) | Select-Object -First 1).Value替换文本
#大小写不敏感,支持正则 $contentStr -replace "old", "new" #大小写敏感,支持正则 $contentStr -creplace "old", "new" #大小写敏感,不支持正则 $contentStr.Replace("old", "new")将关键符号转义为普通字符
[Regex]::Escape($str)获取不带扩展的文件名的路径
[System.IO.Path]::GetFileNameWithoutExtension($fileName)
模板字符串
'{0}{1}' -f $str1, $str2
代码
数据结构
# 数组 $arr = @(1, 2, 3) # 哈希表(无序) $hashTable = @{one = 1; two = 2} # 字典(有序) $dictionary = [ordered]@{one = 1; two = 2} # 列表 $list = [System.Collections.Generic.List[String]]::new() # 集合 $set = [System.Collections.Generic.HashSet[String]]::new() # StringBuilder $sb = [System.Text.StringBuilder]::new()类型转换
[Int]$id = 0 [Int]::TryParse($str, [ref]$id) > $null比大小
-lt #小于 -le #小于或等于 -gt #大于 -ge #大于或等于 -eq #等于 -ne #不等于
合并多个字符
# 方式一 [String]::Join(" ", $strArr) # 方式二 $strArr -join " "
控制台输出
彩色字符串
Write-Host "Hello" -NoNewline -ForegroundColor green未经修改地打印
[System.Console]::WriteLine("raw")打印哈希表
function Print-Table { param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)]$table ) process { foreach ($key in $table.Keys) { Write-Host "$key = $($table[$key])" } } }
检测管理员权限
function Test-IsAdmin { return (net session 2>$null) -ne $null }
各位如果觉得有用请点击下方的打赏,扫描二维码给我投币,创作不易,感谢支持!