新建文件夾
New-Item -ItemType Directory -Force -Path $TargetPath
復制文件夾到另外文件夾
Copy-Item <源文件夾> <新文件夾> -recurse -force
復制文件(與修改文件名)
// 達到復制文件到新文件夾,及修改文件名效果
copy-item $testPic $nowselectHDD// 目標文件不能包含路徑,既不能移動到新文件夾
rename-Item $filePath -NewName $NewFilePath
最新修改文件
$allFolder= Get-ChildItem "C:\Target"
$newFolder=($allFolder|Sort-Object LastWriteTime -Descending|select -first 1).name//1. Get-ChildItem獲取所有文件
//2. Sort-Object LastWriteTime -Descending 排序
//3. select -first 1 選擇前 1 個
//4. .name 只獲取文件名。如果沒有會出現制表
跳過最新的前面n個文件
$files = $allPIc | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip 2
if ($files.count -gt 0)
{foreach($file in $files){Remove-Item $file.FullName -Recurse -Force}
} //1. Select-Object -Skip 2 排除前兩個文件
//2. foreach 刪除所有選擇文件。
//3. 最后剩下1跳過的文件。
刪除文件
Remove-Item?c:/scripts/*?-recurse
$TargetFolder = "c:\Test"
$Files = get-childitem $TargetFolder -force
Foreach ($File in $Files)
{
$FilePath=$File.FullName
Remove-Item -Path $FilePath -Recurse -Force
}
可以使用“get-help remove-item -full”命令來查看Remove-Item的完整幫助文檔,內容如下:
PS C:\> get-help remove-item -full
復制文件
Copy-Item c:/scripts/Test.txt c:/Test
Copy-Item c:/scripts/* c:/Test
Copy-Item c:/scripts/*.txt c:/Test
Copy-Item c:/scripts c:/Test –recurse //復制文件夾
獲取文件名
[System.IO.Path]::GetFileNameWithoutExtension("test.mm.txt")
//結果為test.mm
獲取txt內容
$txt=(Get-Content d:\1.txt -TotalCount 2)[-1].Trim()$txt[0] //第一行//-TotalCount 表示獲取txt內行數,2表示取前2行
//[-1] 表示最后一個
//Trim() 去空格
輸出到txt文件
"Hello World!" | Out-File d:\1.txt
$fileCount | Out-File -Append d:\1.txt //追加
獲取txt所有內容,以及行數
$statusList = Get-Content ./StatusList.txt
$statusList[0] //第一行$statusList.length//所有行
比較文件內容
PS C:\> $old=Get-Content c:\test\File1.txt
PS C:\> $new=Get-Content c:\test\File2.txt
PS C:\> Compare-Object $old $new
其他文件名操作參考
PowerShell文件系統(三)導航文件系統 – PowerShell 中文博客
打包壓縮
Compress-Archive -LiteralPath <PathToFiles> -DestinationPath <PathToDestination>
Compress-Archive -LiteralPath <PathToFolder> -DestinationPath <PathToDestination># PathToFiles 文件集合,用逗號隔開
# PathToDestination zip包名# PathToFolder 需要壓縮文件夾
參考?(11條消息) powershell 壓縮_如何使用PowerShell壓縮(和解壓縮)文件_culiyuan8310的博客-CSDN博客