Blog

Tagged by 'powershell'

  • At times there is need to get a list of files that have been updated. This could for the following reasons:

    • Audit compliance to maintain records of application changes.
    • Backup verification to confirm the right files were backed up.
    • Verification of changed files to confirm which files were added, modified, or deleted during an update.
    • Security checks to ensure that there have been no unauthorised or suspicious files changed or installed through hacking.
    • Troubleshooting Issues after a new application release by seeing a list of changed files can help identify the source of issues.

    Based on the information I found online, I put together a PowerShell script that was flexible enough to meet the needs of the above scenarios, as I encountered one of them this week. I'll let you guess the scenario I faced.

    At its core, the following PowerShell script uses the Get-ChildItem command to list out all files recursively across all sub-folders, ordered by the created date descending with the addition of handful of optional parameters.

    Get-ChildItem -Path C:\My-Path -Recurse -Include *.png | 
    			Select -Last 5 CreationTime,LastWriteTime,FullName | 
    			Sort-Object -Property CreationTime -Descending | 
    			Export-Csv "file-list.csv"
    

    Breakdown of the parameters used:

    Parameter/Object Detail Is Optional
    -Path The folder path to where files need to be listed. No
    -Recurse Get files from the path and its subdirectories Yes
    -Include Filter the file output through a path element or pattern,. This only works when the "Recurse" parameter is present. Yes
    Select Set the maximum output (-Last) and list of fields to be listed. Yes
    Sort-Object Specify field and sort order. Yes
    Export-Csv Export the list of files list to a CSV. Yes

    If the files need to be sorted by last modified date, the Sort-Object property needs to be set to "LastWriteTime".

    When the script is run, you'll see the results rendered in the following way:

    CreationTime        LastWriteTime       FullName
    ------------        -------------       --------
    25/05/2023 20:33:44 25/05/2023 20:33:44 X:\Downloads\synology\Screenshot 2023-05-25 at 20.33.38.png
    16/05/2023 14:18:21 16/05/2023 14:18:21 X:\Downloads\synology\Screenshot 2023-05-16 at 14.18.15.png
    

    Further Information

  • If you have many sites running on your installation of Windows Server, you will soon find that there will be an accumulation of logs generated by IIS. Through my niavity, I presumed that there is a default setting in IIS that would only retain logs for a specific period of time. It is only when I started noticing over the last few weeks the hard disk space was slowly getting smaller and smaller.

    Due to my sheer embaressment, I won't divulge how much space the logs had taken up. All I can say, it was quite a substantial amount. :-)

    After some Googling online, I came across a Powershell script (which can be found here), that solved all my problems. The script targets your IIS logs folder and recusively looks for any file that contains ".log" for deletion. Unfortunately, the script did not run without making some minor modifications to the original source. This is due to changes in versions of Powershell since the post was written 3 years ago.

    $logPath = "C:\inetpub\logs\LogFiles" 
    $maxDaystoKeep = -5
    $cleanupRecordPath = "C:\Log_Cleanup.log" 
    
    $itemsToDelete = dir $logPath -Recurse -File *.log | Where LastWriteTime -lt ((get-date).AddDays($maxDaystoKeep)) 
    
    If ($itemsToDelete.Count -gt 0)
    { 
        ForEach ($item in $itemsToDelete)
        { 
            "$($item.FullName) is older than $((get-date).AddDays($maxDaystoKeep)) and will be deleted." | Add-Content $cleanupRecordPath 
            Remove-Item $item.FullName -Verbose 
        } 
    } 
    Else
    { 
        "No items to be deleted today $($(Get-Date).DateTime)." | Add-Content $cleanupRecordPath 
    }    
    
    Write-Output "Cleanup of log files older than $((get-date).AddDays($maxDaystoKeep)) completed!" 
    
    Start-Sleep -Seconds 10
    

    If you're ever so inclined, hook this script up to a Scheduled Task to run on a daily basis to keep your log files in order.

  • Published on
    -
    1 min read

    HTTP Request Script

    In one of my website builds, I needed to output around a couple thousand records from a database permanently into the .NET cache. Even though I set the cache to never expire, it will get cleared whenever the application pool recycles (currently set to every 24 hours). As you can expect, if a user happens to visit the site soon after the cache is cleared, excess page loading times will be experienced.

    The only way I could avoid this from happening is by setting up a Scheduled Task that would run a script that would carry out a web request straight after the application pool was set to recycle.

    Luckily, I managed to find a PowerShell script on StackOverflow that will do exactly that:

    $request = [System.Net.WebRequest]::Create("")
    $response = $request.GetResponse()
    $response.Close()
    
  • Microsoft’s new command-line tool, PowerShell has been out for quite a few years now and I thought today will be the day I would start using it. I needed to write a script that would move n number of files from one directory to another. This job seemed a perfect fit for PowerShell.

    #Get 'n' number of files
    $FileLimit = 10 
    
    #Destination for files
    $DropDirectory = "C:\Drop\"
    
    $PickupDirectory = Get-ChildItem -Path "C:\Pickup\"
    
    $Counter = 0
    foreach ($file in $PickupDirectory)
    {
        if ($Counter -ne $FileLimit)
        {
            $Destination = $DropDirectory+$file.Name
    
            Write-Host $file.FullName #Output file fullname to screen
            Write-Host $Destination   #Output Full Destination path to screen
            
            Move-Item $file.FullName -destination $Destination
            $Counter++
        }  
    }
    

    From the get go, I was really impressed with the flexibility of the scripting language. This is where command line fails. It is sufficient for simple tasks but not so much for complex jobs.

    As you can see from the code above, I can implement complex operations that supports variables, conditional statements, loops (while, do, for, and foreach), and that’s just the start. I don’t know why I hadn’t used PowerShell sooner. If I didn’t have the option to use PowerShell, I would have probably created a C# service or executable to do the exact same thing. Time saver!

    Since PowerShell is built on the .NET Framework, Windows PowerShell helps control and automate the administration of the operating system and applications that run on Windows. So if you are a C# programmer, you should feel comfortable in writing PowerShell scripts. All you need to be aware of is syntax differences when declaring variables and keywords.

    To end with, I will quote an amusing forum post I found when researching the difference between good ol’ Command Prompt and PowerShell:

    PowerShell has a default blue background and Command Prompt has a default black background.”