如何使PowerShell脚本横向zip文件和基于select-string -pattern的报告

时间:2014-07-10 05:25:59

标签: powershell

我有以下工作,但我还需要能够读取压缩文件(zip)的内容

function Search-Files {
param ([string[]]$Servers, [string]$SearchPath, [string]$SearchItem, [string[]]$LogName)

ForEach ($Server in $Servers) {
    if ($LogName -eq $null) {
        dir -Path \\$server\$SearchPath -Recurse -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Select-String -pattern $SearchItem -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Select-Object Filename, Path, Matches, LineNumber
    }
    Else {
        dir -Path \\$server\$SearchPath -Recurse -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | ? {$_.Name -match $LogName} | Select-String -pattern $SearchItem -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Select-Object Filename, Path, Matches, LineNumber
    }
  }
}

目前我正在显示以下输出,这也是我想要为zip文件做的事情

ip.ininlog \ CO200197L \ C $ \ Temp \ Test \ Test \ ip \ ip.ininlog {3030872954} 136594

我发现以下内容并不确定如何继续实施

Grep File in Zip

List File in Zip

我需要能够横向存储在目录中的所有zip文件

目录结构样本

 2014-07-01 - root
     zip.zip
     zip_1.zip
     zip_2.zip
     etc

2 个答案:

答案 0 :(得分:1)

如果您安装了.NET 4.5框架,则可以使用4.5的内置ZIP支持将文件解压缩到临时路径并在临时文件上运行选择。如果没有4.5可用,我建议使用SharpCompress(https://sharpcompress.codeplex.com/),它的工作方式类似。

以下代码段演示了如何将ZIP存档提取到临时文件中,从脚本运行选择过程以及在提取后清理。如果只包含您要搜索的文件,则可以通过一次性提取整个ZIP文件(只需在存档上使用ExtractToDirectory())来显着简化代码。

# import .NET 4.5 compression utilities
Add-Type -As System.IO.Compression.FileSystem;

# the input archive
$archivePath = "C:\sample.zip";

# open archive for reading
$archive = [System.IO.Compression.ZipFile]::OpenRead($archivePath);
try
{
    # enumerate all entries in the archive, which includes both files and directories
    foreach($archiveEntry in $archive.Entries)
    {
        # if the entry is not a directory (which ends with /)
        if($archiveEntry.FullName -notmatch '/$')
        {
            # get temporary file -- note that this will also create the file
            $tempFile = [System.IO.Path]::GetTempFileName();
            try
            {
                # extract to file system
                [System.IO.Compression.ZipFileExtensions]::ExtractToFile($archiveEntry, $tempFile, $true);

                # create PowerShell backslash-friendly path from ZIP path with forward slashes
                $windowsStyleArchiveEntryName = $archiveEntry.FullName.Replace('/', '\');
                # run selection
                Get-ChildItem $tempFile | Select-String -pattern "yourpattern" | Select-Object @{Name="Filename";Expression={$windowsStyleArchiveEntryName}}, @{Name="Path";Expression={Join-Path $archivePath (Split-Path $windowsStyleArchiveEntryName -Parent)}}, Matches, LineNumber
            }
            finally
            {
                Remove-Item $tempFile;
            }
        }
    }
}
finally
{
    # release archive object to prevent leaking resources
    $archive.Dispose();
}

如果目录中有多个ZIP文件,可以按如下方式枚举它们(使用示例脚本):

$zipArchives = Get-ChildItem -Path \\$server\$SearchPath -Recurse "*.zip";
foreach($zipArchive in $zipArchives)
{
   $archivePath = $zipArchive.FullName;
   ...
}

您可以将演示代码放在...中,或将其移至PowerShell函数。

答案 1 :(得分:0)

有时不希望将zip条目提取为文件。相反,最好在内存中使用该文件。提取包含XML或JSON文本的Zip条目以便可以在内存中进行解析就是一个例子。

这是一种允许您执行此操作的技术。此示例假定存在一个名称以.json结尾的Zip条目,并且该文件将被检索。显然,可以修改该想法以处理不同的情况。

此代码应与包含System.IO.Compression命名空间的.NET Framework版本一起使用。

<main>
            <div class="main-center">
                    <div class="offerte-container">
                            <form action="" method="get" value="offertelijst">
                            <ul class="offerte-list">
                                    <?php
                                      $per_page = 9;
                                        $args = array(
                                        'post_type'=> 'wpcproduct',
                                        'order'     => 'ASC',
                                        'orderby'   => 'menu_order',
                                        'posts_per_page'    => $per_page
                                        );
                                     $products  =   new WP_Query($args); 
                                      ?>
                                    <?php
                                    while($products->have_posts()): $products->the_post();      
                                                $id = get_the_ID();
                        $title      =   get_the_title(); 
                        $permalink  =   get_permalink(); 
                        $price      =   get_post_meta(get_the_id(),'wpc_product_price',true); 
                                                $product_id = get_post_meta(get_the_id(), 'product_ID', true);
                                                if(in_array($id, $_SESSION['cart'])){           
                                         echo '<li class="wpc-product-item">';
                                          echo '<a href="index.php?action=delete&id=' .$id. '">Verwijder </a>';
                                            echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
                                         echo '<a href="'. $permalink .'"><div class="item-title"> ' .$title. ' </div></a>';
                                         echo '<a href="'. $permalink .'"><div class="item-take"> <img width="25px" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/pijltje.png" /> </div></a>';
                                         echo '<a href="'. $permalink .'"><div class="item-nr"> &nbsp; '.$product_id. '</div></a>';
                                         if((isset($_GET["amount$id"]) && $_GET["amount$id"] == 1) || $_GET["amount$id"] == "" ){
                                                            if (is_numeric($price) && (floor($price) == $price)) {
                                                                echo '<div class="item-price"> &#8364;' .number_format ($price , 0 , "," , "." ). ',- </div>';
                                                            } 
                                                            else {                                                      
                                                                echo '<div class="item-price"> &#8364;' .$price. '</div>';
                                                            }
                                                            echo '</li>';
                                                }
                                        else if(isset($_GET["amount$id"]) && floatval($_GET["amount$id"]) > 1){
                                            changeFormat($price);
                                            $priceTotal =  number_format($price * floatval($_GET["amount$id"]), 2);
                                                if (is_numeric($priceTotal) && (floor($priceTotal) == $priceTotal)) {
                                                                echo '<div class="item-price"> &#8364;' .$priceTotal . ',- </div>';
                                                            }
                                                            else {
                                                                echo '<div class="item-price"> &#8364;' .$priceTotal . '</div>';
                                                            }
                                                            echo '</li>';
                                                }}      
                                     endwhile;
                                    ?>
                            </ul>
                                    <input type="submit" value="Bereken"> </input>
                            </form>
                            <div class="totalprice">
                                    <?php 
                                    (float)$total = 0;
                                    while($products->have_posts()): $products->the_post(); {                          
                                                $id = get_the_ID();
                        $title      =   get_the_title(); 
                        $permalink  =   get_permalink(); 
                        $price      =   get_post_meta(get_the_id(),'wpc_product_price',true); 
                                                $product_id = get_post_meta(get_the_id(), 'product_ID', true);
                                                if(in_array($id, $_SESSION['cart'])){           
                                            if (is_numeric($price) && (floor($price) == $price)) {
                                                $price = number_format($price, 2);
                                            }
                                            else {
                                                $price = str_replace(',', '.', $price);
                                            }                                       
                                            $total += (floatval($price) * floatval($_GET["amount$id"]));                    
                                    }}      
                                            endwhile;                       
                                            (String)$total;
                                            number_format($total, 2);
                                            $totalDecimal = str_replace('.', ',', $total);
                                            echo 'Subtotaal: &nbsp;&#8364;' .$totalDecimal. '<br />';
                                            echo 'BTW: &nbsp;&#8364;' . str_replace('.',',', number_format($total * 0.21,2)). '<br />';
                                            echo 'Totaal: &nbsp;&#8364;' . str_replace('.',',', number_format($total * 1.21,2));


                                            function changeFormat($var) {
                                                if(is_numeric($var) && (floor($var) == $var)){
                                                    return number_format($var, 0) + ',-';
                                                }
                                                else {
                                                    if (is_numeric($var)) {
                                                        return number_format($var, 2, ',', '.');
                                                    }
                                                    else if (is_string ($var)){
                                                    return str_replace(',', '.', $var);
                                                }
                                                    else {
                                                        echo "What the hell is dit voor een formaat?";
                                                    }
                                            }}
                                    ?>

                            </div>
                    </div>

            </div>
    </main>