PowerShell Uncovered: A Beginners Guide to Scripting Mastery

📚 Table of Contents

  1. 💡 Unmasking PowerShell
  2. 🔑 Your First Step: Opening PowerShell
  3. 🧭 Navigating the Terrain: Interface Exploration
  4. 🥊 Basic Moves: Executing Simple Commands
  5. 🧱 Building Blocks: Scripting
  6. 🛡️ Adjusting Script Execution Policy
  7. 📦 Storage Boxes: Variables
  8. 🛠️ Power Tools: Functions
  9. 📚 Further Exploration: More Useful Cmdlets

💡 Unmasking PowerShell

PowerShell isn’t just another command-line shell. It’s a scripting superhero, born and bred by Microsoft. Its journey started in 2006, making Windows administration easier, but it has grown beyond its roots and become a cross-platform marvel, empowering admins on macOS and Linux as well.

Riding on the powerful .NET Framework, it can manipulate a vast array of system and application features. Whether you’re automating tasks, managing systems, or performing administrative feats, PowerShell is your go-to tool.

In this guide, we’ll start with the basics - opening the shell, exploring the interface, and executing your first commands. Then we’ll delve deeper into scripting, variables, and functions. This guide is suitable for novices, but also packs in advanced topics for the experienced users.

🔑 Your First Step: Opening PowerShell

For Windows users:

  1. Press the Windows key or click the Start button.
  2. Type “PowerShell” in the search bar.
  3. Click on “Windows PowerShell” in the search results.

For macOS and Linux users, you can install PowerShell by following the instructions on the official PowerShell GitHub repository.

🧭 Navigating the Terrain: Interface Exploration

When you first open PowerShell, you’ll see a command prompt displaying your current user and system information. It typically looks something like this:

PS C:UsersYourUsername>

To navigate the file system, you can use the following commands:

  • cd <directory>: Change the current directory to the specified directory.
  • dir or ls: List the contents of the current directory.
  • mkdir <directory>: Create a new directory with the specified name.
  • rmdir <directory>: Remove the specified directory.

🥊 Basic Moves: Executing Simple Commands

PowerShell employs “cmdlets” (pronounced “command-lets”) to perform tasks. Cmdlets follow a Verb-Noun format, such as Get-ChildItem or Set-Location.

Here are some basic cmdlets to help you start:

  • Get-ChildItem: List the contents of the current directory.
  • Set-Location <directory>: Change the current directory to the specified directory.
  • Get-Content <file>: Display the contents of the specified file.
  • Copy-Item <source> <destination>: Copy a file or directory from the source to the destination.
  • Remove-Item <item>: Delete the specified file or directory.

Pro Tip: Need help with a cmdlet? Use the Get-Help cmdlet followed by the cmdlet name:

PS C:UsersYourUsername> Get-Help Get-ChildItem

The output provides a description of the cmdlet, the syntax, aliases, and other useful information:

PS C:UsersYourUsername> Get-Help Get-ChildItem
Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint32>] [-Force] [-Name] [-UseTransaction] [-Attributes {ReadOnly | Hidden |
System | Directory | Archive | Device | Normal | Temporary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted | IntegrityStream | NoScrubData}] [-FollowSymlink]
[-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>]
Get-ChildItem [[-Filter] <string>] -LiteralPath <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint32>] [-Force] [-Name] [-UseTransaction] [-Attributes {ReadOnly | Hidden |
System | Directory | Archive | Device | Normal | Temporary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted | IntegrityStream | NoScrubData}] [-FollowSymlink]
[-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>]
Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
-- To download and install Help files for the module that includes this cmdlet, use Update-Help.
-- To view the Help topic for this cmdlet online, type: "Get-Help Get-ChildItem -Online" or
go to https://go.microsoft.com/fwlink/?LinkID=113308.

🧱 Building Blocks: Scripting

PowerShell scripts are files with a .ps1 extension that contain a series of cmdlets and other PowerShell code. To create a script, open a text editor, write your code, and save the file with a .ps1 extension.

For example, create a file called hello-world.ps1 with the following content:

Write-Host "Hello, World!"

In the image below, I’ve created a file called hello-world.ps1, opened it in notepad and saved “Write-Host “Hello, World!” in the file.

Hello World

To run the script, navigate to the directory containing the script and execute the following command:

PS C:UsersYourUsername>.\hello-world.ps1

Hellow World Script Output

🛡️ Adjusting Script Execution Policy

By default, PowerShell has a security measure in place known as the “execution policy” that controls how scripts are run. The default policy, “Restricted”, does not allow scripts to run.

To view the current execution policy, use this command:

C:UsersYourUsername> Get-ExecutionPolicy

If you need to run scripts from sources you trust, you might need to change this policy. However, be aware of the security implications. The “Unrestricted” policy allows all scripts to run, which can be dangerous if you’re not certain the scripts are safe.

To set the execution policy to “Unrestricted”, use this command:

C:UsersYourUsername> Set-ExecutionPolicy Unrestricted

This command will prompt you for confirmation before changing the policy. If you’re sure you want to proceed, type Y and press Enter.

Remember to only run scripts that you trust. When you’re done running scripts, consider setting the execution policy back to a safer level. This can be done with the Set-ExecutionPolicy command as well, replacing Unrestricted with the desired level, for example, Restricted or RemoteSigned.

📦 Storage Boxes: Variables

Variables in PowerShell are containers for storing data, identified with a $ symbol. Here’s how to create a variable:

PS C:UsersYourUsername> $variableName = "value"

For instance, to create a variable called greeting with the value “Hello, World!”, use the following code:

PS C:UsersYourUsername> $greeting = "Hello, World!"
PS C:UsersYourUsername> Write-Host $greeting
# Result
"Hello, World!"

🛠️ Power Tools: Functions

Functions in PowerShell are the tools of your scripting toolbox - reusable blocks of code that can be called with a specific name. Here’s the basic syntax for creating a function:

function FunctionName {
# Your code here

For example, create a function called PrintGreeting that prints “Hello, World!“:

function PrintGreeting {
Write-Host "Hello, World!"
# Result
'Hello, World!'

You can also pass parameters to functions using the param keyword:

function PrintGreetingWithName {
Write-Host "Hello, $name!"
PrintGreetingWithName -name "John"
# Result
'Hello, John!'

📚 Further Exploration: More Useful Cmdlets

  • Get-Command: Retrieve a list of all available cmdlets and functions.
  • Get-Process: Get a list of running processes on the system.
  • Stop-Process: Terminate a running process.
  • Get-Service: Get a list of installed services on the system.
  • Start-Service: Start a stopped service.
  • Stop-Service: Stop a running service.
  • Restart-Service: Restart a running service.
  • New-Item: Create a new file or directory.
  • Rename-Item: Rename a file or directory.
  • Move-Item: Move a file or directory to a new location.
  • Get-Date: Display the current date and time.
  • Set-Date: Set the system date and time.
  • Get-History: Get a list of previously executed commands.
  • Clear-History: Clear the command history.
  • Invoke-WebRequest: Send an HTTP or HTTPS request to a web page and parse the response.
  • ConvertTo-Json: Convert an object to a JSON-formatted string.
  • ConvertFrom-Json: Convert a JSON-formatted string to a custom object.
  • Export-Csv: Export data as a comma-separated values (CSV) file.
  • Import-Csv: Import data from a CSV file.
  • Select-Object: Select specific properties from an object or set of objects.
  • Where-Object: Filter objects based on a specific condition.
  • ForEach-Object: Perform an action on each item in a collection.
  • Sort-Object: Sort objects by property values.
  • Measure-Object: Calculate the numeric properties of objects.

Congratulations Fellow Nomad!

You’ve just taken your first steps into the fascinating world of PowerShell scripting. With this foundation, you can go on to automate tasks, manage systems, and make your daily computer life significantly easier. Remember, practice makes perfect, so don’t be afraid to experiment, explore, and build your scripting prowess. The sky is the limit!