Category: PowerShell

PowerShell & Windows Admin Blog Archives, by Peter Whyte (SQL Database Administrator). Includes a lot of WSL posts & more…

  • Delete Files Older Than in PowerShell

    Here is an example of how to use PowerShell to delete files older than a specified date:

    # Set the path to the folder containing the files you want to delete
    $folder = "C:\myfolder"
    
    # Set the maximum age of the files in days
    $maxAge = 30
    
    # Get the current date and subtract the maximum age to get the cutoff date
    $cutoffDate = (Get-Date).AddDays(-$maxAge)
    
    # Get all the files in the folder that are older than the cutoff date
    $files = Get-ChildItem $folder | Where-Object { $_.LastWriteTime -lt $cutoffDate }
    
    # Delete the files
    $files | Remove-Item
    

    This script will delete all files in the specified folder that have the last write time older than 30 days from the current date. You can adjust the $maxAge and $folder variables to customize the behaviour of the script.

    Note that this script does not move the deleted files to the recycle bin, so be careful when using it to avoid accidentally deleting important files. It’s always a good idea to test the script on a small, non-critical folder before running it on a larger folder or system.

  • Get-EventLog in PowerShell

    Get-EventLog in PowerShell

    The Get-EventLog cmdlet in PowerShell can help you view events as you would in Event Viewer, but within your PowerShell Terminal.

    In this post I’ll share a few examples of use:

    # Get List of Event Logs Available
    # Show Events by Count
    # Show Events by Message Name
    # Show Full Message of an Event


    Get List of Event Logs Available

    #Get List of Event Logs Available
    Get-EventLog -List

    Show Events by Count

    # Show Events by Count
    Get-EventLog -LogName Application | Group-Object -Property Source -NoElement | Sort-Object -Property Count -Descending

    Show Events by Message Name

    # Show Events by Message Name
    Get-EventLog -LogName Application -Newest 10 -Message *MSSQLSERVER*

    Show Full Message of an Event

    # Show Full Message of an Event
    Get-EventLog -LogName Application -Newest 1 -Message *MSSQLSERVER* | Select Message

  • Get-Command in PowerShell

    Get-Command in PowerShell

    Get-Command is a cmdlet in PowerShell that allows us to retrieve a list of commands that are available to use in the current session. This cmdlet is useful for discovering new commands and learning more about their usage & capabilities.

    We can query commands using wildcards as displayed in this example:

    # get-command, better use wildcards *
    Get-Command test-sql*
    PowerShell Get Command Wildcard

    We can list commands that belong to a specific PowerShell module, or that have a specific verb or noun in their name. For example, run Get-Command Test-* to retrieve all PowerShell cmdlets with the ‘Test’ prefix.

    If you found this tip useful, you may be interested in checking out my other PowerShell Tips. I regularly publish new content on my blog, including helpful tips and tricks for working with PowerShell.

  • Create Folder If Not Exists in PowerShell

    Create Folder If Not Exists in PowerShell

    The PowerShell script included in this blog post checks if a specific folder exists and then creates it if it does not already exist.

    It does this by using the Test-Path command to check for the existence of the folder and the New-Item command to create it if it doesn’t exist. The script can be modified to check for and create any desired folder by changing the specified path.

    The following is included in this PowerShell demo:
    Using Test-Path to Check if a Folder Exists
    Creating a Folder with New-Item
    Modifying the Script for Others

    Using Test-Path to Check if a Folder Exists

    The first step in this script is to use the Test-Path command to check if the desired folder already exists. The Test-Path command returns a boolean value indicating whether the specified path exists.

    To check if a folder exists using PowerShell, we can use the following syntax:

    # Check if folder exists
    $path = "c:\temp\"
    If(!(test-path $path))

    Here, we are storing the path of the folder we want to check in the $path variable. The ! operator negates the boolean value returned by Test-Path, so the If statement will only execute if the folder does not exist.

    Creating a Folder with New-Item

    To create a new folder, we can use the New-Item command with the -ItemType parameter set to Directory. The -Force parameter ensures that the command will overwrite any existing files with the same name and the -Path parameter specifies the location where the new folder will be created.

    # create a new folder 
    New-Item -ItemType Directory -Force -Path $path

    Modifying the Script for Others

    To use this script to check for and create a different folder, simply modify the $path variable to the desired location. For example, to check for and create the c:\myfolder\ folder, you would use the following script:

    # create folder if not exists
    $path = "c:\myfolder\"
    If(!(test-path $path))
    {
        New-Item -ItemType Directory -Force -Path $path
    }
    

    By modifying the $path variable, you can use this script to check for and create any folder you need.

    PowerShell Create Folder if Not Exist

  • Get-TimeZone in PowerShell

    Get-TimeZone in PowerShell

    The Get-TimeZone command in PowerShell returns the current Time Zone of a computer, or it can be used to list all available Time Zones which will be useful if you’re planning on making changes to timezones.

    In this post I’m showing 2 examples of how to check Timezone with PowerShell:

    # Get the Time Zone of a Local Computer in PowerShell
    # Script to Output Available Time Zones to a Local CSV File

    Get the Time Zone of a Local Computer in PowerShell

    Running Get-TimeZone in PowerShell will return the currently set timezone of the local Windows Computer.

    # get timezone powershell
    Get-TimeZone
    Get timezone PowerShell
    The above shows we are on GMT Standard Time, UTC+00:00.

    Script to Output Available Time Zones to a Local CSV File

    The PowerShell script below will output all available timezones to a local directory.

    # output available timezones to a local directory
    $path = "c:\temp\"
    $output_file_name = "timezones_available.csv"
    $full_output_path = $path + $output_file_name
    
    If(!(test-path $path))
    {
        New-Item -ItemType Directory -Force -Path $path
    }
    Get-TimeZone -ListAvailable | Export-Csv -Path $full_output_path -NoTypeInformation -Force
    

    I saved this script to my c:\temp and ran:

    The CSV will contain all timezones available, which is useful if amending timezones. The Set-TimeZone Microsoft Documentation page will help with this task.

    As ever, I hope this guide has been a useful one. Feel free to check out my PowerShell Tips page for more random PowerShell informational guides.

  • Get-Service in PowerShell

    Get-Service in PowerShell

    Get-Service is a command in PowerShell that returns a list of Services on a Computer.

    This post is a quick guide on running this command in a PowerShell terminal, using a wildcard ( * ) to show me my services with “SQL” in the service name.

    Get-Service *sql*

    We can also amend the above to only show Services that are in a “Stopped” state.

    Get-Service *sql* | Where-Object {$_.status -eq "Stopped"}

  • How to Install and Configure AWS CLI on Windows

    How to Install and Configure AWS CLI on Windows

    This post is a how-to for installing & configuring AWS CLI (Version 2) on Windows.

    In this guide, we’re going to download the AWS Command Line Interface installation media and run through the simple installation. Once done we’ll configure AWS CLI, which you’ll need an AWS Account to do so.

    # Install AWS CLI V2 on Windows
    # Configure AWS CLI V2

    Install AWS CLI V2

    Download AWS CLI V2 and run through the MSI installer. Run the .msi file you downloaded, and click next, next & done to complete the installation.

    Alternatively, we can install AWS CLI using the PowerShell commands below.

    # Download AWS CLI msi file, output to current directory
    Invoke-WebRequest -Uri https://awscli.amazonaws.com/AWSCLIV2.msi -UseBasicParsing -OutFile 'AWSCLIV2.msi'
    
    # Run AWS CLI install
    .\AWSCLIV2.msi
    AWS CLI Install Windows

    When the installation completes, close and re-open any terminals you have open. You should remember/consider doing this every time you install a package for development, close/reopen your VS Code or Windows Terminal.

    Open your command terminal and verify the AWS CLI install by checking the version. Run ‘aws –version‘ as shown in the example below.

    Check AWS CLI Version Windows

    Configure AWS CLI V2

    Now that we have AWS CLI installed on our machine, we need to open a web browser for the next steps, and head to the AWS Console.

    Open AWS IAM and create/select a user with appropriate permissions. My ‘pete‘ login has full Admin (AdministratorAccess Policy) in this case.

    AWS IAM Users

    Click on the Security Credentials tab within the user properties.

    AWS IAM User Creds

    Scroll down to view & create Access Keys. Click to create a new key to see both the Access key ID and Secret Access Key of existing keys.

    AWS IAM User Access Keys

    Open PowerShell and run ‘aws configure‘. You’ll be prompted for:
    AWS Access Key ID (above)
    AWS Secret Access Key (above)
    Default Region Name
    Default Output Format

    AWS CLI Check Version in PowerShell

    Once you’ve entered these details for the first time it’ll save your details, so for me above I’m just hitting enter at each prompt.

    Run ‘aws sts get-caller-identity‘ to confirm what you’re logged in as.

    AWS sts-get-caller-identity
  • How to Install Ubuntu 20.04 on WSL

    How to Install Ubuntu 20.04 on WSL

    This guide shows how to install Ubuntu 20.04 on WSL (Windows Subsystem for Linux). Before installing a WSL Linux distribution you should have already enabled WSL on your computer.

    All WSL Linux distributions are available for download in the Microsoft Store. This is the easiest way to install a WSL Linux distro. If you are automating WSL installations, you may be looking for the WSL distro download links and PowerShell install command.

    This post contains the following methods to get Ubuntu installed on WSL ->
    # Install WSL Ubuntu 20.04 via Microsoft Store
    # Install WSL Ubuntu 20.04 via Command

    Install WSL Ubuntu 20.04 via Microsoft Store

    You can find all the available WSL Linux distributions in the Microsoft Store available for download. This may be restricted by Group Policy if you’re on a Domain (a work/corporate computer).

    Click Start, open the Microsoft Store and simply search for the Ubuntu distribution version you desire.

    Microsoft Store Ubuntu WSL

    Click to download/install Ubuntu WSL, and then go ahead and install Windows Terminal while you’re at it.

    Windows Terminal Microsoft Store

    Once both of the above installs are complete, search and run Windows Terminal, then enter Ubuntu by running wsl in the terminal.

    Open WSL Ubuntu

    Install WSL Ubuntu 20.04 via Command

    To install WSL via PowerShell script or command, we’d download the WSL Linux distro and then extract/install it.

    The Microsoft Documentation contains a full list of WSL download links for each of the available WSL Linux distros:-
    – Ubuntu 20.04 (LTS / 18.04 LTS)
    – openSUSE Leap 15.1
    – SUSE Linux Enterprise Server (15 SP1 / 12 SP5)
    – Kali Linux
    – Debian GNU/Linux
    – Fedora Remix for WSL
    – Pengwin (+ Enterprise)
    – Alpine WSL
    – Raft (Free Trial)

    We are installing Ubuntu 20.04 in this demo, manually via a web browser rather than PowerShell Invoke-WebRequest or Curl.

    Move the downloaded file into some directory.

    Now into the directory within PowerShell, rename the file from .appx to .zip format.

    # rename Ubuntu appx file to zip format
    # add-appxpackage doesn't always work, extracting the .exe seems better
    Rename-Item .\Ubuntu_2004.2020.424.0_x64.appx .\Ubuntu_2004.zip

    Extract the zip file into a new directory.

    # extract the zip file into a new dir
    Expand-Archive .\Ubuntu_2004.zip .\Ubuntu_2004

    Run the ubuntu2004.exe file within the extracted directory and follow the setup instructions to create a new Linux login.

    Once done wsl should be waiting for you.

    Lastly, I’m now exiting (‘exit’ command) out of WSL, listing out my Linux distros and setting this Ubuntu 20.04 distro as my default.

  • Show Event Logs in PowerShell

    Show Event Logs in PowerShell

    In this post, we will explore how to use PowerShell to view event logs. We will use the Get-EventLog command to accomplish this. Specifically, we will cover the following:
    List Event Types Available
    Get Most Recent Events
    Get Events Between a Date Range

    List Event Types Available

    To list the available event log types on a system using the Get-EventLog command, you can run the following:

    # Get event types PowerShell
    Get-EventLog -List
    Get-EventLog -List

    This will return a list of event log types that are available on the system, such as System, Security, and Application. We can then use the -LogName parameter with Get-EventLog to specify a specific event log type to work with.

    Get Most Recent Events

    To return the most recent Windows events for investigating an error that occurred, you can use the following PowerShell command:

    # Get most recent Windows events PowerShell
    Get-EventLog -LogName System -Newest 100
    

    This command will retrieve the 100 most recent events from the System event log, which is where many critical errors and warnings are logged by Windows and other applications.

    In the next example below I am bringing back the newest 1000 error events, grouping by event name and count of error occurrences. This can give a high-level view of frequent events and recent events on the host.

    # Get most recent application events by count
    Get-EventLog -LogName Application -Newest 1000 -EntryType Error | Group-Object -Property Source -NoElement | Sort-Object -Property Count -Descending

    Get Events Between a Date Range

    Here is a PowerShell script that will get all critical and error events from the Windows event logs between a specified date range. The start and end dates can be passed as parameters to the script:

    param(
        [DateTime]$StartDate,
        [DateTime]$EndDate
    )
    
    # Get all critical and error events from the Windows event logs
    Get-WinEvent -FilterHashtable @{
        LogName = 'System, Application';
        Level = 1, 2;
        StartTime = $StartDate;
        EndTime = $EndDate
    }
    

    To run the script, you can use the following command, replacing START_DATE and END_DATE with the actual start and end dates:

    .\Get-CriticalAndErrorEvents.ps1 -StartDate '2021-01-01' -EndDate '2021-12-31'
    

    This script uses the Get-WinEvent cmdlet to retrieve events from the Windows event logs. It filters the events by log name (System and Application), level (critical and error), and date range (using the start and end date parameters). It then outputs the resulting events to the console.

  • Open Current Folder in PowerShell

    Open Current Folder in PowerShell

    When you are working within a PowerShell terminal session, you may want to open Windows Explorer for the current directory you are set as in your terminal. This guide will show you how to open the current working directory from PowerShell.

    Invoke-Item is the cmdlet to do this, and we add a ‘.’ to indicate we want the current working PowerShell directory.

    # Open current folder in windows explorer
    Invoke-Item .
    Invoke-Item PowerShell

    Invoke-Item can also be called with just ‘ii’, and you can specify a file and file path. We’re running a .ps1 script here, writing to output and opening the current directory. Windows Explorer will open when you run this.

    ## ps script to open the current folder
    write-output 'Opening current folder...' 
    ii .
    Run power shell script

    That’s about it for this one. Have a look at my PowerShell Tips tag for more random PowerShell Tips!