Windows PowerShell Scripting Tutorial For Beginners (2024)

Windows PowerShell is a powerful tool for automating tasks and simplifying configuration and can be used to automate almost any task in the Windows ecosystem, including active directory and exchange. It’s no wonder that it’s become a popular tool among sysadmins and experienced Windows users.

In our PowerShell Tutorial, we showed you how to use some of the most useful PowerShell tools. Now it’s time to take the next step: using these tools from within scripts that can be executed with just one click. This PowerShell scripting tutorial will show you how to write and execute basic scripts in PowerShell, and ultimately save you a lot of time.

Get the free PowerShell and Active Directory Video Course

  • What is PowerShell ISE?
  • PowerShell Uses and Features
  • Launching PowerShell
  • Basic Features
  • Before Running Scripts
  • How to Find Commands
  • How to Run a Script
  • Basic Script Examples
  • Windows PowerShell Resources

What is PowerShell Language?

PowerShell language is a high-level proprietary programming syntax developed by Microsoft for the key purpose of enabling system administrators to automate actions and configurations. The language is based on object-oriented standards but can only be used in Windows environments. It is part of the .NET framework and typically has C# code underlying its functions, although knowledge of C# is not a prerequisite for learning PowerShell. The closest comparison to the PowerShell language is Perl, which is used in similar scenarios on Linux environments.

With the PowerShell language, each unique function is referred to as a cmdlet. A cmdlet has one or more sets of defined actions and is capable of returning a .NET object. Some of the most basic cmdlets that come pre-configured with PowerShell are ones for navigating through a folder structure and moving or copying files.

What is the PowerShell ISE?

New PowerShell cmdlet functions can be written in any text editor or word processing tool. However, the latest versions of the Windows operating system include a tool called the PowerShell ISE (Integrated Scripting Environment) to make scripting even easier and more robust.

When you open the PowerShell ISE for the first time, it may look like a familiar command prompt window. However, the tool contains much more functionality and support for writing code. The PowerShell ISE contains a full list of all the common modules and cmdlets that system administrators may need to use. When you are ready to start writing your own cmdlet functions, the debugging tool within the PowerShell ISE will allow you to test your code, identify bugs or issues, and then work to fix them. Like other coding environments, the PowerShell ISE is highly customizable. Users can choose the color scheme, font, and theme they want to use while writing scripts. New scripts created in the ISE will be given the .psi file extension which can only be run in PowerShell environments.

The scripting language in PowerShell will be familiar if you’ve used the Windows Command Prompt. Objects and data piping work in a similar way, for instance, as does ping:

However, the syntax used in PowerShell is, in most instances, much simpler and easier to read than the commands used in Command Prompt.

Windows PowerShell Uses and Features

Windows PowerShell Scripting Tutorial For Beginners (2)

Though Windows PowerShell can be used for a wide range of different applications, for a beginner, the primary utility of PowerShell scripts will be in regard to systems automation related to:

  • Working with batches of files, whether this be to automate backups or to control access to large numbers of files at once.
  • PowerShell scripts are also very useful when adding and removing new users. With a carefully designed script, you can automate the process of adding network drives, updating security software, and granting a new user access to shared files.
  • In order to perform these tasks, you’ll make use of several key features of PowerShell, such as cmdlets and aliases (which I will cover below).

Launching PowerShell

In Windows 10, the search field is one of the fastest ways to launch PowerShell. From the taskbar, in the search text field, type powershell. Then, click or tap the ‘Windows PowerShell’ result.

To run PowerShell as administrator, right-click (touchscreen users: tap and hold) on the Windows PowerShell search result, then click or tap ‘Run as administrator’.

There are also many other ways to start a PowerShell console, but this is a good method to begin with.

Basic Features of PowerShell

If you are new to PowerShell, take a look at our PowerShell Tutorial before reading this guide to PowerShell scripting. In that guide, you’ll find descriptions of all the basic tools you’ll need to work with PowerShell. This includes cmdlets, aliases, help commands, and pipes.

Once you’ve mastered the basic commands, you can begin to write scripts. As your skills develop, you might also like to take a look at our guides on Input Options for PowerShell, and also read through the resources at the bottom of this article.

Windows PowerShell Scripting Tutorial For Beginners (3)

Before Running PowerShell Scripts

PowerShell scripts, like those we are going to create in this tutorial, are saved as .ps1 files. By default, Windows will not allow you to run these scripts by just double-clicking the file. This is because malicious (or poorly written) scripts can cause a lot of accidental damage to your system.

Instead, to run a PowerShell script, right-click the .ps1 file, and then click ‘Run with PowerShell’.

If this is your first time working with PowerShell scripts, this might not work. That’s because there is a system-wide policy that prevents execution. Run this command in PowerShell:

Get-ExecutionPolicy

You will see one of the following outputs:

  • Restricted— No scripts will be executed. This is the default setting in Windows, so you’ll need to change it.
  • AllSigned— You can only run scripts signed by a trusted developer. You will be prompted before running any script.
  • RemoteSigned— You can run your own scripts or scripts signed by a trusted developer.
  • Unrestricted— You can run any script you want. This option should not be used, for obvious reasons.

To start working with PowerShell scripts, you’ll need to change this policy setting. You should change it to ‘RemoteSigned’, and you can do that right from PowerShell by running the following command:

Set-ExecutionPolicy RemoteSigned

Now you are ready to get started.

How to Find PowerShell Commands

People love PowerShell because it’s so, well, powerful. But that power comes from an absolutely insane amount of complexity. It’s just not feasible or practical for someone to memorize all of the different commands, cmdlets, flags, filters and other ways of telling PowerShell what to do.

Thankfully, built right into the editor are multiple tools to help you deal with this fact.

  • Tab Completion
  • Get-Command
  • Syntax
  • One Big String vs Object Properties

Tab Completion

There’s no need to memorize all of the different commands or exact spelling of a command. Type get-c into the editor and hit the TAB key – you’ll cycle through all the commands beginning with what you had input so far. This works at any section of the command you’re trying to invoke, the name (as shown below), but also flags and paths that you’re manipulating to get your desired outcome.

Get-Command

While tab completion works well, what happens if you don’t know the name of the command you’re looking for? In that case, you’d use a command for finding other commands:

Get-Command

In searching for commands, it’s important to keep in mind that there’s a syntax to them: VERB-NOUN. Typically the verbs are things like Get, Set, Add, Clear, Write and Read and the Nouns are the files, servers, or other items within your network and applications.

Get-Command is a discovery tool for exploring the commands available on your system.

PowerShell’s Command Syntax

Someone once described the Perl scripting language as looking like “executable line noise” – an incredibly useful tool with a wildly opaque syntax and a correspondingly high learning curve.

While not quite to that level, the traditional command prompt in Windows isn’t too far off. Consider a common task like finding all the items in a directory whose names start with the string ‘Foo’.

CMD: FOR /D /r %G in (“Foo*”) DO @Echo %G

  • FOR and DO indicate that it’s a loop.
  • The /D flag indicates this is for Directories
  • The /r flag indicates that “Files Rooted at Path”
  • The pattern that defines the set of files to be looped over is designated with “in”
  • @Echo instructs the script to write out the result of each loop and finally;
  • %G is the “implicit parameter” and is chosen because earlier developers had already used the pathname format letters a, d, f, n, p, s, t, and x. So, starting with G is traditional as it gives you the largest set of unused letters for returned variables ( G, H, I, J, K, L, M) – in other words, it’s an ugly hack.

Compare that to the PowerShell equivalent:

PowerShell: Get-ChildItem -Path C:\Example -Filter ‘Foo*’

The output’s functionally the same, but even in this fairly trivial example, it’s much, much easier to understand what’s happening. It’s immediately obvious what all the elements in the command do and how you could modify them. The only slightly non-obvious thing here is the * wildcard character (present in both examples) which indicates that the pattern used to match items should start with ‘Foo’ and end in anything else.

It just keeps getting better from here as, say you want to know how to identify just files (not directories) in the path? You could dig up the docs, Google around and try to sort that out with the command line version, or if you’re in PowerShell, type “-” and hit the tab key, rolling through the flag options until the obvious solution shows up.

One Big String vs Object Properties

Servers are no good to anyone if they’re not online. Which is why people spend an inordinate amount of time pretending they’re sonar operators on a submarine and pinging them (yes, that’s actually why it’s called that).

While the output from ping is useful (and you can use ping within PowerShell), at the end of the day the output is just a big string – a series of letter and number characters with no definite breaks between them).

PowerShell has a command that’s analogous to ping, but that returns data that’s structured, making it easy to work with. That command is Test-Connection.

Below you can see the output of pinging a server (named ‘DC’ on their local network) and the equivalent Test-Connection output.

Putting aside that it’s easier to read, what’s really important is that you can now pass this information off to another command, incorporate it into a larger utility (as this full course is working towards) or just tweak it so that it makes more sense.

How To Run A PowerShell Script

There are two main ways to make a PowerShell script:

  1. The first, which will be familiar if you’ve used Windows Command Line before, is to write scripts directly in notepad. For example, open a new notepad file, and write

Write-Host “Hello World!”

Then save this file as FirstScript.ps1

You can call the script from PowerShell using the command:

& "X:\FirstScript.ps1"

And you’ll see the output in PowerShell.

  1. The second, much more powerful way of making PowerShell scripts is to use the Windows PowerShell Integrated Scripting Environment (ISE). With ISE, you can run scripts and debug them in a GUI environment.

ISE also features syntax highlighting, multiline editing, tab completion, selective execution, and a whole host of other features. It will even let you open multiple script windows at the same time, which is useful once you have scripts that call other scripts.

Though it might seem like overkill right now, it’s worth working with ISE right from the beginning. That way, you can get used to it before you start writing more complex scripts.

Basic PowerShell Script Examples

Now you can start to write PowerShell scripts. So let’s go through the process step by step.

  • Get The Date
  • Force Stop Processes
  • Check if a File Exists
  • Setting Up a VPN
  • PowerShell Punctuation Recap

Example Script 1: Get The Date

Let’s start with a simple script. In ISE or notepad, open a new file. Type:

Write-Host get-date

And then save the file as GetDate.ps1

You can call the script from PowerShell using the command:

& "C:\GetDate.ps1"

And you’ll see the output in PowerShell. Simple, right?

Example Script 2: Force Stop A Process

If you have a Windows service running that has frozen, you can use a PowerShell script to stop it. For instance, suppose my company uses Lync for business communications and it keeps freezing and Lync’s process ID is 9212. I can stop Lync with a script.

To do that, make a new script file in the same way as before. This time, type:

stop-process 9212

or

stop-process -processname lync

Save the file as StopLync.ps1, and then you can invoke the script using:

& "X:\StopLync.ps1"

This script can be expanded to stop a number of processes at once, just by adding extra commands of the same type. You can also write another script if you want to automatically start a number of processes at once, using:

start-process -processname [your process here]

This is particularly useful if you want to start a bunch of networking processes at once, for instance, and don’t want to enter the commands separately.

Example Script 3: Check if a File Exists

Suppose you need to delete multiple files, you might want to first check to see if the files even exist.

test-path, as the name implies, lets you verify whether elements of the path exist. It’ll return TRUE, if all elements exist, and FALSE if any are missing.

You simply type:

test-Path (And then the file path)

Example Script 4: Set up a VPN on a new machine

Now you’ve got the basics, let’s write a script that will actually do something useful. For sysadmins, one of the major advantages of PowerShell is that it allows you to automate the process of setting up new machines.

Today, individuals and businesses alike both use virtual private networks as a near mandatory security measure to protect proprietary data. All new machines should be connected to a VPN during setup. While you could handle each one manually, this is the kind of thing PowerShell is perfect for. For beginners – ie, most people reading this guide – most quality VPN services will work for your computing environment, we can write a script that will automatically set up and configure it.

The most basic way to do this is to open a new file like before, and then type the command:

Set-VpnConnection -Name "Test1" -ServerAddress "10.1.1.2" -PassThru

You will need to set your server address to the address of your local VPN server, and by using the ‘PassThru’ command this script will return the configuration options of the VPN.

Save the file as SetVPN.ps1, and then you should be able to call it in the same way as before, using

& "X:\SetVPN.ps1"

Now. The first time you call this command, you might get some errors. But that’s all part of the process of learning PowerShell scripts. Fear not: whenever you run into an error like this, just take a look at Microsoft’s official guide for the ‘Set-VpnConnection’ command and adapt the examples there to suit your system.

PowerShell Punctuation

Here’s a table to summarize some of the PowerShell punctuation we’ve used:

SymbolNameFunctionExample
$Dollar SignDeclares a variable$a
=EqualAssigns a value to the variable$a=get-date
“”Double QuoteUse double quotes to display textIf $a = Monday

“Day of the Week: $a”
will output as:

Day of the Week: Monday

+PlusConcatenates$a = November

“Day of theWeek: ”
+ $a.Dayofweek

Day of the Week:Monday

( )ParenthesisGroups to create argument(get-date).day

Windows PowerShell Resources

Below are the latest tutorials, and I’ve culled them down to a top ten:

Getting Started with PowerShell

  1. PowerShell for Beginners – A library of links to get started, best practices, command line syntax and more!
  2. Don Jones’ bestselling PowerShell book, Learn Windows PowerShell in a Month of Lunches is also in video! After 3-4 months of lunches with the tutorial video series, you’ll be automating admin tasks faster than you ever thought possible. By the way, the author answers questions atpowershell.org. There are numerous PowerShell resources, events, and even free ebooks!
  3. If you’re taking the MCSA 70-410 Microsoft Exam, these flashcards will help: PowerShell commands.
  4. PowerShell allows you to string multiple commands together on one line using a technique called pipelining. It makes complex things much simpler, and you can learn about it here.

Configure and Manage Active Directory

Save even more time by learning how to configure and manage Active Directory using PowerShell with these resources:

  1. Use PowerShell to Search AD for High-Privileged Accounts.
  2. Use AD module cmdlets to perform various administrative, configuration, and diagnostic tasks in your AD DS and AD LDS environments.
  3. Build an AD utility from scratch in this epic 3 hour PowerShell video course (unlock for free with code: PSHL)

Automate Exchange

With all that free time you have, why not learn how to automate Exchange with these resources:

  1. If you’re an Exchange Admin, make sure you have these 5 skills down
  2. Click here for more PowerShell tips for Exchange Admins. Then scroll down for the good stuff.

A Final Word

We hope that this PowerShell scripting tutorial for beginners has given you everything you need to get started with PowerShell scripts. Once you’ve mastered the basics of the PowerShell syntax, working with scripts is pretty easy: just make sure that you keep all your scripts organized, and you name them in a way that it’s obvious what they do. That way, you won’t get confused.

And once you’ve mastered scripts, there really is no end to what you can do with PowerShell. Take a look at our guide to active directory scripting, for instance, for just a taste of the flexibility that PowerShell can provide.

I’ll finish, though, with just one word of warning: don’t rely on PowerShell alone to manage data security and access. Even after you become an expert in PowerShell scripting, the intricacies of GDPR and similar frameworks make data management simply too complex for such a blunt tool. Instead, you should consider consulting an expert on how to manage access to the data stored on your systems.

Windows PowerShell Scripting Tutorial For Beginners (2024)

FAQs

Is PowerShell scripting easy to learn? ›

Getting started with Microsoft PowerShell can be really easy, since the language is simple and you can easily get information about any cmdlet. But it's essential to also understand the systems you are interfacing with, so that your scripts do not lead to serious issues, such as system downtime or security incidents.

How do I run a PowerShell script step by step? ›

You can execute a PowerShell script by following these steps:
  1. Launch Windows PowerShell as an Administrator. You should see a command-line window with a PS> prompt.
  2. Navigate to the directory containing the script. ...
  3. Execute the script using .\ syntax to tell PowerShell to look for the script in the current directory:
Apr 15, 2024

What is a good practice for scripting in PowerShell? ›

Avoid using plural names for parameters whose value is a single element. This includes parameters that take arrays or lists because the user might supply an array or list with only one element. Plural parameter names should be used only in those cases where the value of the parameter is always a multiple-element value.

What does a PowerShell script look like? ›

A script is a plain text file that contains one or more PowerShell commands. PowerShell scripts have a . ps1 file extension. Running a script is a lot like running a cmdlet.

How fast can you learn PowerShell? ›

How Long Does it Take to Learn PowerShell? PowerShell is a powerful command-line interface solution for Windows devices. As such, it usually takes around one to two weeks to get a handle on it.

Is IT better to learn CMD or PowerShell? ›

Ultimately, sysadmins and technicians should learn PowerShell so they can manage systems more efficiently. The scripting engine makes automating tasks like bulk updates and changing files much easier and more streamlined.

Is IT better to learn PowerShell or Python? ›

Conclusion. PowerShell vs Python does not make an apple-apple comparison in many ways. Python is an interpreted high-level programming language whereas PowerShell provides a shell scripting environment for Windows and is a better fit if you choose to automate tasks on the Windows platform.

What's the difference between PowerShell and command prompt? ›

PowerShell is not just a command shell but a scripting language too. It allows for more complex operations, automation, and system management tasks compared to the limited scope of Command Prompt.

How do you step into a PowerShell script? ›

If the current statement is a function or script call, then the debugger steps into that function or script, otherwise it stops at the next statement. Press F11 or, on the Debug menu, click Step Into, or in the Console Pane, type S and press ENTER .

How to use PowerShell on Windows? ›

From the taskbar, in the search text field, type powershell. Then, click or tap the 'Windows PowerShell' result. To run PowerShell as administrator, right-click (touchscreen users: tap and hold) on the Windows PowerShell search result, then click or tap 'Run as administrator'.

How to start PowerShell from CMD? ›

At the Command Prompt

In Windows Command shell, Windows PowerShell, or Windows PowerShell ISE, to start Windows PowerShell, type: PowerShell . You can also use the parameters of the powershell.exe program to customize the session.

What must you said before you can run a PowerShell script? ›

Prerequisites: You need to be able to run PowerShell as an administrator. You need to set your PowerShell execution policy to a permissive value or be able to bypass it.

What is the best app for PowerShell scripts? ›

PowerShell Studio | The Most Powerful PowerShell GUI Designer and Script Debugger Available.

What tool to write PowerShell script? ›

Popular frameworks, libraries, and tools used with PowerShell Script are:
  • Modules and Libraries: PSReadLine, Pester, PowerCLI, Azure PowerShell.
  • Automation Tools: Task Scheduler, Jenkins, Azure DevOps.
  • Configuration Management: DSC (Desired State Configuration), Chef, Puppet.

How do I write a PowerShell script from Command Prompt? ›

To run PowerShell scripts from Command Prompt in Windows, follow these steps:
  1. Open Command Prompt as an administrator.
  2. Type powershell to launch PowerShell.
  3. To execute a script, use the command powershell -File " path\to\your\script. ps1 " . Replace " path\to\your\script. ps1 " with the path to your script file.
Aug 28, 2024

Where can I write PowerShell scripts? ›

You can build the script in the PowerShell Integrated Scripting Environment (ISE) editor that comes with Windows. Open the PowerShell ISE editor, copy the code and save it as Start-StoppedServices. ps1. All PowerShell scripts have a PS1 extension for Windows that prompts the PowerShell engine to execute the script.

Top Articles
Pros & Cons of Home Equity Loans - Are They Really Worth It?
Home Equity Loan Pros And Cons | Bankrate
Duralast Gold Cv Axle
Did 9Anime Rebrand
America Cuevas Desnuda
Craigslist In South Carolina - Craigslist Near You
Calamity Hallowed Ore
Umn Pay Calendar
Craigslist Dog Sitter
Slay The Spire Red Mask
Rainfall Map Oklahoma
TS-Optics ToupTek Color Astro Camera 2600CP Sony IMX571 Sensor D=28.3 mm-TS2600CP
Moviesda3.Com
Craigslist Free Stuff Santa Cruz
Craigslist Southern Oregon Coast
Foxy Brown 2025
12 Top-Rated Things to Do in Muskegon, MI
Mybiglots Net Associates
Certain Red Dye Nyt Crossword
Reviews over Supersaver - Opiness - Spreekt uit ervaring
Ontdek Pearson support voor digitaal testen en scoren
Asteroid City Showtimes Near Violet Crown Charlottesville
Sand Dollar Restaurant Anna Maria Island
What Equals 16
Best Middle Schools In Queens Ny
Publix Near 12401 International Drive
Striffler-Hamby Mortuary - Phenix City Obituaries
Possum Exam Fallout 76
LG UN90 65" 4K Smart UHD TV - 65UN9000AUJ | LG CA
FSA Award Package
Planned re-opening of Interchange welcomed - but questions still remain
Shauna's Art Studio Laurel Mississippi
Tmj4 Weather Milwaukee
How to Play the G Chord on Guitar: A Comprehensive Guide - Breakthrough Guitar | Online Guitar Lessons
THE 10 BEST Yoga Retreats in Konstanz for September 2024
The Land Book 9 Release Date 2023
Dying Light Nexus
The Thing About ‘Dateline’
The Holdovers Showtimes Near Regal Huebner Oaks
South Bend Tribune Online
The best specialist spirits store | Spirituosengalerie Stuttgart
Setx Sports
Doublelist Paducah Ky
Expendables 4 Showtimes Near Malco Tupelo Commons Cinema Grill
Rise Meadville Reviews
Stitch And Angel Tattoo Black And White
Star Sessions Snapcamz
Okta Login Nordstrom
Home | General Store and Gas Station | Cressman's General Store | California
Suzanne Olsen Swift River
The Missile Is Eepy Origin
Primary Care in Nashville & Southern KY | Tristar Medical Group
Latest Posts
Article information

Author: Terrell Hackett

Last Updated:

Views: 6483

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Terrell Hackett

Birthday: 1992-03-17

Address: Suite 453 459 Gibson Squares, East Adriane, AK 71925-5692

Phone: +21811810803470

Job: Chief Representative

Hobby: Board games, Rock climbing, Ghost hunting, Origami, Kabaddi, Mushroom hunting, Gaming

Introduction: My name is Terrell Hackett, I am a gleaming, brainy, courageous, helpful, healthy, cooperative, graceful person who loves writing and wants to share my knowledge and understanding with you.