← Back to list

Scripting in PowerShell

PowerShell is a powerful scripting language and command-line shell developed by Microsoft. It is built on the .NET framework and is…

Eyad Hasanato · 2025-03-09 09:44 · 0 claps · 3.6 min read
#powershell #automation #it #scripting-language #scripting
Open on Medium ↗
Wiki topics: 🥊 · Combat Sports

Scripting in PowerShell

PowerShell is a powerful scripting language and command-line shell developed by Microsoft. It is built on the .NET framework and is primarily used for automating administrative tasks, managing system configurations, and handling cloud services like Microsoft Azure.

Why Use PowerShell?

  1. Automation — Automate repetitive tasks to save time.
  2. System Administration — Manage Windows OS, Active Directory, and Azure services.
  3. Task Scheduling — Run scripts at specific intervals.
  4. Configuration Management — Deploy and manage system configurations.

PowerShell Variables

PowerShell uses $ to define variables:

$Name = "john"
$Age= 30
Write-Output "my name is $Name & I am $Age years old"

PowerShell Control Structures

1-Conditional Statements (if-else)

$Number = 20
if ($Number -gt 5){
    Write-Output "The number is greater than 5"
}
else{
Wirte_output "The number is 5 or less"
}

2-Loops (For-While-Foreach)

for ($i=1; $i -le 5; $i++){
Wwrite_output "iteration $i"
}
$counter = 1
while ($counter -le 3){
Write_output "counter: $counter"
$counter++
}
$letterArray= 'a','b','c','d'
foreach ($letter in $letterArray)
{
Write_Output "letters: $letter"

Working with Functions

PowerShell functions allow you to reuse code:

function GreetUser {
      param ($name)
      write_output "Hello, $name!"
}
GreetUser "Alice"

Working with Files and Folders

1-Creating a File

New-Item -path "C:\Test\Sample.txt" -ItemType File

2-Reading a File

Get-content "C:\test\sample.txt"

3-Writing to a File

"Hello, Powershell" | out-File "C:\test\sample.txt"

4-Deleting a File

Remove-Item "C:\test\sample.txt

PowerShell module

a group of functions, where-as each function performs a different task, and represents a new cmdlet.

if you have already created a script that contains multiple functions for the organization then you are well on your way to creating a PowerShell module.

Modules extend PowerShell functionality.

1- Listing Installed Modules

Get-Module -ListAvailable

2-Importing a Module

Import_Module ActiveDirectory

3-Installing a new Module

Install-Module -Name Az -Force

PowerShell Scripting Exercises

- System Information Report

Objective- Create a PowerShell script that gathers system information, including OS version, CPU details, memory usage, and disk space. Save the results to a text file.

Steps

  • Get the OS version.
  • Retrieve CPU details.
  • Check total and available RAM.
  • Get disk space usage.
  • Save the information to a text file.
# Get OS version
$OS = Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version

# Get CPU details
$CPU = Get-CimInstance Win32_Processor | Select-Object Name, MaxClockSpeed, NumberOfCores

# Get memory details
$Memory = Get-CimInstance Win32_ComputerSystem | Select-Object TotalPhysicalMemory

# Get free disk space
$Disk = Get-PSDrive -PSProvider FileSystem | Select-Object Name, Free, Used

# Save report
$report = @"
System Information Report
=========================
Operating System: $($OS.Caption) - Version: $($OS.Version)
CPU: $($CPU.Name), Speed: $($CPU.MaxClockSpeed) MHz, Cores: $($CPU.NumberOfCores)
Total RAM: $([math]::Round($Memory.TotalPhysicalMemory / 1GB, 2)) GB
Disk Space:
$($Disk | Format-Table -AutoSize | Out-String)
"@

$report | Set-Content -Path "C:\PowerShellPractice\SystemReport.txt"
Write-Output "System Report Saved!"

- Monitor High CPU Usage and Kill Processes

Objective- Create a script that continuously monitors system processes and terminates any that exceed 80% CPU usage.

Steps:

  • Get all running processes.
  • Filter processes with CPU usage > 80%.
  • Prompt the user before killing the process.
# Get high CPU usage processes
$highCPU = Get-Process | Where-Object { $_.CPU -gt 80 }

if ($highCPU) {
    foreach ($process in $highCPU) {
        $processName = $process.Name
        $confirm = Read-Host "Process $processName is using high CPU. Kill it? (Yes/No)"

        if ($confirm -eq "Yes") {
            Stop-Process -Id $process.Id -Force
            Write-Output "Process $processName terminated."
        }
    }
} else {
    Write-Output "No high CPU usage processes found."
}

- Automated Backup Script

Objective- Create a script that automatically backs up selected files to a different location, with timestamps.

Steps

  • Define the source and backup destination.
  • Copy files to the backup folder with timestamps.
  • Ensure only the latest 5 backups are kept.
# Define paths
$sourcePath = "C:\Users\Public\Documents"
$backupPath = "C:\Backups"
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$backupFolder = "$backupPath\Backup_$timestamp"

# Create backup folder
New-Item -ItemType Directory -Path $backupFolder

# Copy files
Copy-Item -Path "$sourcePath\*" -Destination $backupFolder -Recurse
Write-Output "Backup completed: $backupFolder"

# Keep only latest 5 backups
$backups = Get-ChildItem -Path $backupPath | Sort-Object LastWriteTime -Descending
if ($backups.Count -gt 5) {
    $backups | Select-Object -Skip 5 | Remove-Item -Recurse -Force
    Write-Output "Old backups deleted."
}

- Network Scanner

Objective- Create a script to scan the local network and list active devices.

Steps

  • Get the local subnet IP.
  • Ping IP addresses in the subnet.
  • Display active devices.
$subnet = "192.168.1.10" # change it to be match your Network
$activeDevices = @()
for ($i=; $i -le 254; $i++){
$ip = "$subnet.$i"
if (Test-Connection -ComputerName $ip -Count 1 -Quiet){
   $activedevices + =$ip
  }
}

Write-Output "Active Devices on the network"
$activeDevices

Before Run a script

You need to be aware that some scripts aren’t safe. If you find a script on the internet, you probably shouldn’t run it on your computer unless you understand exactly what it does.

PowerShell is an essential tool for IT administrators, DevOps , and cloud engineers you can automate system tasks, improve efficiency, and manage infrastructure effortlessly.


메타데이터
post_id
6453020e970c
slug
scripting-in-powershell-6453020e970c
url
https://medium.com/@eyad9abd/scripting-in-powershell-6453020e970c
canonical_url
https://medium.com/@eyad9abd/scripting-in-powershell-6453020e970c
author_url
https://medium.com/@eyad9abd
status
ok
fetched_at
2026-08-24 16:46:10