[英]Compress Files from list with PowerShell 5
我有一个文件,其中包含带有说明的文件列表。
像这样:
XXXXXX/sample.txt
XXXXXX/dog.txt
XXXXXX/cat.docx
ZZZZ/lamp.jpg
如何压缩所有文件并使用子方向保存文件。
现在,我可以压缩所有文件但没有指示。
像这样:
sample.txt
dog.txt
cat.docx
lamp.jpg
抱歉我的英语不好。
foreach ($filename in Get-Content .\ListOfFilesToZip.txt)
{
Compress-Archive -Update $filename .\ZipFile.zip
}
编辑如果问题是关于从路径中获取文件名
最有效的方法是使用正则表达式,但如果您不习惯使用它们,它们可能会相当复杂。
一种更简单的方法是简单地拆分每个字符串并选择文件名所在的最后一部分:
$string = "c:\asd\qwe\zxc\dog.txt"
#Split the string on each \
$string.Split("\")
#This will output a list like this
c:
asd
qwe
zxc
dog.txt
现在我们只想选择此列表中的最后一个条目,因为文件名总是在路径中的最后一个。 所以我们为此使用选择对象。
$string.Split("\") | Select-Object -Last 1
这将返回:
dog.txt
您可以通过列表上的 foreach 运行它以获取每个项目的它。
不确定是否有更好的方法来执行此操作,但是您可以创建一个临时文件夹,将要存档的文件与所需的文件夹结构一起复制到那里,然后将整个文件压缩。
看看这里(不是我的代码,但似乎正是这样做的)的示例
以下函数可以将整个文件夹结构压缩到一个 zip 文件中,并将结构保留在 zip 中(甚至适用于 PowerShell <5)。
function createZipFile($outputFileName, $sourceDirectory){
Add-Type -AssemblyName System.IO.Compression.FileSystem
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDirectory, $outputFileName, $compressionLevel, $false)
}
这样称呼它:
createZipFile "c:\temp\output.zip" "c:\folder\to\compress"
function DirNewTemp {
$tmpdir = (New-TemporaryFile).FullName
Remove-Item -Force -Path $tmpdir -ErrorAction 'SilentlyContinue'
New-Item -Type Directory $tmpdir | out-null
return $tmpdir
}
function ZipFiles {
param(
[string]$Zip,
[string[]]$FileList
)
write-host ""
write-host "====================================="
write-host "ZipFile $Zip"
write-host "====================================="
$pwd = (Get-Location).Path
$tmpdir = DirNewTemp
try {
$count = $FileList.Count
foreach ($file in $FileList) {
$pwd_escaped = [Regex]::Escape($pwd)
$save_file = $file -replace "^${pwd_escaped}\\", "${tmpdir}\"
$save_path = Split-Path $save_file -Parent
New-Item -Force -Path $save_path -ItemType Directory | out-null
Copy-Item -Force $file $save_file
}
set-location $tmpdir
$dest = "$pwd\$Zip";
write-host "Creating Zip: $dest"
Compress-Archive -Force -Path * -DestinationPath $dest
}
finally {
write-host "cleanup"
set-location $pwd
remove-item -Force -Recurse -Path $tmpdir -ErrorAction 'SilentlyContinue'
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.