PowerShell |需要一些性能改进

时间:2017-07-22 15:02:15

标签: performance powershell 7zip

我已经编写了一个PowerShell脚本,用于存档旧的日志文件,或者说一些Web应用程序的输出文件是TBs,但脚本需要很长时间。我做了一些改进,但无法从这里加速。

代码:

#region Archive Files using 7zip

[cmdletbinding()]
Param
(
[Parameter(Mandatory=$true, HelpMessage = "Path needs to be with trailing slash at the end of location." )]
[string]$SourceFilesPath
)

$7zip = "C:\Program Files\7-Zip\7z.exe"
$FilePath = ""

foreach ( $filename in $(Get-ChildItem $SourceFilesPath -Force -Recurse | where {$_.LastWriteTime -lt (get-date).AddDays(-1).ToShortDateString()}))
{
    $FilePath = Get-ItemProperty $filename.FullName
    $ZipFilePath = $filename.Directory.ToString() + "\ZippedFiles" + "\Archive_" + $filename.LastWriteTime.ToString("MMddyyyy") + ".7z"

    $tempPath = ("-w"+"C:\Temp")
    $OutputData = &$7zip a $tempPath -t7z $ZipFilePath $FilePath
    $OutputData
    if ($OutputData -contains "Everything is OK")
    {
        Remove-Item $FilePath -Force
        Write-Output "File removed $FilePath"
    }
    Get-Item $ZipFilePath | ForEach-Object {$_.LastWriteTime = $filename.LastWriteTime}
}

#endregion

1 个答案:

答案 0 :(得分:0)

#region Archive Files using 7zip

[cmdletbinding()]
Param
(
    [Parameter(Mandatory = $true, HelpMessage = 'Path needs to be with trailing slash at the end of location.' )]
    [string]$SourceFilesPath
)
Import-Module ..\Invoke-Parallel.ps1 # Download from PSGallery

$7zip = 'C:\Program Files\7-Zip\7z.exe'

$fileToArchive = $(Get-ChildItem $SourceFilesPath -Force -Recurse | Where-Object -FilterScript {
        $_.LastWriteTime -lt (Get-Date).AddDays(-1).ToShortDateString()
})
$counter = 0
$groupSize = 2000 # Will group items by 2,000 increments
$groups = $fileToArchive | Group-Object -Property {
    [math]::Floor($counter++ / $groupSize) 
}
$groups

# This will spawn multiple instances of 7zip - depending on how many groups of 2,000 files exist
$groups.Group | Invoke-Parallel -ScriptBlock {
    $FilePath = $null
    $fileName = $_
    $FilePath = Get-ItemProperty -Path $fileName.FullName
    $ZipFilePath = $fileName.Directory.ToString() + '\ZippedFiles' + '\Archive_' + $fileName.LastWriteTime.ToString('MMddyyyy') + '.7z'

    $tempPath = ('-w'+'C:\Temp')
    $OutputData = &$Using:7zip a $tempPath -t7z $ZipFilePath $FilePath
    $OutputData
    if ($OutputData -contains 'Everything is OK')
    {
        Remove-Item $FilePath -Force
        Write-Output -InputObject "File removed $FilePath"
    }
    Get-Item $ZipFilePath | ForEach-Object -Process {
        $_.LastWriteTime = $fileName.LastWriteTime
    }
}