我正在嘗試制作簡單的 powershell 腳本,該腳本每天都會歸檔檔案。每個檔案在其名稱的開頭都有日期,例如:20211220_Something.csv, 20211220_SomethingElse.txt, 20211219_Something.csv, 20211219_SomethingElse.txt等...
我想制作一個腳本,從特定目錄中收集所有帶有擴展名(*.txt、*.csv、*.xslx)的檔案,這些檔案是:
\\Main\Files 和 \\Main\Files\SecondaryFiles
并將具有上述擴展名的所有檔案歸檔到例如 \\Main\Files\archive\2021\12\20.12.zip
其中 2021、12 和 20.12 是檔案名前綴中提供的日期元素。在 20.12.zip 中,我們擁有\\Main\Files名為“SecondaryFiles”的目錄中的所有檔案,其中包含\\Main\Files\SecondaryFiles. 存檔后,我想洗掉我剛剛壓縮的所有檔案。
現在我有這段代碼,它回圈遍歷目錄中的所有檔案\Main\并提取日期前綴。我曾嘗試使用 [Datetime]::parseexact() 方法,但它不起作用,因為我的回圈回傳整個路徑。任何人都知道如何解決這個問題?
$Date = Get-Date
$Day = $Date.Day
$Month = Date.Month
$Year = $Date.Year
$directoryPath = "\\Main\Files\archive'" $Year "\" $Month
$files = Get-ChildItem -Path "\\Main\Files" -Include *.txt, *.csv, *.xlsx -Recurse
for ($i=0; $i -lt $files.Count; $i ){
$temp = $files[$i].FullName.split("_")[1]
}
if(!Test-Path -path $directoryPath){
New-Item -ItemType directory -Path $directoryPath
}
Compress-Archive -Path "\\Main\Files", "\\Main\Files\*.txt", "\\Main\Files\*.csv", "\\Main\Files\*.xlsx", "\\Main\Files\SecondaryFiles\*.txt", "\\Main\Files\SecondaryFiles\*.csv", "\\Main\Files\SecondaryFiles\*.xlsx" -Update -DestinationPath "\\Main\Files\archive\$Year\$Month\$Day.$Month.zip"
然后我從原始目錄中洗掉專案。
另外值得一提的是,我無法確定檔案夾是否僅包含今天的檔案。因此,當整個星期都有檔案時,腳本應該可以正常作業,我們可以說20211214直到20211220。
因此,我再次想像上面那樣壓縮存檔檔案,但是今天的日期路徑將包含從檔案名前綴中提取的日期。
uj5u.com熱心網友回復:
用于Group-Object將具有相同日期前綴的所有檔案組合在一起,并使用它來創建輸出子目錄、最終的 .zip 檔案以及在壓縮后洗掉原始檔案。
$sourcePath = '\\Main\Files'
$destination = '\\Main\Files\archive'
Get-ChildItem -Path $sourcePath -Include '*.txt', '*.csv', '*.xlsx' -Recurse |
# select only files that start with 8 digits followed by an underscore
Where-Object { $_.BaseName -match '^\d{8}_' } |
# group the files on the date part and loop trhough these groups
Group-Object { $_.BaseName.Substring(0,8) } | ForEach-Object {
# split the date part into variables. Automatic variable $_ represents one Group,
# so we can take that group's Name to split into date parts
$year, $month, $day = $_.Name -split '(\d{4})(\d{2})(\d{2})' -ne ''
# construct the target folder path for the zip file
$targetPath = Join-Path -Path $destination -ChildPath ('{0}\{1}' -f $year, $month)
# create the new sub directory if it does not yet exist
$null = New-Item -Path $targetPath -ItemType Directory -Force
# create the full path and filename for the zip file
$zip = Join-Path -Path $targetPath -ChildPath ('{0}.{1}.zip' -f $day, $month)
# compress the files in the group
Compress-Archive -Path $_.Group.FullName -DestinationPath $zip -Update
# here is where you can delete the original files after zipping
$_.Group | Remove-Item -WhatIf
}
注意:我已經添加開關-WhatIf到Remove-Itemcmdlet的。這是一個安全開關,因此您實際上還沒有洗掉任何內容。該cmdlet現在只顯示什么將被洗掉。一旦您對此輸出感到滿意,請移除該-WhatIf開關,以便洗掉檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388244.html
下一篇:將程式置于前臺或啟動它
