Scripting with PowerShell

PowerShell is a powerful task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. It's designed for system administrators and power users, enabling them to control and automate administration of Windows and other platforms.

Why Use PowerShell for Scripting?

Your First PowerShell Script

Let's create a simple script to get system information.

Example: System Information Script

Create a new file named GetSystemInfo.ps1 and paste the following code:

# GetSystemInfo.ps1
            # This script retrieves basic system information.

            Write-Host "--- System Information ---"

            # Get computer name
            $ComputerName = $env:COMPUTERNAME
            Write-Host "Computer Name: $($ComputerName)"

            # Get Operating System details
            $OS = Get-CimInstance Win32_OperatingSystem
            Write-Host "OS Name: $($OS.Caption)"
            Write-Host "OS Version: $($OS.Version)"
            Write-Host "Build Number: $($OS.BuildNumber)"

            # Get processor information
            $Processor = Get-CimInstance Win32_Processor | Select-Object -First 1
            Write-Host "Processor: $($Processor.Name)"
            Write-Host "Number of Cores: $($Processor.NumberOfCores)"

            # Get total and free physical memory
            $Memory = Get-CimInstance Win32_PhysicalMemoryArray | Select-Object -First 1
            $TotalMemoryGB = [math]::Round($Memory.Capacity / 1GB, 2)
            Write-Host "Total RAM: $($TotalMemoryGB) GB"

            $FreeMemory = (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory - (Get-Counter '\Memory\Available MBytes').CookedValue
            $FreeMemoryGB = [math]::Round($FreeMemory / 1GB, 2)
            Write-Host "Available RAM: $($FreeMemoryGB) GB"

            Write-Host "------------------------"
            

Running the Script

Open PowerShell and navigate to the directory where you saved the file. Then, execute it:

PS C:\Path\To\Your\Scripts> .\GetSystemInfo.ps1
Note: You might need to adjust your PowerShell execution policy to run scripts. You can do this by running Set-ExecutionPolicy RemoteSigned as an administrator.

Key PowerShell Concepts

Common Tasks

PowerShell's capabilities extend far beyond these basics. Dive deeper into the official Microsoft documentation and community resources to unlock its full potential for managing your systems.