2017-04-21 30 views
0

我很好奇如何使用PowerShell在目錄中查找最新的.bak文件並將其壓縮。在目錄中查找最新的.bak文件並將其壓縮

我已經能夠通過找到最新的備份:

Get-ChildItem C:\* -Include *.bak 

,但我有問題荏苒找到文件。任何幫助,將不勝感激!

+0

如果你正在使用PowerShell v5 +還有一個叫做'Compress-Archive'的新命令:https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.archive/compress-archive –

回答

1

SortSelect是你的朋友在這裏,然後通過管道到Compress-Archive(僅適用於PS V5起)

$source = "C:\" 
$filetype = "bak" 

Get-ChildItem "$source\*" -Include "*.$filetype" | sort LastWriteTime | select -last 1 | Compress-Archive -DestinationPath "$source\latest_backup.zip" 

編輯:

要使用的文件名郵編:

$file = Get-ChildItem "$source\*" -Include "*.$filetype" | sort LastWriteTime | select -last 1 
Compress-Archive -Path $file -DestinationPath "$source\$($file.BaseName).zip" 
+0

這很棒。非常感謝你! –

+0

你好詹姆斯,有沒有辦法讓它採用它找到的文件的名稱,並且它是名稱,而不必在腳本中創建名稱? –

+0

@GeoffreySherman是的,看編輯回答 –

相關問題