How to Automate Tasks in Windows With PowerShell Scripts

On
Automating tasks through custom scripts

Automation is one of the benefits when using computing systems for different types of tasks. On a Linux system—in general—shell scripts are used to automate critical administration tasks. Is there something similar available on a Windows computer? Well, PowerShell scripts can be used to automate a wide array of jobs. It's like a Swiss army knife when it comes to automating simple to complex tasks on a Windows machine. Initially, learning it can take some time, but, when mastered, you can control your Windows computer through these scripts. Let's see how to use PowerShell scripts for task automation.

Automating tasks through custom scripts

Remember, whenever you write a script for automating any task, pay attention to its efficiency and security aspects. Both are critical for the proper functioning of the computer system.

Read Also:
A Step-by-Step Guide to Creating and Scheduling Custom Tasks on Windows

In this easy-to-follow tutorial, I've picked a simple task for demo purposes. The goal is to make you familiar with both the PowerShell script creation and its automation process. Let's get started!

PowerShell Scripting Basics

A PowerShell script is nothing but a collection of PowerShell commands written in a file with the .ps1 extension. You need to learn the PowerShell commands to create such scripts.

To run PowerShell scripts, simply prefix .\ to the script file name on the PowerShell command prompt. For example, if the name of the script file is hello-world.ps1, you can execute it by issuing the .\hello-world.ps1 command.

By default, PowerShell script execution is not allowed by Windows. To enable its execution, use the Set-ExecutionPolicy RemoteSigned command on the PowerShell command prompt.

Before firing the command shown above, make sure the PowerShell has administrative privileges. To do so, right-click the PowerShell shortcut and select the Run as Administrator option.

You can use any code editor to create such scripts. Let's learn some of the basic PowerShell commands and constructs.

Comments

Comments within a PowerShell script start with the # symbol. Here's an example.

# A single-line sample comment

<#
	A multi-line
    sample comment.
#>

Feel free to liberally use comments in your scripts. It can help you and others to understand what exactly it does.

Variables

Variables for storing data are also supported by PowerShell. Here's a simple example.

$Greeting = "Hello World!"
Write-Host "$Greeting"

We've created a variable $Greeting for storing a string. In the second line, we're printing the contents of this variable on the console or standard output.

Control-Flow Logic

No scripting or programming construct is incomplete without the ability to execute selective code based on different conditions. Fortunately, PowerShell has all the power to do so.

$OddOrEven = 27
if ($OddOrEven % 2 -eq 0) {
    Write-Host "It's an even number."
} else {
    Write-Host "It's an odd number."
}

If you're already familiar with programming, the if statement shown above needs no explanation.

for ($i = 0; $i -le 10; $i++)
{
    Write-Host $i
}

And, this is the classic for loop found in almost all modern programming languages.

Command Line Parameters

No scripting language can be flexible enough if it doesn't support command-line parameters. PowerShell command line parameters can be handled via the param ( ... ) block.

This block should come first in every script. Here's an example.

param (
		[int]$num
      )
if ($num % 2 -eq 0) {
    Write-Host "It's an even number."
} else {
    Write-Host "It's an odd number."
}

We've used the same example—but this time—the value is neither hardcoded nor preassigned to a variable. We're taking the number dynamically from the command line during the execution of the script.

We can run this script in two different ways.

# Method 1
.\odd-or-even.ps1 -num 65

# Method 2
powershell.exe -file odd-or-even.ps1 -num 65

You can capture multiple command-line arguments separated by white space. Always try to keep the command-line arguments to the minimum or avoid them altogether—if possible.

Functions

Grouping reusable or repetitive code into functions is a great way to modularize the codebase. PowerShell supports functions and here's how we can use it in our scripts.

# A function to add two numbers
function AddNumbers {
    param (
        [int]$first,
        [int]$second
    )

    $result = $first + $second
    Clear-Host
    Write-Output "After adding $first and $second, we get $result"
}

# Call the function with two numbers as parameters
AddNumbers -first 56 -second 73

It's a function to add numbers. Notice how function arguments are declared in the beginning followed by the function body. Use meaningful functions and variable names to make your code—readable.

Exception Handling

Error handling is the cornerstone of writing bullet-proof code that handles exceptional conditions and terminates gracefully. PowerShell scripts have a powerful error-handling mechanism. Let's start with the Try-Catch-Finally block.

try {
    # Execute code that may generate an error
    Get-BlackHoleCmdlet
}
catch {
    # Handle the error
    Write-Host "An error has occurred: $($_.Exception.Message)"
}
finally {
    # This chunk of code is executed in every condition
    Write-Host "Script bla-bla completed its execution."
}

The chunk of code that may generate an error is encapsulated in the try { ... } block. If an error occurs, the catch { ... } block is executed. And, the finally { ... } block is executed regardless of whether an error has occurred or not.

PowerShell scripts also have access to the $Error array which contains information about the most recent errors. Feel free to use it, wherever required.

# A command whose error should be ignored
Remove-Item -Path "F:\database\imaginary-file.xls" -ErrorAction SilentlyContinue

One can also use the -ErrorAction parameter while executing PowerShell commands to customize the default behavior in case of an error. In the example given above, we chose to silently continue with the script execution.

Example Script: Send an Email Alert if Drive Space Is Running Out

Now that we've gone through the basics of PowerShell scripting, it's time to present a demo of performing a job on an automated basis through a PowerShell script.

So, we'll create a script that'll trigger once a day or once a week. Upon its execution, it'll check all the logical hard drives in Windows to see if any one of them has a space of less than 25 GB.

If so, an alert will be sent to the designated email address informing about the low disk space on the drive in question. Let's write the script.

# Add information
$recipientEmail = "recipient@domain-name.com"
$senderEmail = "username@gmail.com"
$smtpServer = "smtp.gmail.com"
$smtpPort = 587
$smtpUsername = "username"
$smtpPassword = "app_password"

# Send an email alert
function Send-Email-Alert {
    param (
        [string]$subject,
        [string]$body
    )
    
    $smtp = New-Object Net.Mail.SmtpClient($smtpServer)
    $smtp.Port = $smtpPort
    $smtp.Credentials = New-Object System.Net.NetworkCredential($smtpUsername, $smtpPassword)
    $smtp.EnableSsl = $true

    $mail = New-Object Net.Mail.MailMessage
    $mail.From = $senderEmail
    $mail.To.Add($recipientEmail)
    $mail.Subject = $subject
    $mail.Body = $body

    $smtp.Send($mail)
}

# Get all drives' free space information and send an email alert, if applicable
Get-CimInstance -ClassName Win32_LogicalDisk | ForEach-Object {
    $drive = $_
    if ($drive.FreeSpace -lt 25GB) {
        $subject = "Low Disk Space Alert (Drive: $($drive.DeviceID))"
        $body = "The drive $($drive.DeviceID) has less than 25 GB of free space left. It has $freeSpaceGB GB of free space."
        Send-Email-Alert -subject $subject -body $body
    }
}

First, we'll provide all the necessary information required to send the email. We're using Google's SMTP server for the same and using the sender's Gmail address for the same.

To make it work, make sure your Google account's 2-factor authentication is—switched on. Next, create an app password for this script within your Google account settings.

Assign the recipient's email address, your Gmail address, your Google account's username, and the app password—generated earlier—to the relevant variables in the script.

Feel free to customize the text of $subject and $body variables.

We're using Get-CimInstance cmdlet to get information about all the logical drives of the Windows installation. Similarly, we're using the Get-WmiObject cmdlet to access the Net.Mail.SmtpClient .NET library object.

This object is then used the send the email. As mentioned in the first section, you have to learn all the PowerShell commands to be able to write such scripts.

Automate PowerShell Script Execution

We've created a PowerShell script to scan all drives and send an email alert for every drive having a free space of less than 25 GB. But, this script won't execute on its own. You can run it manually.

The final step is to automate its execution.

For our demo, we'll configure it to run every week on Monday. Depending on your needs, you can specify a different triggering condition for your PowerShell scripts.

Shortcut for Windows Task Scheduler

Start by pressing the Windows + S key and typing Task Scheduler in the search box. You'll get the application's option in the menu as shown above. Click it to open the task scheduler.

Now click the Create Task... option present in the right sidebar. It'll open a multi-tab dialogue box to configure the settings of the scheduled task.

General settings of a scheduled task on Windows

On the General tab, start by giving a meaningful name to the scheduled task.

Check the box to give the highest privileges to the task to make sure it runs smoothly without any issues. Similarly, check the Hidden option to ensure it runs silently without any visibility in the task manager.

Lastly, select the operating system you want to run it on from the dropdown menu. It'll ensure maximum compatibility when executing the task code.

Trigger settings for a scheduled task on Windows

The next one is the Triggers tab. In this tab, select the time or schedule you want to run the task. For the demo, I chose weekly execution on Monday. Feel free to modify it as per your needs.

Action settings for a scheduled task on Windows

And lastly on the Actions tab, there's a Program/script: text box. In this box, provide the command you want to run.

In this case, we'll type the powershell.exe <path to the PowerShell script file> command in this text box. PowerShell is the shell or program we want to run and script is the argument to the shell or program it should execute.

And, that's it! The rest of the tabs can be ignored.

Conclusion

With the help of PowerShell scripts, one can perform simple to complex tasks on a Windows machine. But, it requires some effort to learn this scripting language. Once you go past the beginner's level, the possibilities of creating complex tasks are endless.

And when these scripts are paired with the task scheduling feature of Windows, you can control your Windows machine on autopilot. So, what are you waiting for? Go ahead and try it yourself—once.