Skip to content

Instantly share code, notes, and snippets.

@InputObject2
Created April 22, 2018 17:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InputObject2/4cf9c471778feba59ff33df4b1b54a17 to your computer and use it in GitHub Desktop.
Save InputObject2/4cf9c471778feba59ff33df4b1b54a17 to your computer and use it in GitHub Desktop.
Param(
[Parameter(Mandatory=$false)][switch]$shutdown=$false,
[Parameter(Mandatory=$false)][switch]$vm=$false
)
# Powershell refuses to connect to the Netbox API on our setup without this.
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Some useful settings.
$token = "TOKEN"
$uri = "https://netbox.domain.com/api"
# Set API Headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Token $token")
$headers.Add("Content-Type", 'application/json')
$headers.Add("Accept", 'application/json')
# We check if the machine is a VM or a physical box using the parameter $VM.
if($vm) {
$MachineID = ((Invoke-WebRequest -uri "$uri/virtualization/virtual-machines/?q=$(hostname)" -Method Get -Headers $headers).content | convertfrom-json).results[0].id
# If $shutdown is false, the machine just turned on. Else we're turning off!
if(-not $shutdown) {Invoke-WebRequest -Uri "$uri/virtualization/virtual-machines/$MachineID/" -Method PATCH -Headers $headers -Body $(@{status=1}| ConvertTo-Json)}
else {Invoke-WebRequest -Uri "$uri/virtualization/virtual-machines/$MachineID/" -Method PATCH -Headers $headers -Body $(@{status=0}| ConvertTo-Json)}
}
else {
$MachineID = ((Invoke-WebRequest -uri "$uri/dcim/devices/?q=$(hostname)" -Method Get -Headers $headers).content | convertfrom-json).results[0].id
$MachineID
# If $shutdown is false, the machine just turned on. Else we're turning off!
if(-not $shutdown) {Invoke-WebRequest -Uri "$uri/dcim/devices/$MachineID/" -Method PATCH -Headers $headers -Body $(@{status=1}| ConvertTo-Json)}
else {Invoke-WebRequest -Uri "$uri/dcim/devices/$MachineID/" -Method PATCH -Headers $headers -Body $(@{status=0}| ConvertTo-Json)}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment