PowerShell Code Snippets

Below are some useful PowerShell code snippets for use in everyday projects.

When dealing with directories and files it may be necessary to check for their existence. Below is an example of how to do this.

# Example path and file.
$exampletPath = "C:\demo\";
$exampleFile = "example.txt";

# Check if the path exists.
if (Test-Path($exampletPath))
{

    Write-Host("The path '$exampletPath' exists.")

}
else
{

    Write-Host("The path '$exampletPath' doesn't exist.")

}

# Check if the file exists.
if (Test-Path($examplePath + $exampleFile))
{

    Write-Host("The file '$exampletPath$exampleFile' exists.")

}
else
{

    Write-Host("The file '$exampletPath$exampleFile' doesn't exist.")

}

PowerShell can be used to copy and move files.

# Example paths and files.
$exampletPathSource = "C:\demo\";
$exampletPathDestination = "C:\demo\backup\";
$exampleFile1 = "example1.txt";
$exampleFile2 = "example2.txt";

# Copy the example1.txt file.
Copy-Item ($exampletPathSource + $exampleFile1) `
    -Destination ($exampletPathDestination + $exampleFile1) -Force

# Move the example2.txt file.
Move-Item ($exampletPathSource + $exampleFile2) `
    -Destination ($exampletPathDestination + $exampleFile2) -Force

Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.

# Minimum and maximum values for random number.
$minVal = 1
$maxVal = 59

# Generate random number.
$random = Get-Random -Minimum $minVal -Maximum $maxVal

# Display the resulting random number.
Write-Host $random

Here, a random password is generated from a specified set of characters. The length of the password is also randomly selected from a given minimum and maximum length.

# Possible characters in password.
$alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
$numbers = '0123456789'
$nonAlpha = '{]+-[*=@:)}$^%;(_!&#?>/|.'

# Put possible password characters into a character array.
$charSet = ($alpha + $number + $nonAlpha).ToCharArray()

# Minimum and maximum password length.
$minLength = 20
$maxLength = 30

# Select a random password length between the minimum and maximum.
$length = Get-Random -Minimum $minLength -Maximum $maxLength

# Character array for password of the desired length.
$result = New-Object char[]($length)

# Construct new password.
for ($i = 0 ; $i -lt $length ; $i++) {

    # Select a random character from the possible characters array.
    $selected = Get-Random -Minimum 0 -Maximum ($charSet.Length-1)

    # Add the chosen character to the new password.
    $result[$i] = $charSet[$selected]
}

# Display the password.
Write-Host (-join $result)

When handling a number of files, it can sometimes be useful to compress them in to one file. PowerShell can be used to both create and extract from a zip archive.

# Example paths and files.
$exampletPathSource = "C:\demo\";
$exampletPathDestination = "C:\demo2\";
$examplePathZip = "C:\temp\demo.zip";

# Create the zip archive file.
Compress-Archive -Path $exampletPathSource* -DestinationPath $examplePathZip -Force

# Extract the zip archive file.
Expand-Archive -LiteralPath $examplePathZip -DestinationPath $exampletPathDestination -Force

This lists all files modified in the last 30 days, within a directory called 'Demo', including any sub folders there may be.

Get-ChildItem -Path "C:\Demo" -Recurse `
    | Where-Object -FilterScript { $_.LastWriteTime -ge (Get-Date).AddDays(-30) }

This lists all files modified after the specified date and time, within a directory called 'Demo', including any sub folders there may be.

Get-ChildItem -Path "C:\Demo" -Recurse `
    | Where-Object -FilterScript { $_.LastWriteTime -gt (Get-Date '09 May 2021 14:00') }