Windows PowerShell & Scripting: A Complete Guide

PowerShell & Scripting Guide
This comprehensive guide is your gateway to mastering Windows PowerShell, a powerful tool designed to streamline tasks and automate processes on Windows machines. Whether you're a beginner or looking to enhance your existing skills, this guide will equip you with the essential knowledge to navigate PowerShell effectively.

Similar to the popular Linux terminal, PowerShell offers a robust command-line environment specifically built for Windows. It complements the traditional graphical user interface by providing a powerful alternative for advanced users, particularly system administrators and IT professionals. By learning PowerShell scripting, you'll gain the ability to automate complex tasks, saving significant time and simplifying configurations within the Windows ecosystem. This guide dives deep into this core functionality, empowering you to unlock the full potential of PowerShell.

What is PowerShell Language?
PowerShell Logo

PowerShell is a scripting language developed by Microsoft to automate system administration chores. Unlike traditional programming languages, PowerShell focuses on automating tasks and setups to save IT professionals time.

PowerShell, which is built on the.NET framework, uses cmdlets (akin to functions) to interact with objects. These cmdlets, which frequently contain underlying C# code, improve data manipulation and automation. While knowledge of C# is not required, PowerShell's functionality is tailored to Windows systems, distinguishing it from its Linux cousin, Perl, which serves a similar purpose.

PowerShell Concepts
PowerShell Basics

In this Powershell Tutorial, we’ll learn about important Powershell concepts:

Cmdlets

Cmdlet are build-command written in .net languages like VB or C#. It allows developers to extend the set of cmdlets by loading and write PowerShell snap-ins.

Functions

Functions are commands which is written in the PowerShell language. It can be developed without using other IDE like Visual Studio and devs.

Scripts

Scripts are text files on disk with a .ps1 extension

Applications

Applications are existing windows programs.

What if

Tells the cmdlet not to execute, but to tell you what would happen if the cmdlet were to run.

Confirm

Instruct the cmdlet to prompt before executing the command.

Verbose

Gives a higher level of detail.

Debug

Instructs the cmdlet to provide debugging information.

ErrorAction

Instructs the cmdlet to perform a specific action when an error occurs. Allowed actions continue, stop, silently- continue and inquire.

ErrorVariable

It specifies the variable which holds error information.

OutVariable

Tells the cmdlet to use a specific variable to hold the output information

OutBuffer

Instructs the cmdlet to hold the specific number of objects before calling the next cmdlet in the pipeline.

Windows PowerShell Uses and Features

PowerShell Features

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.

Powershell Features
PowerShell Logo

  • PowerShell Remoting: PowerShell allows scripts and cmdlets to be invoked on a remote machine.
  • Background Jobs: It helps you to invoked script or pipeline asynchronously. You can run your jobs either on the local machine or multiple remotely operated machines.
  • Transactions: Enable cmdlet and allows developers to perform
  • Evening: This command helps you to listen, forwarding, and acting on management and system events.
  • Network File Transfer: Powershell offers native support for prioritized, asynchronous, throttled, transfer of files between machines using the Background Intelligent Transfer Service (BITS) technology.

How to Launch PowerShell

PowerShell is pre-installed in all latest Versions of Windows. To Launch PowerShell we need to follow the given steps:

Step 1) Search for PowerShell in Windows. Select and Click.

To run PowerShell as administrator, right-click on the Windows PowerShell search result, then click ‘Run as administrator’.

PowerShell Launch

Step 2) Power Shell Window Opens

PowerShell Cmdlet

A cmdlet, also known as Command Let, is a lightweight command used in the Windows-based PowerShell environment. PowerShell runs these cmdlets in the command prompt. You can construct and invoke cmdlets commands using PowerShell APIS..

Cmdlet vs. Command

Cmdlets differ from commands in other command-shell systems in the following ways.

  • Commandlets are.NET Framework class objects. It cannot be executed individually.
  • Cmdlets can be created with just a dozen lines of code.
  • Cmdlets do not handle parsing, output formatting, or error presentation.
  • Cmdlets process works with objects. So text streams and objects cannot be given as output for pipelining.
  • Cmdlets are record-based, processing only one item at a time

The vast majority of PowerShell functionality is obtained from Cmdlets, which are always expressed in verb-noun format rather than plural. Furthermore, Cmdlets return objects, not text. A cmdlet is a set of commands that span several lines and are stored in a text file with the extension.ps1. A cmdlet always includes a verb and a noun separated by a hyphen. The following verbs are used to help you grasp PowerShell:

  • Get — To get something
  • Start — To run something
  • Out — To output something
  • Stop — To stop something that is running
  • Set — To define something
  • New — To create something

PowerShell Commands

People love PowerShell because it is, well, powerful. But that power stems from an unbelievable level of intricacy. It is just not realistic or practical for someone to memorize all of the many commands, cmdlets, flags, filters, and other methods of instructing PowerShell.

Fortunately, the editor includes a variety of options to assist you deal with this fact.

Tab Completion

There is no need to memorize every instruction or its exact spelling. Type get-c into the editor and use the TAB key to cycle through all the commands beginning with what you've entered so far. This applies to whatever section of the command you're attempting to execute, including the name (as shown below), as well as the flags and paths that you're altering to achieve your intended result.

Get-Command

While tab completion is useful, what happens when you don't know the name of the command you're looking for? In that situation, you'd use a command that finds other commands: 

Get-Command 

When searching for commands, remember that they have a syntax: VERB-NOUN. Typically, the verbs are Get, Set, Add, Clear, Write, and Read, while the nouns are files, servers, or other elements in your network and apps.

Get-Command is a utility for discovering the commands accessible on your system.

Get-Help: Help about PowerShell commands and topics

Example: Display help information about the command Format-Table

Get-Help Format-Table

Get-Command: Get information about anything that can be invoked

Powershell Script Example: To generate a list of cmdlets, functions installed in your machine

Get-Command

Get-Service: Finds all cmdlets with the word ‘service’ in it.

Example: Get all services that begin with “vm”

Get-Service "vm*"

Get- Member: Show what can be done with an object

Example: Get members of the vm processes.

Get-Service "vm*" | Get-Member

Other Commands:

  • Get Module Shows packages of commands
  • Get Content This cmdlet can take a file and process its contents and do something with it
  • Get- get Finds all cmdlets starting with the word ‘get-

Example: Create a Folder

New-Item -Path 'X:\Guru99' -ItemType Directory

Output:

PowerShell’s Command Syntax

Someone once described the Perl programming language as resembling "executable line noise" - an extremely valuable tool with a wildly obscure syntax and a steep learning curve.

While not nearly so advanced, the typical command prompt in Windows is not far behind. Consider a common task, like as locating all the entries in a directory whose names begin 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;
  • The pathname format letters a, d, f, n, p, s, t, and x were previously utilized by developers, therefore %G is used as the "implicit parameter". Starting with G is conventional because it provides you the largest group 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 result is essentially identical, but even in this relatively simple example, it is much easier to grasp what's going on. It's immediately clear what each part in the command does and how you can change them. The only somewhat less clear thing here is the * wildcard character (included in both samples), which signals that the pattern used to match things should start with 'Foo' and conclude in anything else. 

It only keeps getting better from here. For example, how do you identify only files (not folders) in a path? You might look up the documentation, Google it, and try to figure it out using the command line version, or if you're in PowerShell, type "-" and press the tab key to cycle through the flag possibilities until the obvious solution appears.

One Big String vs Object Properties

Servers provide no purpose unless they are operational. Which is why people spend so much time pretending to be submarine sonar operators and pinging them.

While ping's output is useful (and it can be used within PowerShell), it is ultimately just a long string of letter and number characters with no definite breaks between them.

PowerShell offers a command similar to ping, except it returns structured data, making it easier to work with. The command is Test-Connection.

The results of pinging a server (called 'DC' on their local network) and the corresponding Test-Connection output are shown below.

Leaving aside that it's simpler to understand, what's actually significant is that you can now send this information off to another command, include it into a larger utility (as this entire course is working toward), or simply alter it so that it makes more sense. 

Powershell Data Types

Powershell Data types

Special Variables

Special Variable

Description

$Error

An array of error objects which display the most recent errors

$Host

Display the name of the current hosting application

$Profile

Stores entire path of a user profile for the default shell

$PID

Stores the process identifier

$PSUICulture

It holds the name of the current UI culture.

$NULL

Contains empty or NULL value.

$False

Contains FALSE value

$True

Contains TRUE value

Before Running PowerShell Scripts

PowerShell scripts, such as the ones we will write in this lesson, are saved as.ps1 files. By default, Windows does not allow you to start these scripts simply by double-clicking the file. This is because malicious (or poorly written) scripts have the potential to cause significant unintended system harm.

Instead, to execute a PowerShell script, right-click the.ps1 file and select 'Run with PowerShell'.

If this is your first time working with PowerShell scripts, it may not work. That is because a system-wide policy prohibits 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 begin working with PowerShell scripts, you must alter this policy option. You should modify it to 'RemoteSigned', which you can do immediately from PowerShell by performing the following command:

Set-ExecutionPolicy RemoteSigned

Now You are Ready to Get Started.

How To Run A PowerShell Script

There are two primary approaches to create a PowerShell script:

1.       If you're comfortable with the Windows Command Line, you can write scripts straight in Notepad. For instance, in a fresh notepad file, type "Write-Host "Hello World!"

Then save the file as FirstScript.ps1

To run the script from PowerShell, use the following command: & "X:\FirstScript.ps1" The output will be displayed in PowerShell.

2.      The Windows PowerShell Integrated Scripting Environment (ISE) offers a more powerful approach to create PowerShell scripts. ISE allows you to run scripts and debug them in a graphical interface.

ISE also has syntax highlighting, multiline editing, tab completion, selective execution, and a variety of other capabilities. It even allows you to launch many script windows at the same time, which is useful for scripts that call other scripts.

Working with ISE from the start is worthwhile, even if it appears to be overkill right now. This way, you may become acclimated to it before you begin writing more intricate scripts.

Basic PowerShell Script Examples

Example Script 1: Get The Date

Let us start with a basic script. Open a new file in either ISE or Notepad. Type: Write-Host Get-Date.

Then save the file as GetDate.To run the script using PowerShell, use the following command: & "C:\GetDate.ps1".

You'll see the results in PowerShell.

Example Script 2: Force Stop A Process

You may halt a stalled Windows service using a PowerShell script. For example, imagine my organization utilizes Lync for corporate communications and it keeps freezing; Lync's process ID is 9212. I can stop Lync using a script.


To achieve this, create a new script file in the same manner as before. Type: stop-process 9212 or stop-process -processname lync.

Save the program as StopLync.ps1 and run the script with: & "X:\StopLync.ps1"

This script can be expanded to halt several processes at once simply by adding more commands of the same type. To start many processes at once, use the following script: start-process -processname [your process here].

This is especially useful if you want to start a large number of networking processes at once and do not want to type the commands individually.

Example Script 3: Check if a File Exists

If you need to delete many files, you should first check to verify if they actually exist.

As the name says, test-path allows you to check the existence of path elements. It will return TRUE if all elements are present, and FALSE if any are missing.

Simply type: test-Path (and then the file path).

Example Script 4: Set Up a VPN on a New Machine

Now that you've covered the basics, let's develop a script that actually does something helpful. One of the most significant benefits of PowerShell for sysadmins is the ability to automate the process of configuring new machines.

Individuals and corporations alike now rely on virtual private networks to protect proprietary data. All new machines should be set up with a VPN. While you could do each one manually, PowerShell is ideal for this. For novices, i.e., the majority of people reading this article, most high-quality VPN services will work for your computer environment; we can develop a script to set it up and configure it automatically.

The simplest approach to achieve 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 must configure your server address to the address of your local VPN server, then by using the 'PassThru' command, this script will return the VPN's setup settings.

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

& "X:\SetVPN.ps1"

Now. The first time you run this command, you may encounter some errors. But this is all part of the learning process for PowerShell scripts. Fear not: whenever you see an error like this, simply have a look at Microsoft's official guide for the 'Set-VpnConnection' command and adapt the examples there to suit your system.

Advantages of Using PowerShell Script
PowerShell Logo

  • PowerShell scripts are really powerful and could do much stuff in fewer lines.
  • Variables are declared in the form $<variable>
  • Variables could be used to hold the output of command, objects, and values.
  • “Type” of a variable need not be specified.

PowerShell Punctuation

Here's a table summarizing some of the PowerShell punctuation we've used.

PowerShell Punctuation

Conclusion
PowerShell Logo

PowerShell's strength is in automating duties for system administrators, especially in big network systems. Consider managing hundreds of servers and implementing a security solution that demands a specific service. Manually inspecting each server would be time consuming and error-prone.

PowerShell excels in this situation. With a single script, you can automate the entire procedure, obtaining information on running services on all servers in minutes. This relieves IT professionals of repetitive activities, allowing them to focus on more strategic objectives.

This beginner's guide will provide you with the necessary knowledge to get started with PowerShell scripting. Once you understand the fundamental syntax, script development becomes more manageable. Remember to neatly organize and name your scripts for future reference. Practice is essential for mastering PowerShell. Embrace its powers, investigate its features, and try with various instructions to improve your skills. With dedication and patience, you may use PowerShell to streamline activities and increase efficiency in your daily operations. Begin your quest to become expert in Windows PowerShell today!

Stay Informed, Stay Safe!