powershell - 如何使用 PowerShell 将多个文件压缩为一个 zip 文件?

标签 powershell zip pipe

我想将多个文件压缩成一个 zip。

我现在坚持这个:

Get-ChildItem -path C:\logs -Recurse | Where {$_.Extension -eq ".csv" -and $_.LastWriteTime -lt (Get-Date).AddDays(-7)} | write-zip -level 9 -append ($_.LastWriteTime).zip | move-item -Force -Destination {
    $dir = "C:\backup\archive"
    $null = mkdir $dir -Force
    "$dir\"
}

我得到这个异常(exception)

Write-Zip : Cannot bind argument to parameter 'Path' because it is null.



这部分是问题:
write-zip -level 9 -append ($_.LastWriteTime).zip

我以前从未使用过powershell,但我必须提供一个脚本,我无法提供c#解决方案。

最佳答案

问题是Get-ChildItem返回 System.IO.FileInfo 的实例类,它没有名为 Path 的属性.因此该值不能自动映射到 Path Write-Zip 的参数cmdlet 通过管道。

您必须使用 ForEach-Object cmdlet 使用 System.IO.FileInfo.FullName 压缩文件属性,其中包含完整路径:

Get-ChildItem -Path C:\Logs | Where-Object { $_.Extension -eq ".txt" } | ForEach-Object { Write-Zip -Path $_.FullName -OutputPath "$_.zip" }

这是使用 aliases 的命令的较短版本和位置参数:
dir C:\Logs | where { $_.Extension -eq ".txt" } | foreach { Write-Zip $_.FullName "$_.zip" }

相关资源:
  • Cool Pipeline Tricks, Redux (TechNet Magazine)
  • 关于powershell - 如何使用 PowerShell 将多个文件压缩为一个 zip 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5634961/

    相关文章:

    node.js - NodeJs : slow req. 管道

    powershell - 在部署期间使用脚本从 SCCM 检索应用程序属性

    bash - 为什么 2>&1 需要在 | 之前出现? (管道)但在 "> myfile"(重定向到文件)之后?

    search - PowerShell,在特定目录中搜​​索特定文件名

    使用applescript zip 文件夹

    swift - 如何提取 zip 文件并在 Swift 的共享扩展中获取提取的组件

    php_zip 在 php 5.3.5 中不存在

    c - 如何在 C 中将一个字符中的两个数字相加?

    powershell - 如何从 powershell 设置 csproj 文件使用的启动操作(外部程序)

    IIS使用脚本切换路径