当前,我正在编写一个脚本,用于将错误压缩的PDF文件移动到某个文件夹。我已经做到了。接下来,我需要开始工作的是将压缩的.pdf文件解压缩到另一个文件夹中。
这是我的整个脚本。除了最后两行以外的所有内容都专用于查找压缩并移动的PDF文件。
在第一部分中,脚本检查文件夹中每个pdf文件的前几个字节。如果它们以“ PK *”开头,则它们是zip文件,并移至压缩文件夹中。 对于每个PDF / zip文件,folder next to it.
中都有一个关联的HL7文件。这些还需要移至同一文件夹。需要从那里解压缩zip文件,然后将其重新定位为“解压缩”
最后两行用于解压缩。
$pdfDirectory = 'Z:\Documents\16_Med._App\Auftraege\PDFPrzemek\struktur_id_1225\ext_dok'
$newLocation = 'Z:\Documents\16_Med._App\Auftraege\PDFPrzemek\Zip'
Get-ChildItem "$pdfDirectory" -Filter "*.pdf" | foreach {
if ((Get-Content $_.FullName | select -First 1 ) -like "PK*") {
$HL7 = $_.FullName.Replace("ext_dok","MDM")
$HL7 = $HL7.Replace(".pdf",".hl7")
move $_.FullName $newLocation;
move $HL7 $newLocation
}
}
Get-ChildItem 'Z:\Documents\16_Med._App\Auftraege\PDFPrzemek\Zip' |
Expand-Archive -DestinationPath 'Z:\Documents\16_Med._App\Auftraege\PDFPrzemek\Zip\unzipped' -Force
遗憾的是,这不起作用。
我怀疑是因为这些文件没有.zip扩展名。适用于Expand-Archive
的唯一过滤器是.zip。
所以我需要找到一种方法来使该文件解压缩,即使它们没有合适的扩展名...
答案 0 :(得分:0)
就像@Ansgar所说的那样,这是可行的方法:
Param (
$SourcePath = 'C:\Users\xxx\Downloads\PDF',
$ZipFilesPath = 'C:\Users\xxx\Downloads\ZIP',
$UnzippedFilesPath = 'C:\Users\xxx\Downloads\Unzipped'
)
$VerbosePreference = 'Continue'
#region Test folders
@($SourcePath, $ZipFilesPath, $UnzippedFilesPath) | Where-Object {
-not (Test-Path -LiteralPath $_)
} | ForEach-Object {
throw "Path '$_' not found. Make sure that the folders exist before running the script."
}
#endregion
#region Get all files with extension .pdf
$Params = @{
Path = Join-Path -Path $SourcePath -ChildPath 'ext_dok'
Filter = '*.pdf'
}
$PDFfiles = Get-ChildItem @Params
Write-Verbose "Got $($PDFfiles.count) files with extension '.pdf' from '$($Params.Path)'"
#endregion
#region Move PDF and HL7 files
$MDMpath = Join-Path -Path $SourcePath -ChildPath 'MDM'
foreach ($PDFfile in ($PDFfiles | Where-Object {
(Get-Content $_.FullName | Select-Object -First 1) -like 'PK*'})
) {
$MoveParams = @{
Path = $PDFfile.FullName
Destination = Join-Path -Path $ZipFilesPath -ChildPath ($PDFfile.BaseName + '.zip')
}
Move-Item @MoveParams
Write-Verbose "Moved file '$($MoveParams.Path)' to '$($MoveParams.Destination)'"
$GetParams = @{
Path = Join-Path -Path $MDMpath -ChildPath ($PDFfile.BaseName + '.hl7')
ErrorAction = 'Ignore'
}
if ($HL7file = Get-Item @GetParams) {
$MoveParams = @{
Path = $HL7file
Destination = $ZipFilesPath
}
Move-Item @MoveParams
Write-Verbose "Moved file '$($MoveParams.Path)' to '$($MoveParams.Destination)$($HL7file.Name)'"
}
}
#endregion
#region Unzip files
$ZipFiles = Get-ChildItem -Path $ZipFilesPath -Filter '*.zip' -File
foreach ($ZipFile in $ZipFiles) {
$ZipFile | Expand-Archive -DestinationPath $UnzippedFilesPath -Force
Write-Verbose "Unzipped file '$($ZipFile.Name)' in folder '$UnzippedFilesPath'"
}
#endregion
一些提示:
Param ()
子句,以包含所有可以更改的变量。Get-ChildItem -Path xxx
代替Get-ChildItem xxx
。hash tables
用于长参数。这使代码的宽度更紧凑,更易于阅读。#region
和#endregion
对代码进行分组。