Heute mal ein paar kleine Beispiele wie man mittels PowerShell und dessen Invoke-RestMethod Cmdlet eine WordPress Webseite über deren REST API Schnittstelle automatisieren kann, incl. Beispiel für Basic Authentication und das erstellen neuer Posts. Damit das Beispiel funktionieren kann, muss die REST API in der WordPress Site aktiviert sein, und eine passende Authentifizierungsmodus konfiguriert sein.
Weitere Information über die API Funktionen findet man unter https://developer.wordpress.org/rest-api/
# Working against a REST API with basic authentication
$PrimaryUri = 'https://www.YourDomain.de'
$SecureString = Read-Host -AsSecureString 'Enter password'
$APIPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto( [Runtime.InteropServices.Marshal]::SecureStringToBSTR( $SecureString))
$APIUserName = "YourUserName"
$Header = @{Authorization = -join ("Basic ", [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("$APIUserName`:$APIPassword"))))}
$Header
# Get title of the start page posts
$Response = Invoke-RestMethod -Method Get -Uri "$PrimaryUri/wp-json/wp/v2/posts?page=1" -Headers $Header
$Response.title.rendered
# Get posts via search
$Response = Invoke-RestMethod -Method Get -Uri "$PrimaryUri/wp-json/wp/v2/posts?search=YourSearchString" -Headers $Header
$Response.title.rendered
# Get all categories
$Response = Invoke-RestMethod -Uri "$PrimaryUri/wp-json/wp/v2/categories/" -Headers $Header
$Response | Select-object id,name,link
# Get site settings
$Response = Invoke-RestMethod -Uri "$PrimaryUri/wp-json/wp/v2/settings" -Headers $Header
$Response | Format-list
# Create a new post
$body = [ordered] @{
title = 'My title'
status = 'draft'
content = '<h1>my headlile</h1>my content with some bla bla text'
excerpt = 'a short excerpt'
format = 'standard'
} | ConvertTo-Json
$Response = Invoke-RestMethod -Method Post -Uri "$PrimaryUri/wp-json/wp/v2/posts" -Headers $Header -Body $body -ContentType 'application/json'