Basic PowerShell Commands for Beginners 2023

PowerShell is a powerful shell interface and scripting language built on top of the .NET framework. It provides system administrators and power users with a vastly improved command-line environment compared to old command shells like cmd.exe.

In this comprehensive guide, you’ll learn foundational PowerShell commands for managing the filesystem, running programs, manipulating strings, managing processes, and more as a beginner.

Why Learn PowerShell Commands?

Here are some of the key benefits of mastering basic PowerShell commands:

  • Productivity – Automate repetitive tasks with one-liners and scripts.
  • Control – Fine-tune system settings and policies with precision.
  • Versatility – Manage components ranging from the registry to Azure services.
  • Accessibility – Interact directly with .NET classes and APIs.
  • Portability – Run on Windows, macOS, and Linux with PowerShell Core.

Whether you manage servers, workstations, networks, or scripts, knowing fundamental PS commands is a must for Windows administrators.

Getting Started with PowerShell

PowerShell is installed by default on Windows 10 and Windows Server 2019. For older Windows versions, install the Windows Management Framework to get PowerShell.

To launch PowerShell:

  • Search for “PowerShell” in the Windows start menu and click on “Windows PowerShell”
  • Or launch the “PowerShell” app directly
  • You can also right-click the Start menu and select “Windows PowerShell”

This will open the PowerShell command prompt where you can start entering commands:

Now let’s dive into the most important PowerShell commands every beginner should know.

PowerShell Help System

The built-in Get-Help command provides you access to PowerShell’s documentation system. Whenever you need help remembering syntax or behavior for a particular command or module, Get-Help is the fastest way to find it.

For example, to view help for the Get-ChildItem command:

Get-Help Get-ChildItem

You can also access help for a cmdlet by using its built-in alias. For Get-ChildItem the alias is gci:

Get-Help gci

Common parameters for Get-Help include:

  • -Full: Show all help content for the command
  • -Online: Open the online help page
  • -Examples: Just show usage examples
  • -Detailed: Show full parameter help and technical details

For more help content, check out the full Get-Help documentation.

Filesystem Management

Now let’s go over the most important filesystem management commands for creating, modifying, and navigating files and folders in PowerShell.

Get-ChildItem (gci)

The Get-ChildItem cmdlet lists all child items inside a directory, returning a FileInfo or DirectoryInfo object for each item. This allows you to inspect attributes of files and folders.

To list all items in the current directory:

Get-ChildItem

# Or using the gci alias:

gci

You can pass a path to list items elsewhere:

Get-ChildItem C:\Users\MyUser

Use parameters like -File and -Directory to only return specific types of child items:

# Only show directories
Get-ChildItem C:\ -Directory 

# Only show files
Get-ChildItem C:\ -File

The most common aliases for Get-ChildItem are gci and ls, similar to the Linux ls command.

Set-Location (cd)

To navigate around the filesystem in PowerShell, use the Set-Location and Push-Location cmdlets.

Set-Location changes the current working directory, mimicking the behavior of cd in cmd.exe:

Set-Location C:\Windows\System32

# Shorthand alias
cd C:\Windows\System32

Push-Location lets you store a directory on a stack so you can easily return to it later:

Push-Location C:\Windows 

# Do some stuff

Pop-Location # To return to original directory

New-Item (ni)

The New-Item cmdlet creates a new file or directory. To create a new folder:

New-Item -Path .\NewFolder -ItemType Directory

# Shorthand
ni .\NewFolder -Type Directory

And to create a new file:

New-Item -Path .\NewFile.txt -ItemType File

ni .\NewFile.txt -Type File

The default ItemType is -File, so you can omit it when creating new files.

Rename-Item (rni)

To change an item’s name or path, use Rename-Item:

Rename-Item -Path .\File.txt -NewName Important.txt 

# Alias
rni .\File.txt Important.txt

Copy-Item (cp)

The Copy-Item cmdlet copies files or directories to a new destination:

Copy-Item -Path .\File.txt -Destination .\Folder\File.txt

cp .\File.txt .\Folder\File.txt

To copy a folder recursively, use the -Recurse switch:

Copy-Item -Path .\Folder -Destination .\FolderBackup -Recurse

Remove-Item (ri)

Remove-Item deletes files and folders:

Remove-Item -Path .\BadFolder

ri .\BadFile.txt

Add -Recurse to recursively delete folders:

Remove-Item -Path .\NestedFolder -Recurse

And use extreme caution when combining with wildcards like * to avoid accidentally deleting everything!

Get-Content

To display the contents of a text file in PowerShell, use Get-Content:

Get-Content -Path .\Readme.txt

It will output the full contents of the file to the console.

You can also save the output to a variable to manipulate it:

$contents = Get-Content -Path .\Readme.txt

Set-Content

Set-Content writes string data to a new or existing text file, overwriting any existing content:

Set-Content -Path .\Output.txt -Value "This is the content" 

# Append data with -Append
Set-Content -Path .\Output.txt -Value "This is additional content" -Append

Running Programs

Now let’s look at how to run programs and scripts with PowerShell.

Start-Process

The Start-Process cmdlet runs an executable file. For example, to open the Windows calc.exe app:

Start-Process -FilePath calc.exe

You can also launch PowerShell scripts by specifying -FilePath:

Start-Process -FilePath .\MyScript.ps1

And open websites in the default browser with -Uri:

Start-Process -Uri https://www.google.com

Stop-Process

To stop a running process, use Stop-Process and pass the PID (process ID):

# Get PID
Get-Process notepad

# Stop process
Stop-Process -Id 4448

Adding -Force will forcibly kill the process immediately.

Wait-Process

The Wait-Process cmdlet pauses PowerShell execution until the specified process finishes.

For example, to run a script and wait for it to complete:

Start-Process -FilePath .\MyScript.ps1 

Wait-Process -Id $PID

"Script finished"

Now PowerShell will wait rather than immediately proceeding.

Managing Services

Services are background processes that run independently of any particular user. Here are some key commands for managing Windows services:

Get-Service

The Get-Service cmdlet retrieves info about installed services on the system. To see all services:

Get-Service

Pass a service name to view info about a specific service:

Get-Service -Name winlogon

Start-Service

Start-Service starts a stopped service:

Start-Service -Name wuauserv

Stop-Service

Stop-Service stops a currently running service:

Stop-Service -Name BITS

Restart-Service

To restart a service:

Restart-Service -Name w32time

This stops and restarts the service.

Managing Processes

Process management is critical for monitoring system health and troubleshooting performance. Here are some key commands for managing processes:

Get-Process

The most important process management cmdlet is Get-Process. It retrieves detailed information about active processes running on the local system.

To view all processes:

Get-Process

Pass a process name to filter the results:

Get-Process -Name explorer

You can store results in a variable to inspect specific properties like the ID:

$explorer = Get-Process -Name explorer
$explorer.Id

Stop-Process

As shown earlier, Stop-Process terminates a running process using its PID:

Get-Process -Name firefox

Stop-Process -Id 17712

Start-Process

We already covered using Start-Process to launch new processes. This includes starting GUI apps like calc.exe, CLI tools like ping.exe, and PowerShell scripts.

Wait-Process

Wait-Process pauses PowerShell execution until the process specified by ID or name finishes. This is useful in scripts that call other programs.

Working with the Registry

The Windows registry serves as a central hierarchical database for system settings. Here are some key PowerShell commands for querying and editing the registry:

Get-ChildItem

You can use Get-ChildItem to list items under registry paths like other filesystem locations.

For example, to show subkeys under the HKEY_CURRENT_USER\Software key:

Get-ChildItem -Path HKCU:\Software

Get-ItemProperty

The Get-ItemProperty cmdlet retrieves the value of a registry key property:

Get-ItemProperty -Path HKCU:\Console -Name ColorTable05

You can pass the result to Select-Object -ExpandProperty to extract just the property value:

Get-ItemProperty -Path HKCU:\Console -Name ColorTable05 | Select-Object -ExpandProperty ColorTable05

Set-ItemProperty

To change the value of a registry property, use Set-ItemProperty:

Set-ItemProperty -Path HKCU:\Console -Name ColorTable05 -Value 5

New-ItemProperty

The New-ItemProperty cmdlet creates a new registry property and value:

New-ItemProperty -Path HKCU:\Software\MyApp -Name Enabled -Value 1 -PropertyType DWORD

Common property types include Binary, Dword, String, and MultiString.

Remove-ItemProperty

To delete a registry value, use Remove-ItemProperty:

Remove-ItemProperty -Path HKCU:\Software\MyApp -Name Enabled

This completely deletes the property and value.

String Manipulation

Strings are a core component of PowerShell scripting. Here are some key string manipulation commands:

-split

The -split operator splits a string into an array based on a delimiter:

$servers = "server1,server2,server3"
$servers -split ','

This returns server1, server2, and server3 as an array.

-join

The -join operator concatenates array elements into a single string:

$servers = "server1","server2","server3"
$servers -join ","

Outputs:

server1,server2,server3

Substring

The .Substring() method extracts parts of a string. To get the first 5 characters:

"Hello World".Substring(0,5)

Trim(), TrimStart(), TrimEnd()

Trim() removes leading and trailing whitespace:

" Hello ".Trim()

Format Strings

PowerShell uses the -f operator for C-style formatted strings:

"Hello {0} {1}" -f "John", "Doe"

Parameters are passed in order to replace placeholders {0}, {1}, etc.

Simple Logic and Loops

Logic and looping constructs are essential to scripting. Here are some basic examples.

If/Else

The if statement checks a condition:

$age = 20

if ($age -ge 21) {
  Write-Output "Can drink" 
} else {
  Write-Output "Cannot drink"
}

The trailing {} block allows multiple lines.

Switches

The switch statement checks multiple conditions:

$color = "Blue"

switch ($color) {
  "Red" { "Apple" }
  "Yellow" { "Banana" } 
  "Blue" { "Blueberry" }
  default { "No matching fruit" }
}

Each case is tested and the matching block is executed.

For Loops

for loops iterate over a set of items:

for ($i = 0; $i -le 10; $i++) {
  Write-Output $i
}

This counts from 0 to 10.

Foreach Loops

foreach loops iterate over elements of an array:

$files = Get-ChildItem

foreach ($file in $files) {
  Write-Output $file.Name
}

This prints the name of each file.

While Loops

A while loop executes a block while a condition is true:

while ($i -ne 10) {
  # Do something
  $i++
}

The block continues looping until $i equals 10.

Interacting with APIs

A major advantage of PowerShell is easy access to web APIs and online services using .NET classes.

Invoke-RestMethod

The Invoke-RestMethod cmdlet sends HTTP requests to web APIs and gets structured responses.

For example, to get JSON data from the GitHub API:

$response = Invoke-RestMethod https://api.github.com/repos/microsoft/PowerShell/issues

Now you can work with the $response variable containing the API response data.

Invoke-WebRequest

To simply download web content like HTML or images, use Invoke-WebRequest:

$response = Invoke-WebRequest https://www.microsoft.com
$response.Content

This downloads and stores the full HTML content from a webpage.

ConvertFrom-Json

When working with JSON APIs, use ConvertFrom-Json to convert a JSON string into a PowerShell object:

$json = '{"name":"John", "age":30}'
$data = ConvertFrom-Json $json

Now you can access properties like $data.name and $data.age on the object.

Creating Reusable Tools with Functions

Functions allow you to encapsulate and reuse logic in PowerShell.

Here is simple syntax for defining a function:

function PrintHello {
  param( 
    $Name
  )

  Write-Output "Hello $Name!"
}

Now you can call this function repeatedly:

PrintHello "John"
PrintHello "Sarah"

The param() block declares parameters you can pass to the function.

Parameters can have:

  • Data types like [int] or [datetime]
  • Default values
  • Validation logic

Function names should use PascalCase instead of lowercase.

Getting Help

This covers foundational PowerShell commands frequently used by administrators and power users on Windows. The key is learning to check Get-Help whenever you need to look up syntax and usage examples.

Here is more content continuing from where I left off:

Using Objects in PowerShell

PowerShell is built on top of the .NET framework, which means many commands return objects instead of plain text. This allows richer interactions via object properties and methods.

For example, Get-Process returns System.Diagnostics.Process objects:

$proc = Get-Process powershell
$proc.Handles # Access a property
$proc.Kill() # Call a method

And Get-Service returns System.ServiceProcess.ServiceController objects:

$svc = Get-Service winmgmt
$svc.Status
$svc.Start()

To discover available properties and methods on an object, pipe it to Get-Member:

Get-Service | Get-Member

You can access properties using dot syntax like $object.Property or hash table syntax like $object.'Property'.

Methods are called using $object.Method() syntax. This emphasizes the object-based nature of PowerShell.

Using the Pipeline

Piping objects between commands is a key distinguishing feature of PowerShell.

The pipeline passes output from one command as input to another command:

Get-Process | Where-Object CPU -gt 50 | Sort-Object CPU

Here Get-Process outputs process objects which are filtered by Where-Object and then sorted by Sort-Object.

This works because the cmdlets accept and output objects, not just text.

Some common pipeline commands include:

  • Where-Object – Filter objects
  • Sort-Object – Sort objects
  • Select-Object – Select object properties
  • Measure-Object – Calculate stats
  • Compare-Object – Compare object differences

Using PowerShell Modules

Commands are organized into modules which must be imported before use.

To view available modules:

Get-Module -ListAvailable

Import a module:

Import-Module NetSecurity

Now you can use commands from that module like Get-NetFirewallRule.

Module autoloading finds and loads modules before cmdlets automatically. But explicitly importing is better practice.

Install modules from the PowerShell Gallery with Install-Module.

Creating Custom Modules

You can organize your own reusable PowerShell code as custom modules.

A module is any PowerShell script (.ps1) or binary module (.dll) stored in a Modules subfolder.

For example:

C:\CustomModules\
  MyModule.psm1
  MyModule.ps1

The .psm1 or .psd1 extension creates a module manifest describing metadata like name, version, and commands.

Once imported, cmdlets defined in MyModule.psm1 are available in the session:

Import-Module C:\CustomModules\MyModule.psm1

This allows sharing common functions across scripts and solutions.

Distributing Code with Scripts

PowerShell code is typically distributed as .ps1 script files.

To run a script, call it from within PowerShell or use the Start-Process cmdlet:

.\MyScript.ps1

Start-Process ".\MyScript.ps1"

This runs the script on the remote computer and returns any output.

Use parameters and functions to make PowerShell scripts modular and reusable across environments. Store them in source control like Git to maintain version history.

Improving Cross-Platform Compatibility

PowerShell Core runs on Windows, macOS, and Linux for greater cross-platform compatibility.

Some key areas to improve POSIX/Linux compatibility include:

  • Using / instead of \ for filesystem paths
  • Avoiding Windows-specific aliases like ls or cat
  • Testing code on Linux/macOS with PowerShell Core
  • Installing modules from the PowerShell Gallery
  • Using open source libraries and cmdlets

Focus on .NET Core and C# where possible for maximum code reuse across platforms.

Digging Deeper with Advanced Functions

PowerShell’s advanced functions unlock more complex logic and capabilities.

These include:

  • Parameter validation and error handling with ParameterSetName
  • Dynamic parameter generation with DynamicParam
  • Pipeline input via BeginProcess, and End blocks
  • Asynchronous parallel execution with Workflow
  • Script cmdlets using compiled C# code via CmdletBinding

For example:

function Test-Parameter {
    
  [CmdletBinding()]
  param (
    
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()] 
    [string]$Name
  
  )
    
  begin {}
  process {
    Write-Output "Validated input: $Name" 
  }
  end {}

}

This implements cmdlet-style parameters with validation.

Explore about_functions_advanced for more on advanced functions.

Summary

This comprehensive guide covered over 70 fundamental PowerShell commands for system administration and scripting.

Here are some of the key topics:

  • PowerShell help system (Get-Help)
  • Filesystem and registry management
  • Working with processes, services, and programs
  • Strings, objects, pipelines
  • Logic, loops, functions
  • APIs, web requests
  • Modules, scripts, cross-platform

These building blocks will prepare any Windows admin or developer to start leveraging PowerShell daily.

The depth of PowerShell is difficult to cover fully in a single guide. Check the Microsoft Docs and YouTube for more detailed video tutorials on specific commands and advanced topics.

With regular practice and referencing documentation, PowerShell will become second nature for automating and DevOps on Windows platforms.

Leave a Comment