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-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*
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.
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 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.
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
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.
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:
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 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.
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.
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
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.
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.
Click on the Security Credentials tab within the user properties.
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.
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
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.
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.
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.
Click to download/install Ubuntu WSL, and then go ahead and install Windows Terminal while you’re at it.
Once both of the above installs are complete, search and run Windows Terminal, then enter Ubuntu by running wsl in the terminal.
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.
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
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.
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
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:
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.
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 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 .
That’s about it for this one. Have a look at my PowerShell Tips tag for more random PowerShell Tips!