[英]Powershell read file for filename and path
我有以下腳本,該腳本在目錄中的.zip文件上運行,該目錄具有包含許多文件的整個目錄結構。 然后在這些文件上運行7zip以解壓縮它們,然后將.eml添加到解壓縮的文件中。
& "c:\program files\7-zip\7z.exe" x c:\TestZip -r -oC:\TestRestore 2> c:\TestLog\ziplog.txt
& "c:\program files\7-zip\7z.exe" x c:\TestRestore -r -aos -oc:\TestExtract 2> c:\TestLog\sevenzip.txt
gci -path "c:\TestExtract" -file | rename-item -newname {$PSItem.name + ".eml"}
我的問題是7zip有時無法從這些文件中進行最終提取,因為7zip不會將其視為存檔。 我發現,如果僅將.eml放在這些特定文件上,則可以將其作為電子郵件進行訪問。 因此,當壓縮文件無法提取時,我將輸出寫入sevenzip.txt文件。 我需要幫助的是如何讀取此文件以獲取文件名並將它們放置在目錄中,以便添加.eml擴展名。 sevenzip.txt文件中的輸出示例如下所示
ERROR: c:\TestRestore\0\0\54\3925ccb78f80d28b7569b6759554d.0_4011
Can not open the file as archive
ERROR: c:\TestRestore\0\0\5b\6fa7acb219dec5d9e55d4eadd6eb1.0_3958
Can not open the file as archive
任何幫助將不勝感激如何做到這一點。
對不起,所有評論,但我正在努力
$SourceFile = 'c:\testlog\sevenzip.txt'
$DestinationFile = 'c:\testlog\testlogextractnew.txt'
$Pattern = 'c:\\TestRestore\\' (Get-Content $SourceFile) |
% {if ($_ -match $Pattern){$_}} |
Set-Content $DestinationFile (Get-Content $DestinationFile).replace('ERROR: ', '') |
Set-Content $DestinationFile (Get-Content$DestinationFile).replace('7z.exe : ', '') |
Set-Content $DestinationFile
如果沒有其他錯誤,則可以使用正則表達式模式匹配從文件中挑選那些文件名:
$filesToFix = Select-String -Pattern "ERROR: (.*)" -LiteralPath 'c:\testlog\sevenzip.txt' |
ForEach-Object {$_.Matches.Groups[1].Value}
並可能用
$filesToFix | ForEach-Object {
Rename-Item -LiteralPath $_ -NewName {"$_.eml"}
}
如果可能還有其他錯誤,而您只想要這些錯誤,則需要進行更多的匹配工作:
$fileContent = Get-Content -LiteralPath 'c:\testlog\sevenzip.txt' -Raw
$filesToFix = [regex]::Matches($fileContent,
"ERROR: (.*)\nCan not open the file as archive",
'Multiline') |
ForEach-Object {$_.Groups[1].Value}
這就是我在注釋中最后要講的內容,因為我不知道如何格式化,但現在已經解決了,因此希望這樣可以使它更容易理解(如果有用)。
本節創建所有無法提取的文件的列表及其目錄位置。 在下一節中使用。
$SourceFile = 'c:\\testlog\\sevenzip.txt' $DestinationFile = c:\\testlog\\testlogextractnew.txt' $Pattern = 'c:\\\\TestRestore\\\\' (Get-Content $SourceFile) | % {if ($_ -match $Pattern){$_}} | Set-Content $DestinationFile (Get-Content $DestinationFile).replace('ERROR: ', '') | Set-Content $DestinationFile (Get-Content $DestinationFile).replace('7z.exe : ', '') | Set-Content $DestinationFile
這只是一些結果檢查
Get-Content C:\\testlog\\testlogextractnew.txt | Measure-Object –Line > c:\\testlog\\numberoffilesthatfailed.txt
這會將txt文件中列出的所有文件復制到另一個目錄
c:\\testlog\\testlogextractnew.txt | copy-item -destination "c:\\TestCopy"
這會將當前擴展名重命名為.eml
gci -path "C:\\TestCopy" -file | rename-item -newname { [io.path]::changeextension($_.name, "eml")}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.