Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Reply To: are begin block variables not global?

$
0
0

I don't see any problem with the scope of the $tempFolder variable. It should be usable right to the end of the function.

It is a little bit odd that you have $LogFileDays listed as able to be passed via the pipeline, but you're using it in your Begin block. The function is also written in such a way that you could only ever really process one input record on the pipeline, so you should probably make that explicit and throw an error if two or more objects are encountered. These aren't really related to the problem you had with $tempFolder, but it's all that really jumped out at me.

Here's a way that you could revise your code and not need to rely on $tempFolder in that particular step. Since you're already moving files in a loop anyway, I just added -Passthru to the Move-Item command, assigned the results to a variable and checked its count:

function Zip-IISLogs
{
    [CmdletBinding()]    
    Param
    (
        # LogFileDays number of days old to archive and then delete
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [UInt32] $LogFileDays = 0,
 
        # ZipFileDays number of days old to delete and remove the old ZIP files that are no longer needed
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [UInt32]
        $ZipFileDays = 0
    )
 
    Begin
    {
        # Setup some global variables
        $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
        $includeBaseDirectory = $false # if true creates a folder within a folder
        $defaultLogPath = Get-WebConfiguration -Filter system.applicationhost/sites/sitedefaults/logfile | Select-Object -ExpandProperty directory
 
        # TEMP foldername and filename variable
        $tempName = "IISLogs"+(Get-Date).ToShortDateString().Replace("/","-")
        $Destination = $defaultLogPath.Replace("%SystemDrive%",$env:SystemDrive)+"\"+$tempName+".zip"
        [System.IO.FileInfo]$tempFolder = $env:TEMP+"\"+$tempName
        New-Item -Path $tempFolder -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null
 
        function Get-IISLogFilePath
        {
            # Load the PowerShell Module for IIS
            Import-Module WebAdministration
 
            $Sites = Get-ItemProperty 'IIS:\Sites\*'
            foreach ($Site in $Sites)
            {
                $SiteID = $Site.ID
                $LogPath = $Site.logFile.directory
                $Logpath = $LogPath.Replace("%SystemDrive%",$env:SystemDrive)
                "$LogPath"+'\W3SVC'+"$SiteID"
            }
        }
 
        $alreadyExecutedProcessBlock = $false
    }
    Process
    {
        if ($alreadyExecutedProcessBlock)
        {
            throw 'Only one object may be piped to Zip-IISLogs.'
        }
        else
        {
            $alreadyExecutedProcessBlock = $true
        }
 
        $oldestLogDate = (Get-Date).AddDays(-$LogFileDays)
        $iisLogFolders = Get-IISLogFilePath
 
        $movedLogs = @(
            foreach ($folder in $iisLogFolders)
            {
                Get-ChildItem $folder -Recurse -Include *.log |
                Where-Object { $_.LastWriteTime -le $oldestLogDate } |
                Move-Item -Destination $tempFolder -Force -PassThru
            }
        )
 
        if ($movedLogs.Count -gt 0)
        {
            # Now create the zip file
            # Load the built in ZIP Assembly from Windows
            [Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )# Load the built in ZIP Assembly from Windows
            [System.IO.Compression.ZipFile]::CreateFromDirectory($tempFolder,$Destination,$compressionLevel,$includeBaseDirectory)
        }
 
        Remove-Item $tempFolder -Recurse -Force -ErrorAction SilentlyContinue
 
        # Remove old ZIPs
        if ($ZipFileDays)
        {   
            Get-ChildItem -Path ([Environment]::ExpandEnvironmentVariables($defaultLogPath)) -Include *.zip -Recurse |
            Where-Object {$_.LastWriteTime -le (Get-Date).AddDays(-$ZipFileDays)} |
            ForEach-Object {Remove-Item $_.FullName -Force}
        }
    }
    End
    {
        Clear-Host
        (Get-ChildItem $Destination).FullName
    }
}
 
# Remember to set your defaults below replace the variables with your numbers if you plan to run from a scheduled task then REMOVE the "#" from the last line
# HINT: ZipFileDays 0 will NOT delete old ZIP files 
Zip-IISLogs -LogFileDays 30 -ZipFileDays 120

Viewing all articles
Browse latest Browse all 13067

Trending Articles