What is PowerShell?
You might know PowerShell as the improved command prompt version of Microsoft Windows, but PowerShell is more than that. It is also a scripting language that can be used for automation, and in this article we’ll show you how to automate tasks with PowerShell. PowerShell is built on the .Net CLR (Common Language Runtime), and as a scripting language, it can be used for automating the management of systems. You can use PowerShell to automate boring or repetitive IT tasks whether they are simple or complex. PowerShell even has backward compatibility with the command prompt, meaning you can type a CMD command in PowerShell and it will execute the command and return the output.
PowerShell is everywhere on Windows clients and servers and in macOS, Linux, and Cloud environments. Hence, it makes sense to use PowerShell to automate your day to day tasks. PowerShell is installed by default on your Windows system and you can easily install it on our Linux systems as well.
Why automate with PowerShell?
As an automation language, PowerShell has a wide array of modules to deploy and manage multiple ecosystems and technologies like Azure, Exchange, SQL, and many other third parties like AWS, VMWare, GCP, etc.
Using PowerShell you can automate tasks such as managing Active Directory users, managing and building Virtual Machines in Hyper-V, generating reports, monitoring performance, sending emails, etc. Automation with PowerShell is executing your commands via a script; those commands you type every day in PowerShell to do something. You can also use your PowerShell scripts and run them with Task Scheduler at desired times of the day.
PowerShell in Windows comes with the PowerShell ISE (Integrated Scripting Environment), which can help you write, test, and debug scripts in a GUI editor. The PowerShell ISE has some benefits when writing your scripts like syntax coloring, tab completion, and context-sensitive help. Of course, there are some other editors like Visual Studio Code, for example, that you can use. Using a GUI editor to create and test your scripts will make it easy to automate with PowerShell. There are even online resources like https://tio.run/#powershell where you can try some PowerShell commands (not like in Windows but is helpful).
How to create a PowerShell Script?
If you have used PowerShell, you have already executed commands to Get or Set configurations in Windows. Creating a script is saving those commands in a .ps1 file. A .ps1 file is a file that contains a script that is to be executed by PowerShell such as Get-Help. That is an easy-to-remember command that is not worth saving to a .ps1 file, but maybe Get-Date -DisplayHint Date is worth saving. We will see some more complex commands to save in .ps1 files later.
Note that by default in Windows, the default setting to execute scripts in PowerShell is not to allow scripts to run. PowerShell is enforcing its Execution Policy, which is Restricted by default. To check the execution policy, you can type Get-ExecutionPolicy. Also, check the help command in PowerShell by typing get-help set-executionpolicy. Finally, if you want to execute PowerShell scripts, you can change the execution policy by typing set-executionpolicy unrestricted or set-executionpolicy remotesigned depending on your requirements.
When you start to write these scripts, you might add one or more commands, and then you start scripting (which is writing a series of commands that can be executed) in PowerShell and saving your commands or tasks in a ps1 file.
A basic PowerShell script can be, for example:
Write-Host “Hello, Admin!”
Write-Host “Today is:”
Get-Date -DisplayHint Date
The output will display the Write-Host text strings and the date when you execute the command.
Or maybe something more advanced like installing a Windows Server role, for example:
Install-WindowsFeature -Name “Windows-Server-Backup” -IncludeAllSubFeature -IncludeManagementTools
The result will be that the Windows Server Backup role will be installed on the Windows system.
How to automate a simple task with PowerShell?
Automation might seem complicated but think of it as a series of steps executed in a system to reduce your input. A simple example to automate with PowerShell is to check the available Disk Space of a system:
Get-CimInstance -ClassName Win32_LogicalDisk -Filter “DriveType=3” |
Measure-Object -Property FreeSpace,Size -Sum |
Select-Object -Property Property,Sum | `
Export-CSV C:\Users\Administrator\Downloads\Computer-Storage.csv -NoTypeInformation -Encoding UTF8
The output should be a new CSV file containing the available disk space of a system and the total space.
Or maybe you want to automate a report that shows if a user password expired. We can write something like the following:
Get-ADUser -filter * -properties PasswordLastSet, PasswordExpired |
Sort Name |
Select Name, PasswordLastSet, PasswordExpired | `
Export-CSV C:\Users\Administrator\Downloads\Users.csv -NoTypeInformation -Encoding UTF8
The output should be a CSV file with all the users in Active Directory with their names when the password was last set and if the password is expired.
With the previous two examples, we can start querying for system information and status to understand how our systems are performing or just retrieving data on a time basis. There might be other use cases depending on your environment. For example, monitor Azure AD sign-in logs, check privileged group membership in Active Directory, expired passwords, users with the password never expire tick, etc.
You should start seeing the benefits of automating these sysadmin tasks with PowerShell. You should avoid complex scripts that do multiple tasks in one execution as a best practice. It might be challenging to debug and troubleshoot later if you have issues or need to update or modify the scripts. Also, remember to always comment on your scripts to remember what each line of code does or if someone else will be expanding your script, it will be beneficial to know what each piece of line does.
If you want to execute these scripts at a specific time automatically, just set a task in Task Scheduler and check your daily reports; no more typing the same commands to get your data every day.
How to create a task in Task Scheduler?
There’s a tool to run tasks automatically called Task Scheduler on Windows operating systems. The system and applications will use Task Scheduler to execute and run processes like updates, disk cleanup, backups, etc. but we can take advantage and automate with PowerShell
and schedule our scripts to execute at a particular day and time.
Follow these steps to create a Basic Task in Task Scheduler:
a. Click on the Windows button on the lower-left corner of your screen.
b. Type in the search box Task Scheduler.
c. Click on the Task Scheduler application.
d. On the Task Scheduler window, click on the Task Scheduler Library.
e. Right-click and select Create Basic Task.
f. Type a name for your task in the Name text box, optionally a Description, and click Next.
g. On the Task Trigger window, select weekly under When do you want the task to start?
h. Click Next to continue.
i. Choose a Start Date and Time on the Weekly window.
j. Select the Days you want the task to run and click Next.
k. Under the Action Window, select the Start a program radio button and click Next.
l. Now, here, we need to select the Powershell executable in the Program/Script by clicking the textbox click on the Browse button.
m. Browse to C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
n. In the Add arguments, you select the script location entering the path.
o. Click Next and Finish.
You can also edit the task once it is created or delete it if no longer needed.
Automate with PowerShell with security in mind
When creating your scripts as an Administrator, you want to automate with PowerShell with security in mind. You need to develop and test your scripts in a lab environment before using them in a production environment. Also, keep in mind that your Group Policy could require that your scripts are digitally signed before they can be executed. To fix this, either digitally sign the scripts or simply remove that requirement (less secure).
To check on these PowerShell policies, open Group Policy Editor and select the Group Policy to edit and navigate to Computer Configuration\Policies\Administrative Templates\Windows Components\Windows PowerShell. You will see different policies to manage PowerShell. Note that you can also apply them at the User level. For example, check out the Turn On Script Execution policy setting, and in the dropdown, you will see the three different options. RemoteSigned is Microsoft’s recommendation.
But setting one of these policies is not a security mechanism since there are some ways to bypass PowerShell execution Policies. Often, you’ll see a debate online on the best way to implement PowerShell Execution Policies.
Other ways to automate with PowerShell
With Windows PowerShell, you can use Desired State Configuration (DSC), which is a feature that helps sysadmins to do some advanced automation and specify the configuration of a machine. Think of it as having ten or a hundred Windows systems and setting the same setup to all.
What is PowerShell DSC?
With virtual machines in the cloud, physical servers and VMs being hosted on-premises, administrators have difficulty having a standard environment with the same baseline. Here is where DSC with its declarative model comes to the rescue to provide a way for system configuration management. That way, we can decide how our systems are to be configured with the help of PowerShell and the Windows Workflow engine.
One of the benefits of Desired State Configuration is to simplify your tasks by configuring any number of devices automatically.
There’s a lot of information related to DSC that is worth doing a Google search to find out more on how to use it and how it can apply to your use case.
How to learn to automate with PowerShell?
With PowerShell scripts on multiple websites on the Internet, one might be asking how to learn to automate with PowerShell? ServerAcademy.com has an entire module on Administration and Automation with Windows PowerShell that will get you started with the basics of PowerShell up to the use of PowerShell Desired State Configuration (DSC) Basics.
PowerShell is an excellent tool for system administration and is not going away, so it makes sense to learn its power to make your life easier as a sysadmin. Even information security professionals are learning how to use it to discover vulnerabilities or misconfiguration and secure system environments.
Sign up free and start learning today!
Practice on REAL servers, learn from our video lessons, interact with the Server Academy community!