常用集合,方便后續復制粘貼
# 判斷文件在不在
# 輸出文件
IF(!(test-path $filePath))
{$result|Out-File $filePath
}# 讀取txt
$result=(Get-Content $filePath -TotalCount 1).Trim()
$result# 刪除文件
remove-item "C:\wistron\Datasource\spiderPort.txt"
Test-Path,檢查路徑是否存在。
語法:Test-Path <路徑>
說明:這里的路徑可以是:文件、文件夾、HKLM路徑、環境變量env:路徑
Test-Path D:\q.txt
Test-Path C:\Scripts
Test-Path C:\Scripts\Archive\*.ps1
字符串Join命令
"$TargetPath", "$copyFileName" -Join "\"
-Join("$portCount","$ACPIStatus","$VolLetter") //直接拼接
字符串split命令
("$userInput" -split " ").count //空格分組,然后計算個數
("$userInput" -split " ")[$num] $a="abc:def:ghi"
$a -Split ":"
$path.Split(".")[-1] Split-Path -Parent "sourceFullPath" //獲取所在文件夾
修改文件名
rename-Item 'D:\For PS\A.txt' -NewName 'aa.txt'
replace
$itemCommonName=$testItem.Replace("`\","-")
$itemCommonName=$testItem.Replace("`/","-")
null語句
PS C:\Users\> $a # 當$a不賦予任何值時
PS C:\Users> $a -eq ""
False
PS C:\Users> $a -eq $null
True
PS C:\Users> $a = "" # 當$a設為空字符串時
PS C:\Users> $a -eq ""
True
PS C:\Users> $a -eq $null
False
可以看到,當$a不賦予任何值是,結果為Null,在powershell 中表示為$null
if語句
$a="S0"
if($acpiCount -eq 1)
{$a="S3"
}
elseif($acpiCount -eq 2)
{$a="S4"
}
If(!(test-path $TargetPath))
{New-Item -ItemType Directory -Force -Path $TargetPath
}$filePath ="$TargetPath", "$copyFileName" -Join "\"
$filePath|Out-File C:\bat\Output_filePath.txtIF(!(test-path $filePath))
{Copy-Item $sourceFullPath -destination $filePath
}
Powershell 中的比較運算符
-eq :等于
-ne :不等于
-gt :大于
-ge :大于等于
-lt :小于
-le :小于等于
-contains :包含
-notcontains :不包含布爾運算-and :和
-or :或
-xor :異或
-not :逆