Powershell笔记

操作符

变量前面加$

参数前面加-

注释前面加#

代码结尾无分号

逻辑运算符

比大小

  • -eq‌:等于
  • ‌**-ne**‌:不等于
  • ‌**-gt**‌:大于
  • ‌**-ge**‌:大于等于
  • ‌**-lt**‌:小于
  • ‌**-le**‌:小于等于

布尔运算

-and -or -not -xor

数据类型(常用)

int

float

string\]使用单引号或双引号定义,双引号支持变量插值 ### 判断 if(判断语句){ } ### 循环 #### for循环 ```bash for ($i = 1; $i -le 10; $i++) { Write-Host "当前数字: $i" } ``` #### foreach循环 foreach ($XXX in $XXXs){ } #### while循环 ```bash $count = 1 while ($count -le 5) { Write-Host "计数: $count" $count++ } ``` ### 函数 #### 函数定义 function 函数名{ param( [类型]$参数名1, [类型]$参数名2, [类型]$参数名3=默认值 ) 函数体 } 函数调用 函数名 -参数名1 值 -参数名2 值 -参数名3 值 ### 常用API #### Get-ChildItem得到文件夹成员 Get-ChildItem -Path 路径 -Filter "*.后缀名" #路径写.代表脚本所在的路径 #### Write-Host打印 Write-Host "提示语" -ForegroundColor 颜色 #### ChangeExtension改后缀名 [System.IO.Path]::ChangeExtension($file.Name, ".jpg") #### $PSScriptRoot当前脚本的目录 ## 报错 ### 对webp使用\[System.Drawing.Image\]::FromFile($_.FullName)提示内存不足 System.Drawing.Image不支持webp。 ## 一些脚本 ### 调整jpg的质量 在倒数第2行的-quality后面输入百分比质量,结果在New文件夹。 function ChangeImageQuality{ param ( [string]$imagePath, [string]$outputPath,# 设置输出路径和新的图像 [ValidateRange(0, 100)] [int]$quality = 75# 质量范围从1到100,100为最高 ) Add-Type -AssemblyName System.Drawing # 加载图像 $image = [System.Drawing.Image]::FromFile($imagePath) # 创建一个JPEG编码器的实例 $encoder = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq "image/jpeg" } $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1) $encoderParams.Param = New-Object System.Drawing.Imaging.EncoderParameter([System.Drawing.Imaging.Encoder]::Quality, $quality) # 保存图像 $image.Save($outputPath, $encoder, $encoderParams) # 清理资源 $image.Dispose() $imagePath+"已修改完成" } $path=$PSScriptRoot $newPath=$path+"\New" if (-not (Test-Path -Path $newPath)) { # 文件夹不存在,创建文件夹 New-Item -ItemType Directory -Path $newPath Write-Host "创建了文件夹$newPath" } $files = Get-ChildItem -Path $path -Filter "*.jpg" foreach($file in $files) { #file.Name是完整文件名,BaseName是不包括扩展名的文件名 #$file.Name $newName=$newPath+"\"+$file.BaseName+"_1.jpg" ChangeImageQuality -imagePath $path"\"$file -outputPath $newName -quality 70 } ### 删除文件夹里某类型文件 这里是webp Get-ChildItem -Path "." -Recurse -Filter "*.webp" | Remove-Item -Force

相关推荐
IOT那些事儿3 天前
Windows PowerShell配置Qt5编译运行环境
windows·powershell·qt5
今夕资源网6 天前
powershell工具包 安装升级脚本并设置UTF-8 环境快捷方式创建 将powershell的编码默认改为UTF-8
开发语言·utf-8·powershell·utf-8编码·powershell7·powershell5·设置utf-8编码
代码中介商11 天前
Makefile工程管理完全指南:从基础到实践
linux·脚本
fengyehongWorld11 天前
Powershell 注册.dll类库到系统
powershell
就叫年华吧丶12 天前
Git Bash、CMD 与 PowerShell 的区别详解
linux·git·命令行·powershell·cmd·gitbash
七夜zippoe15 天前
DolphinDB脚本语言:从入门到精通
后端·struts·脚本·语言·dolphindb
Soari17 天前
Ziggo-CaaS-Switch软件配置教程
bash·powershell·tsn 交换机
LAM LAB23 天前
【shell】win10 Powershell字体美化
powershell
humors22125 天前
AI工具合集,不定期更新
人工智能·windows·ai·工具·powershell·deepseek
Yiyi_Coding1 个月前
bat 脚本(真实项目可用):ftp取远程文件
运维·脚本·ftp