Complete PowerShell Guide: Tutorial from Beginner to Advanced [2026]
PowerShell is Microsoft’s powerful task automation and configuration management framework, combining a command-line shell with a scripting language built on .NET. This comprehensive guide teaches you everything from basic commands to advanced automation, with practical examples you can use immediately.
Whether you’re a system administrator automating routine tasks, a DevOps engineer managing infrastructure, or an IT professional looking to enhance your skills, this guide provides the knowledge and hands-on examples to master PowerShell.
Table of Contents
- What is PowerShell?
- Installing and Setting Up PowerShell
- PowerShell Basics
- Understanding the Pipeline
- Variables and Data Types
- Arrays and Collections
- Hashtables and Dictionaries
- Operators
- Control Flow
- Functions and Scripts
- Working with Objects
- File System Operations
- String Manipulation
- Working with CSV, JSON, and XML
- Error Handling
- PowerShell Remoting
- Active Directory Management
- Registry Management
- Best Practices
- Advanced Topics
- Frequently Asked Questions
What is PowerShell?
PowerShell is a cross-platform task automation solution made up of a command-line shell, a scripting language, and a configuration management framework. PowerShell runs on Windows, Linux, and macOS, providing administrators with a unified automation platform.
Key Features
- Object-Based Pipeline: Unlike text-based shells (CMD, Bash), PowerShell passes .NET objects between commands
- Consistent Syntax: Verb-Noun naming convention makes commands predictable and discoverable
- Extensive Integration: Deep integration with Windows, Active Directory, Azure, Microsoft 365, and more
- Scripting Language: Full programming language with loops, conditionals, functions, classes
- Remote Management: Built-in remoting capabilities for managing remote systems
- Module System: Thousands of modules extend PowerShell functionality
PowerShell vs. Traditional Command Prompts
| Feature | PowerShell | CMD | Bash |
|---|---|---|---|
| Objects vs. Text | Objects | Text | Text |
| Syntax | Verb-Noun | Varied | Varied |
| Cross-Platform | Yes (PS 7+) | Windows only | Unix/Linux/Mac |
| Scripting | Full language | Limited | Full language |
| Remote Management | Built-in | Limited | SSH |
| Module Ecosystem | Extensive | None | Package-dependent |
PowerShell Versions
| Version | Release Year | Platform | Status |
|---|---|---|---|
| PowerShell 5.1 | 2016 | Windows only | Maintenance (included with Windows) |
| PowerShell 7.0-7.4 | 2020-2023 | Cross-platform | Current |
| PowerShell 7.5+ | 2024+ | Cross-platform | Latest |
Recommendation: Use PowerShell 7.x (PowerShell Core) for new projects. It’s cross-platform, actively developed, and includes modern features while maintaining 95%+ compatibility with Windows PowerShell 5.1.
Common Use Cases
- System Administration: Manage users, computers, services, and configurations
- Automation: Automate repetitive tasks and workflows
- Active Directory Management: Create, modify, and query AD objects
- Azure Management: Provision and manage Azure resources
- Microsoft 365 Administration: Manage Exchange, SharePoint, Teams
- DevOps: Infrastructure as Code, CI/CD pipelines, configuration management
- Security Operations: Incident response, log analysis, compliance checking
- Reporting: Generate reports from various data sources
Installing and Setting Up PowerShell
Windows
Windows 10/11 includes PowerShell 5.1 by default. To install PowerShell 7:
Method 1: Microsoft Store
- Open Microsoft Store
- Search for “PowerShell”
- Click Get or Install
Method 2: MSI Installer
- Download from GitHub Releases
- Run the
.msiinstaller - Follow installation wizard
Method 3: winget (Windows Package Manager)
winget install Microsoft.PowerShell
```powershell
**Method 4: PowerShell (Bootstrap)**
```powershell
iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"
macOS
Using Homebrew:
brew install --cask powershell
Verification:
pwsh --version
Linux
Ubuntu/Debian:
# Update package index
sudo apt-get update
# Install dependencies
sudo apt-get install -y wget apt-transport-https software-properties-common
# Download Microsoft repository GPG keys
wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb"
# Register repository
sudo dpkg -i packages-microsoft-prod.deb
# Install PowerShell
sudo apt-get update
sudo apt-get install -y powershell
# Start PowerShell
pwsh
RHEL/CentOS/Fedora:
# Register repository
curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo
# Install PowerShell
sudo yum install -y powershell
# Start PowerShell
pwsh
Opening PowerShell
Windows PowerShell 5.1:
- Start Menu → Search “PowerShell”
- Run dialog (
Win+R) → Typepowershell→ Enter - File Explorer → Address bar → Type
powershell→ Enter - As Administrator: Right-click → “Run as Administrator”
PowerShell 7+:
- Start Menu → Search “pwsh” or “PowerShell 7”
- Run dialog → Type
pwsh→ Enter - Windows Terminal (recommended)
Configuring PowerShell
Set Execution Policy (Windows):
PowerShell’s execution policy controls which scripts can run.
# View current execution policy
Get-ExecutionPolicy
# Set execution policy (requires Administrator)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Execution Policies:
- Restricted: No scripts allowed (default on Windows client)
- AllSigned: Only signed scripts
- RemoteSigned: Local scripts OK, downloaded scripts must be signed (recommended)
- Unrestricted: All scripts allowed (prompts for downloaded scripts)
- Bypass: Nothing blocked, no warnings
Install PowerShellGet (Module Management):
# Check current version
Get-Module -Name PowerShellGet -ListAvailable
# Update PowerShellGet (if needed)
Install-Module -Name PowerShellGet -Force -AllowClobber
Install PSReadLine (Better Console Experience):
Install-Module -Name PSReadLine -Force
PSReadLine provides:
- Syntax highlighting
- Predictive IntelliSense
- History search (
Ctrl+R) - Improved editing experience
PowerShell Basics
Cmdlets: The Building Blocks
Cmdlets (pronounced “command-lets”) are PowerShell commands following a Verb-Noun naming convention.
Examples:
Get-Process- Retrieves running processesSet-Location- Changes current directoryNew-Item- Creates new files or directoriesRemove-Item- Deletes files or directoriesStop-Service- Stops a Windows service
Common Verbs:
- Get: Retrieve information
- Set: Modify or configure
- New: Create new objects
- Remove: Delete objects
- Start/Stop: Control services and processes
- Enable/Disable: Enable or disable features
- Test: Validate or check conditions
- Export/Import: Save or load data
Get-Command: Discovering Cmdlets
Find all cmdlets:
Get-Command
Find cmdlets by verb:
Get-Command -Verb Get
Get-Command -Verb Set
Find cmdlets by noun:
Get-Command -Noun Service
Get-Command -Noun Process
Search by pattern:
Get-Command *User*
Get-Command *AD*
Get-Help: Your Built-in Documentation
Get help for a cmdlet:
Get-Help Get-Process
Get detailed help:
Get-Help Get-Process -Detailed
Get full help with examples:
Get-Help Get-Process -Full
Get only examples:
Get-Help Get-Process -Examples
Update help files (run periodically):
Update-Help -Force
Search help:
Get-Help *process*
Get-Member: Understanding Objects
See object properties and methods:
Get-Process | Get-Member
Filter by member type:
Get-Process | Get-Member -MemberType Property
Get-Process | Get-Member -MemberType Method
Example output:
TypeName: System.Diagnostics.Process
Name MemberType Definition
---- ---------- ----------
Handles Property int Handles {get;}
Id Property int Id {get;}
ProcessName Property string ProcessName {get;}
Kill Method void Kill()
WaitForExit Method void WaitForExit()
Basic Navigation
Get current location:
Get-Location
# Or shortcut:
pwd
Change directory:
Set-Location C:\Windows
# Or shortcut:
cd C:\Windows
List files and directories:
Get-ChildItem
# Or shortcuts:
dir
ls
Go to parent directory:
cd ..
Go to home directory:
cd ~
Go to root:
cd \
Aliases: Shortcuts for Cmdlets
PowerShell includes aliases for common commands:
| Alias | Cmdlet | Description |
|---|---|---|
| ls, dir | Get-ChildItem | List files |
| cd | Set-Location | Change directory |
| pwd | Get-Location | Print working directory |
| cat | Get-Content | Display file contents |
| cp | Copy-Item | Copy files |
| mv | Move-Item | Move files |
| rm | Remove-Item | Delete files |
| cls, clear | Clear-Host | Clear screen |
| echo | Write-Output | Output text |
View all aliases:
Get-Alias
Find alias for cmdlet:
Get-Alias -Definition Get-ChildItem
Create custom alias:
Set-Alias -Name list -Value Get-ChildItem
Note: Aliases are session-specific unless added to your PowerShell profile.
Understanding the Pipeline
The pipeline (|) is PowerShell’s most powerful feature, allowing you to pass objects from one cmdlet to another.
Basic Pipeline Concept
Get-Process | Where-Object {$_.CPU -gt 100} | Sort-Object CPU -Descending | Select-Object -First 10
How it works:
Get-Processretrieves all processes (outputs process objects)Where-Objectfilters processes with CPU > 100Sort-Objectsorts by CPU usage (descending)Select-Objecttakes top 10 results
Objects in the Pipeline
Unlike text-based shells, PowerShell passes full objects with properties and methods:
# Get a process object
$process = Get-Process -Name notepad
# Access properties
$process.Id
$process.ProcessName
$process.CPU
# Call methods
$process.Kill()
Common Pipeline Cmdlets
Where-Object: Filtering
Filter by property value:
Get-Service | Where-Object {$_.Status -eq 'Running'}
Multiple conditions (AND):
Get-Process | Where-Object {$_.CPU -gt 100 -and $_.WorkingSet64 -gt 100MB}
Multiple conditions (OR):
Get-Service | Where-Object {$_.Status -eq 'Running' -or $_.StartType -eq 'Automatic'}
Simplified syntax (PowerShell 3.0+):
Get-Service | Where Status -eq 'Running'
Get-Process | Where CPU -gt 100
Select-Object: Choosing Properties
Select specific properties:
Get-Process | Select-Object Name, Id, CPU
Select first N objects:
Get-Process | Select-Object -First 10
Select last N objects:
Get-Process | Select-Object -Last 5
Select unique values:
Get-Process | Select-Object -Property ProcessName -Unique
Create calculated properties:
Get-Process | Select-Object Name, @{Name='Memory(MB)'; Expression={$_.WorkingSet64 / 1MB}}
Sort-Object: Sorting
Sort ascending (default):
Get-Process | Sort-Object CPU
Sort descending:
Get-Process | Sort-Object CPU -Descending
Sort by multiple properties:
Get-Process | Sort-Object Company, ProcessName
ForEach-Object: Processing Each Object
Perform action on each object:
Get-Process | ForEach-Object {
Write-Host "$($_.Name) is using $($_.CPU) CPU"
}
Simplified syntax:
Get-Process | ForEach-Object Name
# Same as: Get-Process | Select-Object -ExpandProperty Name
Using aliases:
Get-Process | % { $_.Kill() } # % is alias for ForEach-Object
Group-Object: Grouping Data
Group by property:
Get-Process | Group-Object ProcessName
Group with count:
Get-Service | Group-Object Status
Output:
Count Name Group
----- ---- -----
185 Running {AdobeARMservice, Appinfo, AppXSvc...}
98 Stopped {ALG, AppIDSvc, AppReadiness...}
Measure-Object: Statistics
Count objects:
Get-Process | Measure-Object
Calculate statistics:
Get-Process | Measure-Object -Property CPU -Sum -Average -Maximum -Minimum
Example output:
Count : 156
Average : 2.34
Sum : 365.12
Maximum : 45.78
Minimum : 0
Variables and Data Types
Creating Variables
Variables in PowerShell start with $:
$name = "John Doe"
$age = 30
$isAdmin = $true
$salary = 75000.50
View variable value:
$name # Outputs: John Doe
Write-Host $name
Variable naming rules:
- Must start with
$ - Can contain letters, numbers, underscores
- Case-insensitive (
$Name=$name) - Avoid PowerShell reserved words
Data Types
PowerShell automatically determines data type, but you can explicitly specify:
[string]$name = "John"
[int]$age = 30
[double]$salary = 75000.50
[bool]$isActive = $true
[datetime]$hireDate = "2020-01-15"
Common data types:
[string]- Text[int]- 32-bit integer[long]- 64-bit integer[double]- Floating point number[bool]- Boolean (true/false)[datetime]- Date and time[array]- Array[hashtable]- Hash table/dictionary
Check variable type:
$name.GetType()
Output:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
Type Casting
Convert between types:
# String to integer
[int]$number = "42"
# Integer to string
[string]$text = 42
# String to datetime
[datetime]$date = "2024-01-15"
# String to boolean
[bool]$value = "true"
Type conversion examples:
# Explicit casting
$result = [int]"100" + [int]"50" # 150
# Implicit conversion
$result = "100" + "50" # "10050" (string concatenation)
$result = 100 + 50 # 150 (numeric addition)
Automatic Variables
PowerShell provides built-in automatic variables:
| Variable | Description |
|---|---|
$_ or $PSItem | Current object in pipeline |
$true / $false | Boolean values |
$null | Null value |
$HOME | User’s home directory |
$PWD | Current directory |
$PSVersionTable | PowerShell version information |
$Error | Array of recent errors |
$PID | Current process ID |
$Host | Current host application |
Examples:
# Current directory
$PWD
# PowerShell version
$PSVersionTable.PSVersion
# Last error
$Error[0]
Variable Scope
Scope levels:
- Global: Available everywhere
- Script: Available in script file
- Local: Current scope (default)
- Private: Current scope only (not child scopes)
Explicitly set scope:
$global:ConfigPath = "C:\Config"
$script:tempValue = 42
$local:count = 0
Example:
$globalVar = "Global" # Local to current scope
function Test-Scope {
$localVar = "Local" # Local to function
$global:globalVar = "Modified Global"
Write-Host $localVar # Works
}
Test-Scope
Write-Host $globalVar # Shows "Modified Global"
Write-Host $localVar # Empty (out of scope)
Arrays and Collections
Arrays are fundamental data structures in PowerShell that allow you to store multiple items and work with collections of data. This section covers creating, manipulating, and iterating through arrays using PowerShell’s powerful collection cmdlets.
For a deep dive on arrays, see our Complete Arrays Tutorial.
Creating Arrays
Basic array:
$fruits = @("Apple", "Banana", "Orange")
Alternative syntax:
$fruits = "Apple", "Banana", "Orange"
Empty array:
$emptyArray = @()
Single-element array:
$singleArray = @("Apple") # Force array with one element
$notArray = "Apple" # Just a string
Array of integers:
$numbers = 1, 2, 3, 4, 5
Range operator:
$numbers = 1..10 # 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
$letters = 'a'..'z' # All lowercase letters
Accessing Array Elements
Index access (zero-based):
$fruits = @("Apple", "Banana", "Orange")
$fruits[0] # Apple
$fruits[1] # Banana
$fruits[2] # Orange
Negative indices (from end):
$fruits[-1] # Orange (last element)
$fruits[-2] # Banana (second from last)
Range of elements:
$numbers = 1..10
$numbers[2..5] # 3, 4, 5, 6
$numbers[0,2,4] # 1, 3, 5 (specific indices)
Array Properties and Methods
Array length:
$fruits.Count
$fruits.Length # Same as Count
Check if array contains element:
$fruits -contains "Apple" # True
$fruits -contains "Grape" # False
Get index of element:
$index = [array]::IndexOf($fruits, "Banana") # 1
Modifying Arrays
⚠️ Arrays are fixed-size - you can’t truly add/remove elements, but you can create new arrays:
Add elements:
$fruits = @("Apple", "Banana")
$fruits += "Orange" # Creates new array with Orange added
$fruits += "Grape", "Mango" # Add multiple elements
Remove elements (using Where-Object):
$fruits = $fruits | Where-Object { $_ -ne "Banana" }
# Or:
$fruits = $fruits -ne "Banana"
Replace element:
$fruits[1] = "Blueberry"
ArrayList (Dynamically Sized)
For better performance with dynamic arrays, use ArrayList:
$list = [System.Collections.ArrayList]@()
# Add elements (use [void] to suppress output)
[void]$list.Add("Apple")
[void]$list.Add("Banana")
# Remove elements
$list.Remove("Apple")
$list.RemoveAt(0) # Remove by index
# Check count
$list.Count
Multi-Dimensional Arrays
Create 2D array:
$matrix = @(
@(1, 2, 3),
@(4, 5, 6),
@(7, 8, 9)
)
Access elements:
$matrix[0][0] # 1
$matrix[1][2] # 6
$matrix[2][1] # 8
Array Iteration
ForEach-Object loop:
$fruits | ForEach-Object {
Write-Host "Fruit: $_"
}
ForEach loop:
foreach ($fruit in $fruits) {
Write-Host "Fruit: $fruit"
}
For loop:
for ($i = 0; $i -lt $fruits.Count; $i++) {
Write-Host "Index $i : $($fruits[$i])"
}
Useful Array Operations
Sort array:
$numbers = 5, 2, 8, 1, 9
$sorted = $numbers | Sort-Object
Remove duplicates:
$numbers = 1, 2, 2, 3, 3, 3, 4
$unique = $numbers | Select-Object -Unique
Filter array:
$numbers = 1..10
$evens = $numbers | Where-Object { $_ % 2 -eq 0 }
Find first matching element:
$fruits = @("Apple", "Banana", "Orange", "Apple")
$first = $fruits | Where-Object { $_ -eq "Apple" } | Select-Object -First 1
Join array to string:
$fruits = @("Apple", "Banana", "Orange")
$joined = $fruits -join ", " # "Apple, Banana, Orange"
Split string to array:
$text = "Apple,Banana,Orange"
$array = $text -split "," # @("Apple", "Banana", "Orange")
[Due to length constraints, I’ll continue with the remaining major sections in summary form. The full guide would continue with the same depth for each topic.]
Hashtables and Dictionaries
Hashtables (hash tables) store data in key-value pairs, making them perfect for structured data like configuration files, user records, and lookups. Unlike arrays indexed by number, hashtables use named keys for more readable and maintainable code.
Learn more: PowerShell Hashtables Complete Guide
Hashtables store key-value pairs:
$user = @{
Name = "John Doe"
Age = 30
Department = "IT"
IsActive = $true
}
# Access values
$user["Name"]
$user.Age
# Add/modify
$user["Email"] = "john@contoso.com"
$user.Age = 31
# Remove
$user.Remove("IsActive")
# Iterate
foreach ($key in $user.Keys) {
Write-Host "$key : $($user[$key])"
}
[Full section would include ordered hashtables, nested hashtables, hashtable methods, and practical examples]
---
## Operators
**PowerShell operators control how values are compared and combined.** Understanding operators is essential for building conditions, filters, and expressions throughout your scripts. PowerShell supports comparison, arithmetic, logical, and assignment operators.
**Recommended guides:**
- [Comparison Operators for Filtering](/powershell-where-object)
- Regular Expression Matching
- Boolean Logic
PowerShell operators for comparison, arithmetic, logical operations:
**Comparison:**
- `-eq` (equal), `-ne` (not equal)
- `-gt` (greater than), `-lt` (less than)
- `-ge`, `-le` (greater/less than or equal)
- `-like`, `-notlike` (wildcard matching)
- `-match`, `-notmatch` (regex matching)
- `-contains`, `-notcontains` (array contains)
**Arithmetic:**
- `+`, `-`, `*`, `/`, `%` (modulus)
**Logical:**
- `-and`, `-or`, `-not`, `!`
**Examples:**
```powershell
5 -eq 5 # True
"Hello" -like "H*" # True
10 -gt 5 -and 5 -lt 20 # True
```powershell
[Full section would include all operator types, precedence, and examples]
---
## Control Flow
**Control flow statements determine which code blocks execute based on conditions.** PowerShell supports if/else statements, switch statements, and multiple loop types (foreach, for, while, do-while) for iterating through data and making decisions.
**Related guides:**
- If/Else Statements
- [Switch Statements](/powershell-switch-statement)
- ForEach Loops
- While and Do-While Loops
### If/ElseIf/Else
```powershell
$age = 25
if ($age -lt 18) {
Write-Host "Minor"
} elseif ($age -lt 65) {
Write-Host "Adult"
} else {
Write-Host "Senior"
}
Switch
$day = "Monday"
switch ($day) {
"Monday" { "Start of work week" }
"Friday" { "End of work week" }
"Saturday" { "Weekend!" }
"Sunday" { "Weekend!" }
default { "Regular work day" }
}
Loops
ForEach:
$fruits = @("Apple", "Banana", "Orange")
foreach ($fruit in $fruits) {
Write-Host $fruit
}
For:
for ($i = 0; $i -lt 10; $i++) {
Write-Host "Count: $i"
}
While:
$count = 0
while ($count -lt 5) {
Write-Host $count
$count++
}
Do-While / Do-Until:
do {
$input = Read-Host "Enter 'exit' to quit"
} while ($input -ne "exit")
[Full section would include break, continue, and loop control]
Functions and Scripts
Functions are reusable blocks of code that perform specific tasks. PowerShell supports simple functions and advanced functions with parameters, validation, help documentation, and error handling. Scripts combine functions and commands to automate complex tasks.
Learn more:
- PowerShell Functions Complete Guide
- Function Parameters
- Error Handling in Functions
Basic Functions
function Get-Greeting {
param(
[string]$Name
)
return "Hello, $Name!"
}
Get-Greeting -Name "John"
Advanced Functions
function Get-UserInfo {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Username,
[Parameter()]
[string]$Domain = "contoso.com"
)
Write-Verbose "Getting info for $Username"
# Function logic here
}
[Full section would cover script files, dot-sourcing, modules, parameter validation, and more]
Working with Objects
PowerShell is fundamentally object-oriented;everything is an object with properties and methods. Unlike text-based shells, PowerShell passes full objects through the pipeline, allowing you to access properties and call methods on any output.
Related guides:
- Select-Object: Choose Properties
- Where-Object: Filter Objects
- ForEach-Object: Process Each Object
- Custom Objects
PowerShell is object-oriented. Everything is an object:
$process = Get-Process -Name notepad
# Properties
$process.Id
$process.ProcessName
$process.CPU
# Methods
$process.Kill()
$process.Refresh()
# Custom objects
$user = [PSCustomObject]@{
Name = "John"
Age = 30
Department = "IT"
}
[Full section would include object creation, manipulation, and custom types]
File System Operations
PowerShell provides powerful cmdlets for working with the file system, including reading, writing, creating, deleting, and managing files and folders. Learn efficient file operations patterns for daily administration tasks.
Comprehensive guides:
- Creating Files in PowerShell
- Deleting Files and Folders
- Renaming Files and Folders
- Listing Files and Directories
Reading Files
# Read entire file
$content = Get-Content "C:\file.txt"
# Read first N lines
$content = Get-Content "C:\file.txt" -TotalCount 10
# Read last N lines
$content = Get-Content "C:\file.txt" -Tail 5
# Read line by line
Get-Content "C:\file.txt" | ForEach-Object {
Write-Host $_
}
Writing Files
# Overwrite file
"Hello World" | Out-File "C:\file.txt"
# Append to file
"New line" | Add-Content "C:\file.txt"
# Write multiple lines
@("Line 1", "Line 2", "Line 3") | Set-Content "C:\file.txt"
File Operations
# Create file
New-Item -Path "C:\file.txt" -ItemType File
# Copy file
Copy-Item "C:\source.txt" "C:\destination.txt"
# Move file
Move-Item "C:\source.txt" "C:\new-location\file.txt"
# Delete file
Remove-Item "C:\file.txt"
# Check if file exists
Test-Path "C:\file.txt"
# Get file properties
Get-Item "C:\file.txt" | Select-Object Name, Length, LastWriteTime
[Full section would include directory operations, filters, recursion, and advanced file management]
Active Directory Management
PowerShell is essential for Active Directory administration, providing powerful cmdlets to manage users, groups, organizational units, and group policies at scale. The ActiveDirectory module enables administrators to automate routine AD tasks and perform complex queries.
Comprehensive AD Resources:
PowerShell is essential for AD administration:
# Import AD module
Import-Module ActiveDirectory
# Get user
Get-ADUser -Identity jdoe
# Create user
New-ADUser -Name "John Doe" -SamAccountName jdoe -UserPrincipalName jdoe@contoso.com
# Modify user
Set-ADUser -Identity jdoe -Department "IT" -Title "System Administrator"
# Get all users in OU
Get-ADUser -Filter * -SearchBase "OU=Users,DC=contoso,DC=com"
# Get group members
Get-ADGroupMember -Identity "Domain Admins"
# Add user to group
Add-ADGroupMember -Identity "IT-Staff" -Members jdoe
For comprehensive Active Directory coverage, see our Complete Active Directory Guide.
Best Practices
Follow these best practices to write maintainable, professional PowerShell code. These guidelines apply to scripts, functions, and modules alike.
- Use approved verbs:
Get-Verbshows standard verbs - Write functions, not scripts: Reusable and testable - Learn about functions
- Use comment-based help: Document your code
- Handle errors properly: Use Try/Catch blocks
- Use PSReadLine: Better editing experience
- Write verbose and debug output: Help troubleshooting
- Use splatting for readability: Organize parameters
- Test scripts thoroughly: Use Pester for unit testing
- Follow naming conventions: Clear, descriptive names - Naming conventions guide
- Use version control: Git for script management
Related Topics:
- PowerShell Functions
- Error Handling
- Script Organization
- Advanced Function Patterns
Frequently Asked Questions
Q: What’s the difference between PowerShell and PowerShell Core? A: “PowerShell” or “Windows PowerShell” (5.1) is Windows-only. “PowerShell Core” (now just “PowerShell 7+”) is cross-platform, open-source, and actively developed. Use PowerShell 7+ for new projects.
Q: How do I run PowerShell scripts?
A: Save code as .ps1 file, then run: .\script.ps1 (or powershell.exe -File script.ps1 from CMD). You may need to set execution policy first.
Q: What are PowerShell modules?
A: Modules are packages of cmdlets, functions, and scripts. Install with Install-Module, import with Import-Module. Browse modules at PowerShell Gallery.
Q: How do I automate PowerShell scripts?
A: Use Windows Task Scheduler to run scripts on schedule. Create scheduled task running powershell.exe -File C:\script.ps1.
[20+ more FAQs covering common PowerShell questions]
Related Resources
Arrays and Collections
- Complete Arrays Tutorial
- Hashtables and Dictionaries
- ForEach-Object: Iterate Collections
- Where-Object: Filter Data
- Group-Object: Organize Data
- Measure-Object: Calculate Statistics
- Select-Object: Choose Properties
File Operations
- Create Files
- Delete Files and Folders
- Rename Files
- List Files in Directory
- Directory Listing
- Copy and Move Files
- Get File Properties
String Operations
- PowerShell Strings Guide
- Replace Text in Strings
- Split Strings
- Extract Substrings
- String Formatting
- Regular Expressions
- Escape Special Characters
- String Concatenation
Control Flow
- If/Else Statements
- Switch Statements
- ForEach Loops
- For Loops
- While Loops
- Do-While Loops
- Break and Continue
- Try-Catch Error Handling
Functions and Scripts
- PowerShell Functions Guide
- Function Parameters
- Advanced Functions
- Function Return Values
- Script Blocks
- Modules and Imports
- Best Practices
Variables and Data Types
- Variables in PowerShell
- Variable Scope
- Type Casting
- Null Values
- Boolean Logic
- Numeric Operations
Data Formats
- CSV Operations
- JSON Handling
- XML Processing
- Custom Objects
- Hash Tables
Active Directory
Advanced Topics
- PowerShell Remoting
- Invoke-Command
- Registry Management
- Event Logs
- Performance Optimization
- Debugging Techniques
Miscellaneous
- Date and Time Operations
- Output Formatting
- Get-Help System
- Aliases
- Environment Variables