PowerShell Script Examples [Top 75]

Are you looking at some PowerShell examples? In this tutorial, I have listed 75 PowerShell script examples. These PowerShell scripting examples will help you to start with Microsoft PowerShell.

You can execute these PowerShell script examples using Visual Studio code if you are new to PowerShell.

Table of Contents

PowerShell script example

Here is the list of 75 PowerShell script examples.

1. Checking Your PowerShell Version

Before you begin, knowing which version of PowerShell you’re running is important. The $PSVersionTable.PSVersion command, displays the major, minor, build, and revision numbers of your PowerShell environment.

$PSVersionTable.PSVersion

2. Getting Help

PowerShell provides a built-in help system. Get-Help followed by a cmdlet name, such as Get-Help Get-Process, will show you detailed information about the cmdlet’s usage, parameters, examples, and more. It’s an essential command for learning and troubleshooting.

Get-Help Get-Process

3. Listing All Commands

Get-Command List all cmdlets, functions, scripts, and aliases in your session. It’s useful for discovering the commands you can use for various tasks.

Get-Command

4. Setting Execution Policy

PowerShell’s execution policy determines which scripts can run on your system. Set-ExecutionPolicy RemoteSigned allows you to run scripts that you’ve created and scripts from trusted sources.

Set-ExecutionPolicy RemoteSigned

5. Getting System Services

Get-Service cmdlet lists all the services installed on your system, along with their statuses (Running, Stopped, etc.). This is useful for monitoring and managing the services that your system relies on. To list all services on your system, use:

Get-Service

6. Converting Output to HTML

The ConvertTo-Html cmdlet converts the output of a command into an HTML formatted table. This is useful for creating reports or web content from your PowerShell data. Convert the output of a command to HTML format with:

Get-Process | ConvertTo-Html | Out-File process.html

7. Exporting to CSV

Export-Csv cmdlet takes the output of a command and exports it to a CSV file. This is particularly useful for data analysis and sharing since CSV files can be easily opened in spreadsheet software like Microsoft Excel. To export data to a CSV file in PowerShell, use:

Get-Process | Export-Csv -Path processes.csv

8. Sorting Objects

Sort-Object cmdlet in PowerShell sorts objects by property values. You can sort information like process names, file sizes, or dates to organize your data more effectively. Sort the output of a command by a specific property:

Get-Process | Sort-Object -Property CPU

9. Filtering with Where-Object

Where-Object cmdlet filters objects based on specified criteria. It allows you to retrieve only the items that match certain conditions, such as processes using more than a certain amount of CPU. Filter the results of a command using Where-Object in PowerShell.

Get-Process | Where-Object { $_.CPU -gt 10 }

10. Fetching Event Logs

Get-EventLog cmdlet retrieves event log entries. This can be used to analyze system events, application errors, security logs, and more. Retrieve event logs with the below PowerShell command:

Get-EventLog -LogName Application -Newest 50

11. Stopping a Process

Stop-Process cmdlet stops one or more running processes. The -Force parameter ensures that the process is stopped even if it’s not responding. To stop a process, use the below PowerShell command:

Stop-Process -Name notepad -Force

12. Starting a Process

Start-Process cmdlet initiates a process on the local computer, such as opening an application or running a script. To start a process like Notepad, use the PowerShell command below.

Start-Process notepad.exe

13. Getting Process Information

Select-Object cmdlet selects specific properties of objects, allowing you to customize the information you retrieve about processes or other data types. To get detailed information about processes, use the below PowerShell command.

Get-Process | Select-Object Name,ID,CPU

14. Creating a New Directory

New-Item cmdlet creates new items, such as files or directories. Specifying -ItemType Directory creates a new folder at the specified path. Create a new folder with the below PowerShell cmdlets.

New-Item -Path 'C:\NewFolder' -ItemType Directory

15. Copying Files

Copy-Item cmdlet copies a file or folder from one location to another in PowerShell. It’s a basic but essential task for file management. Copy a file from one location to another with:

Copy-Item -Path C:\file.txt -Destination C:\backup\file.txt

16. Deleting Files

Remove-Item cmdlet deletes files or folders. It’s a straightforward way to clean up your file system. To delete a file, use the below PowerShell command:

Remove-Item -Path C:\file.txt

17. Moving Files

Move-Item cmdlet moves a file or folder to a new location. This is useful for organizing files and directories on your system. Move a file to a new location with the below PowerShell command.

Move-Item -Path C:\file.txt -Destination C:\backup\file.txt

18. Renaming Files

Rename-Item cmdlet changes the name of an existing item, such as a file or folder, to a new name. Use the PowerShell code to rename a file:

Rename-Item -Path C:\file.txt -NewName file_new.txt

19. Reading File Content

Get-Content cmdlet reads the content of a file and displays it in the PowerShell console. This is handy for quickly viewing text files without opening them in an editor. Read the content of a text file with the below PowerShell script example.

Get-Content -Path C:\file.txt

20. Writing to Files

Out-File cmdlet writes output to a file. You can use it to save data generated by your scripts. Write content to a file using the below PowerShell code:

"New content" | Out-File -FilePath C:\file.txt

21. Appending to Files

Add-Content cmdlet adds content to the end of a file without overwriting the existing content. It’s useful for logging and data accumulation. Append content to an existing file with:

"Additional content" | Add-Content -Path C:\file.txt

22. Getting the Current Date and Time

To retrieve the current date and time, you can use the Get-Date cmdlet. This is useful for timestamping, logging, or starting a time-based operation.

$currentDate = Get-Date
Write-Host "The current date and time is: $currentDate"

This script will display the current date and time in the console.

See also  PowerShell Reference Variable

23. Formatting Dates

You can format the date and time in a specific way using the -Format parameter with the Get-Date cmdlet. This is particularly useful when you need to display or log dates in a certain format.

$formattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "The formatted date and time is: $formattedDate"

This script will display the date and time in a format commonly used for logs or file names.

24. Comparing Dates

Comparing two dates is a common task in scripting. You can compare dates to find out which is earlier or later, or if two dates are the same.

$date1 = Get-Date "2023-01-01"
$date2 = Get-Date "2023-12-31"

if ($date1 -lt $date2) {
    Write-Host "$date1 is earlier than $date2"
} else {
    Write-Host "$date1 is the same as or later than $date2"
}

This script compares two dates and outputs which one is earlier.

25. Calculating Date Differences

To calculate the difference between two dates, you can subtract one from the other. This can help determine time spans, such as the number of days until a certain event. Below are the PowerShell programs.

$startDate = Get-Date "2023-01-01"
$endDate = Get-Date "2023-12-31"
$timeSpan = $endDate - $startDate
Write-Host "The difference is: $($timeSpan.Days) days"

This script calculates the number of days between two dates and displays the result.

26. Adding or Subtracting Time from a Date

PowerShell allows you to easily add or subtract time from a date using the AddDaysAddHoursAddMinutes, and similar methods available on date objects.

$originalDate = Get-Date
$futureDate = $originalDate.AddDays(30)
$pastDate = $originalDate.AddDays(-30)

Write-Host "30 days from now: $futureDate"
Write-Host "30 days ago: $pastDate"

This script shows how to calculate dates 30 days in the future and 30 days in the past from the current date.

27. Basic For Loop

for loop repeats a block of code a set number of times. Here is a simple PowerShell loop example.

for ($i = 0; $i -lt 5; $i++) {
    Write-Host "Iteration number: $i"
}

This loop will print the iteration number five times, from 0 to 4.

28. ForEach Loop Through a Collection

The foreach loop iterates through each item in a collection, such as an array. Here is a PowerShell script example.

$names = @('Alice', 'Bob', 'Charlie')
foreach ($name in $names) {
    Write-Host "Hello, $name!"
}

This loop will greet each person in the $names array.

29. While Loop

while loop continues to execute as long as the specified condition is true. Below is an example of a PowerShell script.

$count = 1
while ($count -le 5) {
    Write-Host "Count is: $count"
    $count++
}

This loop will print the value of $count until it is greater than 5.

30. Do-While Loop

The do-while loop executes the code block at least once, and then repeats the loop as long as the condition is true.

$count = 1
do {
    Write-Host "Count is: $count"
    $count++
} while ($count -le 5)

This loop behaves like the while loop, but ensures the code inside the loop runs at least once.

31. Do-Until Loop

The do-until loop is similar to do-while, but it continues until the condition becomes true. Below is the PowerShell example.

$count = 6
do {
    Write-Host "Count is: $count"
    $count++
} until ($count -gt 10)

This loop will run until $count is greater than 10.

See also  How To Split Comma Separated String To Array In PowerShell?

32. Infinite Loop

An infinite loop runs continuously until it’s stopped manually or by a break statement. Here is an example PowerShell script.

while ($true) {
    Write-Host "Press CTRL+C to stop."
    Start-Sleep -Seconds 2
}

This loop will run forever, printing a message every 2 seconds.

33. Looping with Break

The break statement exits a loop immediately, regardless of the loop’s condition in PowerShell.

$numbers = 1..10
foreach ($number in $numbers) {
    if ($number -eq 5) {
        Write-Host "Breaking out of the loop at number: $number"
        break
    }
    Write-Host "Number: $number"
}

This loop will stop once it reaches the number 5.

34. Looping with Continue

The continue statement skips the rest of the loop block and starts the next iteration.

$numbers = 1..10
foreach ($number in $numbers) {
    if ($number % 2 -eq 0) {
        continue
    }
    Write-Host "Odd Number: $number"
}

This loop will print only the odd numbers, skipping even numbers due to the continue statement.

35. Testing Network Connection

Test-NetConnection cmdlet performs a network connectivity test to a specified remote destination, providing details about the path and quality of the connection. Check the network connection to a host:

Test-NetConnection -ComputerName google.com

36. Getting IP Configuration

Get-NetIPConfiguration cmdlet retrieves IP configuration information, including IP address, DNS servers, and gateway for all network adapters. Retrieve IP configuration details with the below useful PowerShell scripts.

Get-NetIPConfiguration

37. Finding Large Files

Combining Get-ChildItem with Where-Object, you can search for files over a certain size, which helps in disk cleanup and management. Find files larger than a specific size:

Get-ChildItem -Path C:\ -Recurse | Where-Object { $_.Length -gt 1GB }

38. Getting Disk Space

Get-PSDrive cmdlet retrieves information about drives on your system, including used and available space. Check the available disk space:

Get-PSDrive -PSProvider FileSystem

39. Sending Email

Send-MailMessage cmdlet allows you to send emails from within PowerShell, automating email notifications and alerts. Send an email using PowerShell:

Send-MailMessage -From 'you@example.com' -To 'someone@example.com' -Subject 'Test email' -Body 'This is a test email' -SmtpServer 'smtp.example.com'

40. Downloading Files from the Internet

Invoke-WebRequest cmdlet can download files from the internet to your local drive, useful for automated downloads and updates. Download a file from the web by using the PowerShell code:

Invoke-WebRequest -Uri http://example.com/file.zip -OutFile C:\file.zip

41. Creating a ZIP Archive

Compress-Archive cmdlet creates a new zip file containing specified files or folders, which is great for data compression and archiving. Create a compressed zip file using the below PowerShell command:

Compress-Archive -Path C:\folder -DestinationPath C:\archive.zip

42. Extracting ZIP Files

Expand-Archive cmdlet extracts files from a zip archive to a specified destination, allowing you to decompress files easily. Extract a zip file with the below PowerShell script example.

Expand-Archive -Path C:\archive.zip -DestinationPath C:\folder

43. Listing Installed Programs

By querying the Windows registry using Get-ItemProperty, you can list installed programs on a Windows system. By using the below PowerShell example, you can get a list of installed programs on Windows:

Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate

44. Changing Directory

Set-Location cmdlet changes the current working directory to a specified path, similar to the cd command in other shells. To change the current directory to another directory in PowerShell use the below cmdlet:

Set-Location -Path C:\NewFolder

45. Listing Directory Contents

Get-ChildItem cmdlet lists the items in a directory, including files and subdirectories. List all items in the current directory using the below PowerShell examples.

Get-ChildItem

46. Creating a New File

New-Item can also create files, not just directories. Specifying -ItemType File creates a new file at the given path. Create a new text file using the below PowerShell script:

New-Item -Path 'C:\NewTextFile.txt' -ItemType File

47. Monitoring System Performance

Get-Counter cmdlet retrieves performance counter data, such as CPU and memory usage, which can be used for monitoring and troubleshooting. Monitor CPU and memory usage:

Get-Counter -Counter "\Processor(_Total)\% Processor Time", "\Memory\Available MBytes"

48. Finding System Uptime

This script calculates how long the system has been running by subtracting the last boot-up time from the current date and time. Find out how long the system has been running:

(Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime

49. Listing Environment Variables

Get-ChildItem Env: lists all current environment variables, which can be important for understanding the context in which programs run. List all environment variables using PowerShell script:

Get-ChildItem Env:

50. Adding Environment Variables

Using the $env: scope, you can create or modify environment variables within your PowerShell session. Add a new environment variable using PowerShell, execute:

$env:MyVariable = "MyValue"

51. Removing Environment Variables

RRemove-Item can also be used to delete environment variables by specifying the Env: scope. Remove an environment variable:

Remove-Item Env:MyVariable

52. Running a Remote Command

Invoke-Command allows you to execute scripts or commands on remote computers, facilitating remote management. Execute a command on a remote computer:

Invoke-Command -ComputerName RemotePC

53. Creating a PowerShell Script File

Out-File can be used to create a script by redirecting a string into a .ps1 file, which is the extension for PowerShell scripts. To write a script, save your commands in a .ps1 file:

"Notepad.exe" | Out-File -FilePath C:\Scripts\MyScript.ps1

54. Running a PowerShell Script

The call operator & allows you to execute a PowerShell script file by specifying its path. Execute a script by calling its path:

& "C:\Scripts\MyScript.ps1"

55. Scheduling a Job with Task Scheduler

New-ScheduledTaskAction and New-ScheduledTaskTrigger are used to create a scheduled task that runs a PowerShell script at a specified time. Schedule a PowerShell script to run at a specific time:

$Action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument 'C:\Scripts\MyScript.ps1'
$Trigger = New-ScheduledTaskTrigger -At 7am -Daily
Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName "MyTask" -Description "My daily PowerShell script"

56. Listing All Drives

Get-PSDrive lists all drives on your system, including network drives, CD-ROMs, and more. Get a list of all drives on your system using the below PowerShell cmdlet.

Get-PSDrive

57. Checking Service Status

Get-Service with the -Name parameter checks the status of a specific service by name. Check the status of a specific service:

Get-Service -Name "wuauserv"

58. Restarting a Service

Restart-Service cmdlet stops and then starts a service, which can be useful for troubleshooting or applying changes. To restart a service, use the below PowerShell script example.

Restart-Service -Name "wuauserv"

59. Creating a Custom Object

The New-Object cmdlet with the PSObject type and a hashtable of properties allow you to create an object with custom properties. This can be used to store and manipulate data in a structured form. Create a custom object with specific properties using PowerShell:

$customObject = New-Object PSObject -Property @{
    Name = 'John Doe'
    Age = 30
    JobTitle = 'Software Developer'
}

60. Filtering Event Logs

By combining Get-EventLog with Where-Object, you can filter event logs for specific types of entries or time frames, which is useful for system diagnostics and monitoring. Filter event logs by entry type or date using the simple PowerShell script example below.

Get-EventLog -LogName System | Where-Object { $_.EntryType -eq 'Error' -and $_.TimeGenerated -gt (Get-Date).AddDays(-1) }

61. Getting BIOS Information

The Get-WmiObject cmdlet with the Win32_BIOS class retrieves BIOS information from your system. This can include details like the BIOS version, manufacturer, and serial number. Retrieve BIOS information from your system using the below PowerShell scripts.

Get-WmiObject Win32_BIOS

62. Checking for Admin Rights

This script checks whether the current PowerShell session has administrative privileges by using the .NET class WindowsPrincipal. This is important for scripts that require elevated permissions to run correctly. Check if you’re running PowerShell with administrator privileges by using the sample PowerShell script.

if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Host "You are not running PowerShell as an Administrator."
}

63. Updating Help Files

The Update-Help cmdlet downloads the latest help files for PowerShell cmdlets, ensuring that you have access to the most current documentation and examples. Update PowerShell help files to the latest version:

Update-Help

64. Creating a Multi-Line Comment

In PowerShell, anything between <# and #> is treated as a comment and ignored by the interpreter. Multi-line comments are useful for adding detailed explanations or documentation within scripts. You can create a multi-line comment in your scripts like this:

<#
This is a multi-line comment.
It can span several lines.
#>
powershell script example

65. Creating an Array

In PowerShell, arrays are created by enclosing a comma-separated list of values in @().

$myArray = @('apple', 'banana', 'cherry')
Write-Host "The array contains: $myArray"

This command creates an array $myArray with three elements: ‘apple’, ‘banana’, and ‘cherry’. The Write-Host command then outputs the entire array as a string.

See also  PowerShell unblock-file

66. Accessing Array Elements

Each item in an array is assigned a unique index, starting with 0 for the first element.

$myArray = @('apple', 'banana', 'cherry')
Write-Host "The first element is: $($myArray[0])"

Here, $myArray[0] accesses the first element of $myArray, which is ‘apple’. The parentheses around $myArray[0] are necessary to ensure the array element is evaluated before being concatenated into the string.

67. Modifying an Array Element

You can change the value of an array element by specifying its index.

$myArray = @('apple', 'banana', 'cherry')
$myArray[1] = 'blueberry'
Write-Host "The modified array contains: $myArray"

This script changes the second element (at index 1) from ‘banana’ to ‘blueberry’. The array now contains ‘apple’, ‘blueberry’, and ‘cherry’.

68. Adding Elements to an Array

The += operator appends an item to the end of an array.

$myArray = @('apple', 'banana', 'cherry')
$myArray += 'date'
Write-Host "The array now contains: $myArray"

The += operator takes the existing array and adds ‘date’ as the last element, expanding the array’s size.

69. Iterating Over an Array

The foreach loop goes through each element in an array, executing the code block for each one.

$myArray = @('apple', 'banana', 'cherry')
foreach ($item in $myArray) {
    Write-Host "Fruit: $item"
}

In this example, the loop prints out each element in $myArray with the prefix “Fruit:”. It’s a common way to perform operations on each item in an array.

70. Filtering an Array

Where-Object filters an array based on a script block that returns true or false.

$myArray = @(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
$evenNumbers = $myArray | Where-Object { $_ % 2 -eq 0 }
Write-Host "Even numbers: $evenNumbers"

In this script, $_ represents each number in the pipeline, and the script block { $_ % 2 -eq 0 } evaluates to true for even numbers. The result is a new array $evenNumbers that contains only the even numbers from $myArray.

71. Basic PowerShell Function

A simple function that prints a greeting to the console using the below PowerShell example.

function Say-Hello {
    Write-Host "Hello, World!"
}

Say-Hello

When you call Say-Hello, it invokes the Write-Host cmdlet that outputs “Hello, World!” to the console.

72. PowerShell Function with Parameters

A function that takes a name as a parameter and greets the user by name. Here is a PowerShell script example.

function Greet-User {
    param($Name)
    Write-Host "Hello, $Name!"
}

Greet-User -Name "Alice"

The Greet-User function uses the param keyword to define a parameter $Name. When you call Greet-User -Name "Alice", it outputs “Hello, Alice!”.

73. Function with Multiple Parameters

A function that adds two numbers and returns the result. Here is a PowerShell example of a function with multiple parameters.

function Add-Numbers {
    param($Number1, $Number2)
    return $Number1 + $Number2
}

$result = Add-Numbers -Number1 5 -Number2 10
Write-Host "The result is: $result"

Add-Numbers takes two parameters, $Number1 and $Number2, adds them, and returns the sum. The result is stored in $result and then printed.

74. Function with Parameter Defaults

Here is a PowerShell script example of a function with a default value for a parameter.

function Get-TimeStamp {
    param($Format = "yyyyMMddHHmmss")
    return Get-Date -Format $Format
}

$timeStamp = Get-TimeStamp
Write-Host "The timestamp is: $timeStamp"

Get-TimeStamp returns the current date and time in a specified format. If no format is provided, it defaults to “yyyyMMddHHmmss”.

75. Advanced Function with Parameter Validation

A function that checks if a path is a valid directory before proceeding. Here is a PowerShell script example.

function Test-Directory {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [ValidateScript({Test-Path -Path $_ -PathType Container})]
        [string]$Path
    )
    Write-Host "The path '$Path' is a valid directory."
}

Test-Directory -Path "C:\Windows"

Test-Directory uses advanced function features like CmdletBinding for better integration with the PowerShell runtime and ValidateScript to ensure that the provided $Path is a valid directory before the function body executes.

These 75 PowerShell script examples should give beginners a solid foundation to automate tasks and manage systems using PowerShell. Remember, the best way to learn is by doing, so try out these examples, modify them, and practice writing your own scripts to become more proficient in PowerShell scripting.

You may also like:

  • I need to do a script using the function Measure-EquationOfline ($Point1, $Point2) that do the follow:

    Take exactly 2 arguments: $Point1and $Point2
    each is a pair of (x,y)coordinates
    Return a string of the format “y = mx + b”, where m and b are solved for
    Format m and b so they are nice to read (1.23 instead of 1.23456789)
    Return “Points are identical” if the inputs are the same
    Return “Undefined Slope” if line is a straight vertical line
    Make sure inputs to the function are valid, thus only one error is printed

    Any ideas? I tried but it is not working

  • Thank you for these introductory scripts in PowerShell..

    Found one error in Example-27

    $factValue = $number * (Get-Factorial($number – 1))

    should be

    $factValue = $number * (Factorial-Of-A-Number($number – 1))

  • >