Testing new text format

Sure! Below is a PowerShell script to create a hub virtual network and two spoke virtual networks in Azure:

“`powershell

# Variables

$resourceGroupName = โ€œYourResourceGroupNameโ€

$location = โ€œYourAzureRegionโ€

$hubVnetName = โ€œHubVnetโ€

$spokeVnet1Name = โ€œSpokeVnet1โ€

$spokeVnet2Name = โ€œSpokeVnet2โ€

$hubVnetAddressPrefix = “10.0.0.0/16โ€

$spokeVnet1AddressPrefix = “10.1.0.0/16โ€

$spokeVnet2AddressPrefix = “10.2.0.0/16โ€

# Create the hub virtual network

New-AzVirtualNetwork -ResourceGroupName $resourceGroupName -Name $hubVnetName -Location $location -AddressPrefix $hubVnetAddressPrefix

# Create the first spoke virtual network

New-AzVirtualNetwork -ResourceGroupName $resourceGroupName -Name $spokeVnet1Name -Location $location -AddressPrefix $spokeVnet1AddressPrefix

# Create the second spoke virtual network

New-AzVirtualNetwork -ResourceGroupName $resourceGroupName -Name $spokeVnet2Name -Location $location -AddressPrefix $spokeVnet2AddressPrefix

“`

Replace the placeholder values (`YourResourceGroupName` and `YourAzureRegion`) with your desired resource group name and Azure region. The script will create three virtual networks: one hub virtual network and two spoke virtual networks, each with their respective address prefixes.

Note: Make sure you have the Azure PowerShell module installed and authenticated to your Azure account before running the script.

# Script to clean temporary files with advanced filtering and comprehensive error reporting
param (
    [int]$MaxAgeDays = 30,                    # Maximum age of files to delete in days
    [int64]$MaxFileSizeBytes = 100MB,         # Maximum file size to delete (default 100MB)
    [int]$FailureThreshold = 10,              # Number of failures before sending alert
    [string]$EmailFrom = "[email protected]",
    [string]$EmailTo = "[email protected]",
    [string]$SmtpServer = "smtp.company.com"
)

$ErrorActionPreference = "Stop"
$LogFile = "C:\Logs\temp_cleanup_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
$TempPaths = @(
    "C:\Users\*\AppData\Local\Temp\*"
    "$env:windir\Temp\*"
)

# Create log directory if it doesn't exist
try {
    New-Item -ItemType Directory -Path (Split-Path $LogFile) -Force -ErrorAction Stop | Out-Null
} catch {
    Write-Error "Failed to create log directory: $_"
    exit 1
}

# Function to write to log file and console
function Write-Log {
    param(
        [string]$Message,
        [ValidateSet('Info', 'Warning', 'Error')]
        [string]$Severity = 'Info'
    )
    $TimeStamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $LogMessage = "$TimeStamp [$Severity] - $Message"
    Add-Content -Path $LogFile -Value $LogMessage
    
    switch ($Severity) {
        'Warning' { Write-Warning $LogMessage }
        'Error'   { Write-Error $LogMessage }
        default   { Write-Output $LogMessage }
    }
}

# Function to send email notification
function Send-AlertEmail {
    param(
        [string]$Subject,
        [string]$Body
    )
    try {
        $EmailParams = @{
            From = $EmailFrom
            To = $EmailTo
            Subject = $Subject
            Body = $Body
            SmtpServer = $SmtpServer
        }
        Send-MailMessage @EmailParams -BodyAsHtml
        Write-Log "Alert email sent successfully"
    } catch {
        Write-Log "Failed to send alert email: $($_.Exception.Message)" -Severity 'Error'
    }
}

Write-Log "Starting temporary file cleanup..."
Write-Log "Configuration: Max Age = $MaxAgeDays days, Max File Size = $([math]::Round($MaxFileSizeBytes/1MB, 2)) MB"

$TotalStats = @{
    TotalFiles = 0
    DeletedFiles = 0
    FailedFiles = 0
    SkippedFiles = 0
    TotalSize = 0
    FreedSpace = 0
}

$MaxAge = (Get-Date).AddDays(-$MaxAgeDays)
foreach ($Path in $TempPaths) {
    Write-Log "Processing path: $Path"
    try {
        # Get files with age and size filtering
        $Files = Get-ChildItem -Path $Path -Recurse -Force -ErrorAction Stop | 
            Where-Object { 
                -not $_.PSIsContainer -and 
                $_.LastWriteTime -lt $MaxAge -and 
                $_.Length -le $MaxFileSizeBytes
            }

        $TotalStats.TotalFiles += $Files.Count
        
        foreach ($File in $Files) {
            try {
                $TotalStats.TotalSize += $File.Length
                
                # Check if file is locked
                $Locked = $false
                try {
                    $Stream = $File.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
                    $Stream.Close()
                } catch {
                    $Locked = $true
                }

                if ($Locked) {
                    Write-Log "Skipping locked file: $($File.FullName)" -Severity 'Warning'
                    $TotalStats.SkippedFiles++
                    continue
                }

                Remove-Item -Path $File.FullName -Force -ErrorAction Stop
                $TotalStats.DeletedFiles++
                $TotalStats.FreedSpace += $File.Length
                Write-Log "Deleted: $($File.FullName) (Size: $([math]::Round($File.Length/1KB, 2)) KB)"
            } catch {
                $TotalStats.FailedFiles++
                Write-Log "Failed to delete: $($File.FullName) - Error Code: $($_.Exception.HResult) - $($_.Exception.Message)" -Severity 'Error'
            }
        }

    } catch {
        Write-Log "Error accessing path $Path : $($_.Exception.Message)" -Severity 'Error'
    }
}

# Generate summary report
$Summary = @"
<h2>Temporary File Cleanup Summary</h2>
<p>Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')</p>
<ul>
    <li>Total files processed: $($TotalStats.TotalFiles)</li>
    <li>Successfully deleted: $($TotalStats.DeletedFiles)</li>
    <li>Failed to delete: $($TotalStats.FailedFiles)</li>
    <li>Skipped (locked) files: $($TotalStats.SkippedFiles)</li>
    <li>Total size processed: $([math]::Round($TotalStats.TotalSize/1MB, 2)) MB</li>
    <li>Total space freed: $([math]::Round($TotalStats.FreedSpace/1MB, 2)) MB</li>
</ul>
"@

Write-Log "Cleanup operation completed."
Write-Log $Summary

# Send alert if failure threshold is exceeded
if ($TotalStats.FailedFiles -ge $FailureThreshold) {
    $AlertSubject = "WARNING: High failure rate in temporary file cleanup"
    Send-AlertEmail -Subject $AlertSubject -Body $Summary
}

# Export detailed results to CSV
$LogSummary = [PSCustomObject]@{
    Date = Get-Date
    TotalFiles = $TotalStats.TotalFiles
    DeletedFiles = $TotalStats.DeletedFiles
    FailedFiles = $TotalStats.FailedFiles
    SkippedFiles = $TotalStats.SkippedFiles
    TotalSizeMB = [math]::Round($TotalStats.TotalSize/1MB, 2)
    FreedSpaceMB = [math]::Round($TotalStats.FreedSpace/1MB, 2)
}

$LogSummary | Export-Csv -Path "C:\Logs\temp_cleanup_summary.csv" -Append -NoTypeInformation

# Display final status
Get-Content $LogFile | Select-Object -Last 10

Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *