Yep! I'm actually running PowerShell on my Mac where I do all my other development work. 😉
That earlier code is kind of gross. Global variables and all that. I only spent ~20 minutes writing and testing it, though. Here's a version with somewhat better encapsulation:
class CheckPointApiConnection {
[String]$ManagementServer
hidden [String]$CheckPointApiSid = ""
CheckPointApiConnection(
[String]$mgmtServer,
[String]$User,
[String]$Pass,
[Boolean]$readOnly
) {
$this.ManagementServer = $mgmtServer
$loginBody = @{user=$User;password=$Pass;"read-only"=$readOnly}
$loginResult = $this.ApiCall("login", $loginBody, $false)
$this.CheckPointApiSid = $loginResult["sid"]
}
[Hashtable] ApiCall(
[String]$ApiPoint
) {
return $this.ApiCall($ApiPoint, @{}, $false)
}
[Hashtable] ApiCall(
[String]$ApiPoint,
[Hashtable]$Body
) {
return $this.ApiCall($ApiPoint, $Body, $false)
}
[Hashtable] ApiCall(
[String]$ApiPoint,
[Boolean]$PrintResult
) {
return $this.ApiCall($ApiPoint, @{}, $PrintResult)
}
[Hashtable] ApiCall(
[String]$ApiPoint,
[Hashtable]$Body,
[Boolean]$PrintResult
) {
$CallResult = Invoke-WebRequest `
-Uri "https://$($this.ManagementServer)/web_api/${ApiPoint}" `
-ContentType "application/json"`
-Method POST `
-Headers @{"x-chkp-sid"=$($this.CheckPointApiSid)} `
-Body $($Body | ConvertTo-Json -Compress) `
-SkipCertificateCheck
if ($apiPoint -eq "logout") {
$this.CheckPointApiSid = ""
}
if ($PrintResult) {
Write-Host "${ApiPoint} result:`n${CallResult}`n"
}
return ($CallResult | ConvertFrom-Json -AsHashtable)
}
}
$apiConnection = [CheckPointApiConnection]::new("192.168.65.2", "my_username", "secret", $false)
$newHostBody = @{name="new host name";"ip-address"="192.168.1.1"}
$newHostResult = $apiConnection.ApiCall("add-host", $newHostBody, $true)
$publishResult = $apiConnection.ApiCall("publish", $true)
$logoutResult = $apiConnection.ApiCall("logout", $true)
I'm not as familiar with methods in PowerShell objects as I am with functions. It feels like all those signatures for ApiCall could probably be consolidated down with optional arguments, or default values. I'm not sure if I can add argument names to method calls. That would cost a little verbosity, but greatly improve clarity at the call site.
This also doesn't have any error handling or disposal handling. For example, if you remove the object for the API connection, it should call logout to cleanly close the session on the management side.