Write an SIE script in PowerShell
PowerShell 7 runs on Linux, so teams that already script in PowerShell can write SIE scripts in it. It’s comfortable with REST APIs and JSON. It needs a little care to keep progress messages off stdout.
Good for
- Teams whose scripting is in PowerShell.
- REST APIs, including Microsoft and Windows management APIs.
Set it up
Install PowerShell 7 from Microsoft’s package repository for your OS; Microsoft’s “Install PowerShell on Linux” page has the steps. Then check the path:
which pwsh # usually /usr/bin/pwshThe command
/usr/bin/pwsh -NoProfile -NonInteractive -File {script_path}my-script.ps1 {device_ip} {device_username} {device_password}-NoProfile stops a profile script changing behaviour, and -NonInteractive makes a prompt fail instead of waiting.
A minimal script
This one reads a JSON config from an HTTPS API with Basic authentication:
# Minimal SIE script in PowerShell: fetch a JSON config over HTTPS.## Usage: pwsh -File powershell-skeleton.ps1 <host> <username> <password>
param( [Parameter(Mandatory)] [string] $DeviceHost, [Parameter(Mandatory)] [string] $Username, [Parameter(Mandatory)] [string] $Password)
$ErrorActionPreference = 'Stop'$ProgressPreference = 'SilentlyContinue'
function Note([string] $Message) { [Console]::Error.WriteLine($Message) }function Fail([string] $Message) { [Console]::Error.WriteLine("ERROR: $Message"); exit 1 }
$uri = "https://$DeviceHost/api/config" # adapt for your device$pair = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("${Username}:${Password}"))
Note "fetching config from $DeviceHost"try { $data = Invoke-RestMethod -Uri $uri -Headers @{ Authorization = "Basic $pair" } -TimeoutSec 30} catch { Fail "request to $DeviceHost failed: $($_.Exception.Message)"}
if ($null -eq $data) { Fail "empty config, refusing to store it" }
# ConvertTo-Json keeps the API's key order and stops at depth 2 unless told otherwise.[Console]::Out.Write(($data | ConvertTo-Json -Depth 50) + "`n")Note "SIE-OK: powershell config from $DeviceHost"exit 0Habits that matter in PowerShell
[Console]::Error.WriteLinefor progress.Write-HostandWrite-Outputboth reach stdout when run this way, so they’d be stored.-DepthonConvertTo-Json. The default depth is 2, which silently cuts nested settings off.exit 1on failure. An uncaught error ends the script, but set the exit code yourself so the failure is always clear.$ProgressPreference = 'SilentlyContinue'. Progress bars from web cmdlets add noise to the output streams.
Related
- Python for the same job with no extra runtime
- HTTP APIs: curl and requests