Powershell 如何从我的输出创建几个zip文件夹(函数)?

Powershell 如何从我的输出创建几个zip文件夹(函数)?,powershell,powershell-2.0,7zip,Powershell,Powershell 2.0,7zip,我正在尝试压缩在名为services的文件夹中找到的所有文件夹 #declare variables $folder = "C:\com\services" $destPath = "C:\destinationfolder\" #Define the function function create-7zip{ param([String] $folder, [String] $destinationFilePath) write-

我正在尝试压缩在名为
services
的文件夹中找到的所有文件夹

 #declare variables
    $folder = "C:\com\services"
    $destPath = "C:\destinationfolder\"

    #Define the function
    function create-7zip{
    param([String] $folder, 
    [String] $destinationFilePath)
    write-host $folder $destinationFilePath
    [string]$pathToZipExe = "C:\Program Files\7-Zip\7z.exe";
    [Array]$arguments = "a", "-tzip", "$destinationFilePath", "$folder";
    & $pathToZipExe $arguments;
    }

     Get-ChildItem $folder | ? { $_.PSIsContainer} | % {
     write-host $_.BaseName $_.Name;
     $dest= [System.String]::Concat($destPath,$_.Name,".zip");
     (create-7zip $_.FullName $dest)
     } 
我使用
Get Childitem
查找这些文件夹,我想在管道之后添加函数,但它没有按照我想要的方式工作。 zip文件应该与文件夹本身具有相同的名称,因此我尝试使用“$.FullName”来命名,而destinationpath是文件夹“C:\com\$.name”

这是我的剧本:

Get-ChildItem "C:\com\services" | % $_.FullName 


$folder = "C:\com\services"
$destinationFilePath = "C:\com"

function create-7zip([String] $folder, [String] $destinationFilePath)
{
    [string]$pathToZipExe = "C:\Program Files (x86)\7-Zip\7zG.exe";
    [Array]$arguments = "a", "-tzip", "$destinationFilePath", "$folder";
    & $pathToZipExe $arguments;
}

首先。声明变量,如文件夹和目标路径

第二。将7zip文件夹路径更改为我的文件夹路径(
程序文件


$\u.PSIsContainer
将只找到文件夹,构造目标路径变量
$dest
,然后调用函数。我希望这有帮助。

如果我理解正确,您希望通过管道将gci的输出输入到Create-7Zip函数中,并让该函数创建一个以您传入的每个目录命名的zip文件,如下所示:

gci | ?{ $_.PSIsContainer } | Create-7Zip
为此,您需要编写支持从管道中获取值的cmdlet,这可以通过params()列表中的[Parameter]属性来实现


您将看到7zip的输出;您可以通过管道将此信息传输到其他地方来捕获。

谢谢,我对powershell还是很陌生。所以对我来说,它没有按照我想要的方式工作。你为什么要用你的方式去执行可执行文件?为什么不简单地给出完整的路径?感谢完整路径会很好,如果可能的话,我只是尝试用环境变量等价物替换任何windows路径。对于程序文件,该实用程序不太明显,但对于使用$env:Temp的临时目录(通常是c:\Users\\AppData\Local\Temp)这样的东西,多个用户更安全,更容易键入。当然,但特别是7zip在某些版本上有两个不同的可执行文件,分别是7z.exe和7zG.exe。我相信7zG在提供相同功能的同时,在命令行上为您提供了某种GUI,但我还没有验证。嘿,mitul,非常有用,唯一的一点是,zip文件存储在我的脚本所在的文件夹中。但我可能会想:)
function Create-7Zip
{
  param(
    [Parameter(ValueFromPipeline=$True)]
    [IO.DirectoryInfo]$Directory #we're accepting directories from the pipeline.  Based on the directory we'll get the zip name
    );
    BEGIN
    {
        $7Zip = Join-Path $env:ProgramFiles "7-Zip\7z.exe"; #get executable
    }
    PROCESS
    {
        $zipName = $("{0}.zip" -f $Directory.Name);
        $7zArgs = Write-Output "a" "-tzip" $zipName $directory.FullName; #Q&D way to get an array
        &$7Zip $7zArgs
    }
}



Usage:
    #Powershell 3.0
    get-childitem -directory | Create-7Zip
    #Powershell 2
    get-childitem | ?{ $_.PSIsContainer } | Create-7Zip