Certifications / Microsoft

First Steps to IT Automation with PowerShell

by Sabrin Alexander
First Steps to IT Automation with PowerShell picture: A
Follow us
Published on October 9, 2019

PowerShell is arguably the best automation language out there for systems administrators wanting to foray into IT automation. PowerShell offers an extensive library with which you can automate practically every aspect of your Microsoft Windows Server and desktop infrastructure.

PowerShell is an object-oriented scripting language, which means we can play around with the output of our command or script any way we would like with a lot of ease. PowerShell can be used to automate most of a sys admin's tasks, both simple to complex.

It's also one of those tools that can make your work day easier by helping you automate mundane tasks required to maintain and scale your infrastructure. Here's how to get started using PowerShell to automate many IT tasks.

The Basics of PowerShell

PowerShell is divided into variables, parameters, methods (commands) and pipelines. These are the four basic components of PowerShell you need to learn, which makes it very simple to understand.

With VBS or Batch, you have to learn and understand more than just the components. For example, you can't use VBS if you don't understand variables types, declaration, system objects and properties, functions and the specific wording of the syntax.

For PowerShell you just need to search for the command you want to use and the parameters. With only one command you can run a task that would take you an entire script in VBS or Batch. Here is one example. The script needs to look for a specific file in a folder structure and output the file location.

If we were using Batch or VBS (Visual Basic Scripting) our command would look like this:

Batch

1  for /r C:\ %%a in (*) do if "%%~nxa"=="FileToLookFor.txt" set p=%%~dpnxa
2  echo %P%

First Steps to IT Automation (Snippet) (fr migration)

VBS

Const startDir = "c:\"Set oFSO   = CreateObject("Scripting.FileSystemObject") sFileName  = "FileToLookFor.txt"Set oFolder = oFSO.GetFolder(startDir)Recurse(oFolder)Sub Recurse(oFldr)    If IsAccessible(oFolder) Then        For Each oSubFolder In oFldr.SubFolders             Recurse oSubFolder        Next         For Each oFile In oFldr.Files            If LCase(oFile.Name) = sFileName Then WScript.Echo sFileName, "exists."        Next     End IfEnd SubFunction IsAccessible(oFolder)  On Error Resume Next  IsAccessible = (oFolder.SubFolders.Count >= 0)End Function

If we were using PowerShell, we need just one line for that task.

1  Get–ChildItem –Path C:\ –Include *FileToLookFor* –File –Recurse –ErrorAction SilentlyContinue | Select–Object FullName

We can immediately see that PowerShell is the way to go. By using PowerShell we only need one line of code in a language, from which we can easily identify what each method does and getting the right output is as simple as accessing the correct object. Which, in our case, is the FullName property of the file we are looking for.

This is in comparison to Batch and VBS, in which we had to write an obscure line of code or a whole script for such a simple task.

This is the perfect example of how easily PowerShell gives you the option to adapt to scripting and development — because PowerShell uses a lot of the basics of Software Development. But before we get into that, let's take a look at our PowerShell line to further understand the ease of the syntax.

The initial command is Get-ChildItem, which is the equivalent of dir in Batch. It gives us the contents of a folder. The parameters that we are using are extremely intuitive, such as Path. The path of the folder, Include, lets us specify what to look for. File tells the command to only look for files. And Recurse enables us to go through the entire folder structure.

The last command is the Select-Object command, which lets us output only what we want. If we didn't have the Select-Object command at our disposal, getting the output we want would be daunting.

Grab PowerShell by the Horns and Start Scripting

We've seen that one line of PowerShell can complete a simple task. Now let's look at a PowerShell script and how we can automate a task that's a part of a typical workday. We will also learn how to create our own parameters with our own language for the script, making it easier to run it.

In this example script, we will take some specific files and copy them to another directory. This script is perfect for our example because it covers some advanced PowerShell features. It also shows us how PowerShell scripts can take on more complicated tasks yet keep the complexity of the code to a minimum.

1   params (
2 
3   $myLocation,
4 
5   $myDestination,
6   
7   $myFiles
8   $files = Get–ChildItem –Path $myLocation –Include $myFiles –Recurse
9   
10  ForEach ($File in $Files) {
11   
12  Copy–Item $file.FullName –Destination $myDestination

Even at first glance we can see the extreme complexity of this script. This is the beauty of PowerShell. The syntax is easy to learn and remember since it contains familiar words.

1  params (
2 
3  $myLocation,
4 
5  $myDestination,
6 
7  $myFiles

In the first script block we get acquainted with params, which lets us create our own parameters that we pass to the script once we run it. It's built out of variables so we can name them anything we want. For this example, we named them as close as possible to what value they hold, the original location of the files, which files to include and the destination.

1    $files = Get–ChildItem –Path $myLocation –Include $myFiles –Recurse

In the next script block, we gather all the files that we want using the Get-ChildItem command that we used in our previous example. A neat trick we do here is we take all the output of that command and assign it to a variable by using the assignment operator (the = sign). Once we've populated that variable with the desired info, it's time to do something with it.

1  ForEach ($File in $Files) {
2 
3  Copy–Item $file.FullName –Destination $myDestination

One thing that we did here that is more advanced is we've taken the output which is an array of objects and assigned it to a variable. Using ForEach, we are able to take each individual array object and do something to it — in our case, copy it to another location.

To run PowerShell scripts, first they are saved as .ps1 files. In our example the file can be called CopyFiles.ps1.

To run the file, we just open our PowerShell prompt and run it with the parameters we assigned to it. For example:

1    .\CopyFiles.ps1 –myLocation C:\SomeFolder –myFiles "*.docx" –myDestination C:\OtherFolder

How to use PowerShell for Day-to-Day Administration

The correct way to use PowerShell for day-to-day administration is to identify which tasks you do most often and their complexity. This is also a great way to master PowerShell, because different tasks or environments acquaint you with different PowerShell scripting styles, commands, and so forth.

A common mistake is creating a very complex PowerShell script to execute multiple tasks which will increase the complexity of the script, making it harder to understand and troubleshoot. This will ultimately increase the time you spend on those tasks. An alternative is to create smaller scripts and link them together with the goal of running those multiple tasks.

Software Development Fundamentals Used in PowerShell

Throughout this article we've touched several aspects of software development. We've talked about variables, methods (actions), arrays and assignment operators, which are basics of software development. Once you're well acquainted with PowerShell, you should have a foundation for software development, specifically C#.

Because PowerShell is an object-oriented language, most of the software development concepts are available to us — and we use them subconsciously through the work day. Of course, software development is an entirely different field than IT administration. Knowing your automation languages, and specifically PowerShell, will help you a great deal if you are looking to pursue a career in software development.

Your Next Steps…

The best way to learn PowerShell is through hands-on experience. Go ahead and try to use PowerShell to complete tasks where you would otherwise use the Windows UI. You can, for example, start by changing network configuration, manage your DNS and AD environment, and learn how to access and read files with PowerShell.

Theory, combined with practice, will help you reach another level in your IT career. Better yet, learning PowerShell can help you free up more time to do things you enjoy. Start learning today with CBT Nuggets.


Download

By submitting this form you agree to receive marketing emails from CBT Nuggets and that you have read, understood and are able to consent to our privacy policy.


Don't miss out!Get great content
delivered to your inbox.

By submitting this form you agree to receive marketing emails from CBT Nuggets and that you have read, understood and are able to consent to our privacy policy.

Recommended Articles

Get CBT Nuggets IT training news and resources

I have read and understood the privacy policy and am able to consent to it.

© 2024 CBT Nuggets. All rights reserved.Terms | Privacy Policy | Accessibility | Sitemap | 2850 Crescent Avenue, Eugene, OR 97408 | 541-284-5522