Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save macnotes/e616deb88fabd876844db4c4242d162f to your computer and use it in GitHub Desktop.
Save macnotes/e616deb88fabd876844db4c4242d162f to your computer and use it in GitHub Desktop.
Example Script Demonstrating Jamf Pro Customer API Powershell (Create and then delete a Mobile Device)
# Use Jamf Customer API to create a Jamf Mobile Device record then delete it.
# v1 osl/jamf 2018-03-26
# Settings...
$ErrorActionPreference = "Stop"
$printDebugInfo = $true # $true or $false
# An extension attribute name into which we will save a dummy value.
# This must exist in the target JSS
$ExtensionAttributeName="CA_ActiveSync-ExchangeID"
$user = 'user'
$pass = 'password'
$base = 'https://organization.jamfcloud.com'
# Security/Safety: JSS Account used should have no more permissions than necessary
# code...
function Write-Debug {
param (
[string]$msg
)
if ($printDebugInfo) {
Write-Host $msg
}
}
$dateTimeStamp = Get-Date -Format "yyyyMMdd_HHmmss"
Write-Host "[start] Starting at $dateTimeStamp"
Write-Host "[step] Setting TLS Level..."
Write-Debug "[info] Reading Security Protocol before setting to TLS 12: "
$tlsVersion = [System.Net.ServicePointManager]::SecurityProtocol
if ( $tlsVersion -eq 'Tls12') {
Write-Debug -msg 'TLS 1.2 is already available'
}else{
Write-Debug "[info]TLS is $tlsVersion -- Setting v1.2..."
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Write-Debug -NoNewline "[info] Reading Security Protocol after setting to TLS 12: "
[System.Net.ServicePointManager]::SecurityProtocol
}
Write-Host "[step] Posting a new Mobile Device to $base"
$DeviceID = "0"
$Endpoint = "${base}/JSSResource/mobiledevices/id/$DeviceID"
$Method = "POST"
$payload = @"
<?xml version="1.0" encoding="UTF-8"?>
<mobile_device>
<general>
<display_name>api-${dateTimeStamp}</display_name>
<udid>api-${dateTimeStamp}</udid>
<serial_number>api-${dateTimeStamp}</serial_number>
</general>
</mobile_device>
"@
Write-Host "> Sending Device Data to ${Endpoint}"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
try {
$response = Invoke-RestMethod -URI "${Endpoint}" -Credential $credential -Method $Method -ContentType "text/xml" -Headers @{"accept"="application/xml"} -Body $payload -SessionVariable cookieJar
Write-Host "[status] OK"
} catch {
If ($_.Exception.Response.StatusCode.value__) {
$statuscodevalue = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim(); # (the double _ on value__ is intentional.)
Write-Output "[Error]HTTP Status Code: $statuscodevalue";
}
If ($_.Exception.Response.StatusDescription) {
$description = ($_.Exception.Response.StatusDescription).ToString().Trim();
Write-Host "[Error]HTTP Status Description: $description"
}
If ($_.Exception.Message) {
$message = ($_.Exception.Message).ToString().Trim();
Write-Output "[Error]HTTP Message: $message";
}
If ($_.ErrorDetails.Message) {
$ResponseBody = ($_.ErrorDetails.Message).ToString().Trim();
$ResponseBody = $ResponseBody -replace "\s+", " ";
Write-Output "[Error]HTTP Response: $ResponseBody";
}
# Write-Debug "--"
# Write-Output "[error] raw list:";
# $_.Exception | Format-List -Force
# # If you want to show the html-formatted error message returned by the API, you could do this...
# # (Invoke-WebRequest -URI "${LookupURL}" -Credential $credential -UseBasicParsing).Content
exit
}
$cookies = $cookieJar.Cookies.GetCookies($Endpoint)
foreach ($cookie in $cookies) {
Write-Debug "Cookie : $($cookie.name) = $($cookie.value)"
# APBALANCEID is what you get when you run on jamfcloud
}
# In subsequent API calls, we can add -WebSession $cookieJar to re-use that session info.
Write-Debug "--"
Write-Debug "[debug] Raw API Query Response:"
Write-Debug $response.OuterXml
Write-Debug "--"
Write-Host "Converting API response to PS XML object"
try {
# $xml = ([xml]($response)).mobile_device.id
$xml = ([xml]($response)).mobile_device
Write-Host "[status] OK"
} catch {
Write-Host "[status] Error parsing XML"
# Discovering the full type name of an exception
Write-Host "[Error]" $_.Exception.gettype().fullName
Write-Host "[Error]" $_.Exception.message
return
}
$DeviceID = $xml.id
Write-Debug '--'
Write-Debug "[debug] The jss id of the newly created record: $DeviceID"
Write-Host "==============================================================="
Write-Host "[step] Deleting the Mobile Device we just created"
$Endpoint = "${base}/JSSResource/mobiledevices/id/$DeviceID"
$Method = "DELETE"
Write-Host "> Sending Delete method to ${Endpoint}"
try {
$response = Invoke-RestMethod -URI "${Endpoint}" -Credential $credential -Method $Method -Headers @{"accept"="application/xml"} -WebSession $cookieJar
Write-Host "[status] OK"
} catch {
If ($_.Exception.Response.StatusCode.value__) {
$statuscodevalue = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim(); # (the double _ on value__ is intentional.)
Write-Output "[Error]HTTP Status Code: $statuscodevalue";
}
If ($_.Exception.Response.StatusDescription) {
$description = ($_.Exception.Response.StatusDescription).ToString().Trim();
Write-Host "[Error]HTTP Status Description: $description"
}
If ($_.Exception.Message) {
$message = ($_.Exception.Message).ToString().Trim();
Write-Output "[Error]HTTP Message: $message";
}
If ($_.ErrorDetails.Message) {
$ResponseBody = ($_.ErrorDetails.Message).ToString().Trim();
$ResponseBody = $ResponseBody -replace "\s+", " ";
Write-Output "[Error]HTTP Response: $ResponseBody";
}
# Write-Debug "--"
# Write-Output "[error] raw list:";
# $_.Exception | Format-List -Force
# # If you want to show the html-formatted error message returned by the API, you could do this...
# # (Invoke-WebRequest -URI "${LookupURL}" -Credential $credential -UseBasicParsing).Content
exit
}
Write-Debug "--"
Write-Debug "[debug] Raw API Query Response:"
Write-Debug $response.OuterXml
Write-Debug "--"
Write-Host "Converting API response to PS XML object"
try {
# $xml = ([xml]($response)).mobile_device.id
$xml = ([xml]($response)).mobile_device
Write-Host "[status] OK"
} catch {
Write-Host "[status] Error parsing XML"
# Discovering the full type name of an exception
Write-Host "[Error]" $_.Exception.gettype().fullName
Write-Host "[Error]" $_.Exception.message
return
}
$DeviceID = $xml.id
Write-Debug '--'
Write-Debug "[debug] The jss id of the deleted device record: $DeviceID"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment