2017-05-16 78 views
0

我想查找名称为'test'的所有文件夹,并将它们压缩到具有不同名称的单个文件夹中,当然。找到所有特定的文件夹并将它们压缩

我设法做一些代码:

$RootFolder = "E:\" 
$var = Get-ChildItem -Path $RootFolder -Recurse | 
     where {$_.PSIsContainer -and $_.Name -match 'test'} 

#this is assembly for zip functionality 
Add-Type -Assembly "System.IO.Compression.Filesystem" 

foreach ($dir in $var) { 
    $destination = "E:\zip\test" + $dir.Name + ".zip" 

    if (Test-Path $destination) {Remove-Item $destination} 

    [IO.Compression.Zipfile]::CreateFromDirectory($dir.PSPath, $destination) 
} 

它给了我一个错误:

Exception calling "CreateFromDirectory" with "2" argument(s): "The given path's format is not supported."

我想知道,究竟是通过我的$dir的路径的正确途径。

回答

1

PSPath财产Get-ChildItem返回是前缀为PSProviderCreateFromDirectory() method需要两个字符串;第一个是sourceDirectoryName,您可以从您的对象中使用Fullname

$RootFolder = "E:\" 
$Directories = Get-ChildItem -Path $RootFolder -Recurse | Where-Object { 
    $_.PSIsContainer -And 
    $_.BaseName -Match 'test' 
} 

Add-Type -AssemblyName "System.IO.Compression.FileSystem" 

foreach ($Directory in $Directories) { 
    $Destination = "E:\zip\test$($Directory.name).zip" 

    If (Test-path $Destination) { 
     Remove-Item $Destination 
    } 

    [IO.Compression.ZipFile]::CreateFromDirectory($Directory.Fullname, $Destination) 
} 
+0

谢谢! '全名'propery令我困惑,我没有怀疑这实际上是一条路! – Stefan0309

1

如果您使用V5,我会建议使用Commandlet

如果你不想使用您可以使用此命令行开关:

$FullName = "Path\FileName" 
$Name = CompressedFileName 
$ZipFile = "Path\ZipFileName" 
$Zip = [System.IO.Compression.ZipFile]::Open($ZipFile,'Update') 
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($Zip,$FullName,$Name,"optimal") 
$Zip.Dispose() 
+0

我喜欢Dispose方法,我会试一下! TNX。 – Stefan0309

0

如果你有一个文件夹结构是这样的:

- Folder1 
-- Test 
- Folder2 
-- Test 
- Folder3 
-- Test 

你可以这样做:

gci -Directory -Recurse -Filter 'test*' | % { 
    Compress-Archive "$($_.FullName)\**" "$($_.FullName -replace '\\|:', '.').zip" 
} 

,你会得到:

D..Dropbox.Projects .StackOverflow-Posh.ZipFolders.Folder1.Test.zip D..Dropbox.Projects.StackOverflow-Posh.ZipFolders.Folder2.T est.zip D..Dropbox.Projects.StackOverflow-Posh.ZipFolders.Folder3.Test.zip

或者,如果你想保留你的拉链里面的目录结构:

gci -Directory -Recurse -Filter 'test*' | % { 
     Compress-Archive $_.FullName "$($_.FullName -replace '\\|:', '.').zip" 
    } 
相关问题