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

相关推荐
gis分享者2 天前
Shell 脚本中如何使用 here document 实现多行文本输入? (中等)
shell·脚本·document·多行·文本输入·here
gis分享者8 天前
Shell 脚本中如何使用 trap 命令捕捉和处理信号(中等)
shell·脚本·信号·处理·trap·捕捉
課代表8 天前
bat 批处理中 FOR 命令的变量修饰符
脚本·bat·环境变量·批处理·路径·扩展名·短名称
chao_6666669 天前
解决 PowerShell 中文乱码问题
网络·学习·powershell
課代表9 天前
PowerShell 目录树生成与递归算法陷阱:目录统计为何从0变多?
脚本·powershell·bat·目录·计数·文件夹·树状结构
gis分享者13 天前
请解释 Shell 脚本中的重定向(redirection)操作及其用途(中等)
shell·脚本·重定向·操作·用途·redirection
lingxiao1688814 天前
vs脚本自动复制生成的文件至指定的位置
c#·脚本
Huazzi.15 天前
PowerShell 配置以及使用指南
windows·git·编辑器·shell·powershell·效率
qq_3176203117 天前
002:windows命令速查手册
windows·powershell·cmd
Irene199118 天前
Bash、PowerShell 常见操作总结
bash·powershell