我正在尝试将一个飞蛾的文件夹压缩到单个文件中。例如,201501适用于jan的所有文件夹,我需要压缩到名为somename-2015-jan.zip的文件。所有其他逻辑只工作zipplig部分显示上述错误。我有powershell v3和net 4.54,当我可以调用System.IO.Compression.ZipFile] :: CreateFromDirectory来压缩文件时出错了。
$year = 2015
$base = "D:\Archive\"
$folder = Get-Content "D:\Archive\MasterFolder.txt"
#write-host $folder.count total lines read from file
foreach ($Fname in $folder)
{
$yearmonth = Get-Content "D:\Archive\duration.txt"
write-host $yearmonth.count total lines read from file
foreach ($date in $yearmonth)
{
$source = "$base$Fname\$date*"
#[string]$text = "$date"
$string = $date
#201501
$mmd = $string.Substring(4,2)
Write-host "fffcmd $mmd"
if ($mmd -gt 12) {
"$mmd is bigger than 12 Which is not valid,Please Correct The file name durations.txt and run the command again"
break
}
Else {
write-host " This is Source Folder Name !!!!!!!!!!!!!!!!!!!!$source"
switch($mmd)
{
"01" {$mm = "jan"
write-host "New mm is $mm"
}
"02" {$mm = "Feb"
write-host "New mm is $mm"
}
"03" {$mm = "Mar"
write-host "New mm is $mm"
}
"04" {$mm = "Apr"
write-host "New mm is $mm"
}
"05" {$mm = "May"
write-host "New mm is $mm"
}
"06" {$mm = "Jun"
write-host "New mm is $mm"
}
"07" {$mm = "Jul"
write-host "New mm is $mm"
}
"08" {$mm = "Aug"
write-host "New mm is $mm"
}
"09" {$mm = "Sep"
write-host "New mm is $mm"
}
"10" {$mm = "Oct"
write-host "New mm is $mm"
}
"11" {$mm = "Now"
write-host "New mm is $mm"
}
"12" {$mm = "Dec"
write-host "New mm is $mm"
}
default
{
Write-host "The Month Duration $mmd is not valid";continue
}
}
$destination = "$base$Fname\$Fname-$year-$mm.zip"
write-host " Destination $destination"
Add-Type -assembly "system.io.compression.filesystem"
function ZipFiles( $zipfilename, $sourcedir )
{
[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
$zipfilename, $compressionLevel, $false)
}
ZipFiles "$destination", "$source"
}
start-sleep -s 1
}
}
答案 0 :(得分:0)
CreateFromDirectory
不允许使用通配符。请改用Get-ChildItem
。
行后
$source = "$base$Fname\$date*"
将匹配的文件传递给foreach
循环:
$files = (Get-ChildItem "$base$Fname\$date*")
foreach ($file in $files) {
# ...
# Continue with the rest of your code, starting at the line "$string = $date"
# ...
ZipFiles $destination, $file.FullName
}
其他一些建议:
ZipFiles
函数定义移到foreach
循环之外 - 每次循环运行时都不需要重新定义。System.IO.Compression.FileSystem
移到foreach
es之外。switch
语句,并将其替换为:$mm = [CultureInfo]::CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName($mmd)