---
title: PowerShell Scripting and Programming
tags: [powershell, scripting, programming, automation, development]
---

# PowerShell Scripting and Programming

This guide dives deeper into the programming aspects of PowerShell, moving beyond simple one-liners to robust, reusable scripts and tools.

**Parent Topic:** [[programming/PowerShell/PowerShell|PowerShell Comprehensive Guide]]

## 1. Script Execution

By default, Windows prevents scripts from running for security reasons.

### Execution Policies
*   **Restricted**: No scripts run. (Default on many systems)
*   **RemoteSigned**: Scripts created locally run; downloaded scripts must be signed by a trusted publisher. (Recommended)
*   **Unrestricted**: All scripts run, but you may be prompted before running downloaded scripts.

```powershell
# Check current policy
Get-ExecutionPolicy

# Set policy (requires Admin)
Set-ExecutionPolicy RemoteSigned
```

### Running Scripts
To run a script in the current directory, you must specify the path (e.g., `.\`).
```powershell
.\MyScript.ps1
```

## 2. Advanced Functions

You can turn a simple function into a robust tool that behaves like a native cmdlet by adding `[CmdletBinding()]`.

```powershell
function Get-UserReport {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, Position=0)]
        [string]$UserName,

        [Parameter(ValueFromPipeline=$true)]
        [string]$Department = "IT"
    )

    process {
        Write-Verbose "Processing user: $UserName"
        return [PSCustomObject]@{
            Name = $UserName
            Dept = $Department
            Date = Get-Date
        }
    }
}
```
*   **`[CmdletBinding()]`**: Enables common parameters like `-Verbose`, `-WhatIf`, and `-Confirm`.
*   **`[Parameter()]`**: Defines validation, mandatory status, and pipeline behavior.

## 3. Input Validation

Ensure your script receives the right data using validation attributes.

```powershell
param (
    [ValidateSet("Dev", "QA", "Prod")]
    [string]$Environment,

    [ValidateRange(1, 100)]
    [int]$Count,

    [ValidateScript({ Test-Path $_ })]
    [string]$FilePath
)
```

## 4. Error Handling

### Try-Catch-Finally
Use `try-catch` blocks to handle exceptions gracefully. Note that only terminating errors are caught, so use `-ErrorAction Stop`.

```powershell
try {
    # Stop error allows Catch to trigger
    Get-Item "C:\Missing.txt" -ErrorAction Stop
}
catch [System.IO.FileNotFoundException] {
    Write-Warning "File specifically not found."
}
catch {
    Write-Error "An unexpected error occurred: $_"
}
finally {
    Write-Host "Cleanup operations (runs regardless of error)..."
}
```

---
Return to [[programming/PowerShell/PowerShell|PowerShell Comprehensive Guide]]