Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Powershell脚本压缩文件夹_Powershell - Fatal编程技术网

使用Powershell脚本压缩文件夹

使用Powershell脚本压缩文件夹,powershell,Powershell,编写了以下代码以将文件移动到驱动器上的特定年-月文件夹。但是,我还想压缩操作结束时写入的文件夹。我该怎么做 # Get the files which should be moved, without folders $files = Get-ChildItem 'D:\NTPolling\InBound\Archive' -Recurse | where {!$_.PsIsContainer} # List Files which will be moved # $files # Targ

编写了以下代码以将文件移动到驱动器上的特定年-月文件夹。但是,我还想压缩操作结束时写入的文件夹。我该怎么做

# Get the files which should be moved, without folders
$files = Get-ChildItem 'D:\NTPolling\InBound\Archive' -Recurse | where {!$_.PsIsContainer}

# List Files which will be moved
# $files

# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'D:\SalesXMLBackup'

foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()

# Out FileName, year and month
$file.Name
$year
$month

# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}

# Move File to new location
$file | Move-Item -Destination $Directory
}

其目的是将这些文件移动到一个文件夹中,并对其进行压缩和归档,以供以后使用。因此,我将计划每月运行一次,以便在上个月运行这是我用于解压缩目录中所有文件的代码。您只需要对其进行足够的修改,以压缩而不是解压缩

$ZipReNameExtract = Start-Job {
#Ingoring the directories that a search is not require to check
$ignore = @("Tests\","Old_Tests\")

#Don't include "\" at the end of $loc - it will stop the script from matching first-level subfolders
 $Files=gci $NewSource -Fecurse | Where {$_.Extension -Match "zip" -And $_.FullName -Notlike $Ignore} 
    Foreach ($File in $Files) {
        $NewSource = $File.FullName
        #Join-Path is a standard Powershell cmdLet
        $Destination = Join-Path (Split-Path -parent $File.FullName) $File.BaseName
        Write-Host -Fore Green $Destination
        #Start-Process needs the path to the exe and then the arguments passed seperately. 
        Start-Process -FilePath "C:\Program Files\7-Zip\7z.exe" -ArgumentList "x -y -o $NewSource $Destination" -Wait
    }
}
Wait-Job $ZipReNameExtract
Receive-Job $ZipReNameExtract
如果有帮助,请告诉我


UnderDog…

如果您使用的是PowerShell v5,则可以使用压缩存档功能:

Get-ChildItem $targetPath | Compress-Archive -DestinationPath "$targetPath.zip"

这将把
D:\SalesXMLBackup
压缩为
D:\SalesXMLBackup.zip

谢谢你!