Powershell script issue

roiegat
Contributor III

So I've been working with our account create team and they wanted to monitor Macs that have admin on them. So we have a process where a person request admin access and if they are granted it, the account creation team creates a special ID for them and creates a special role for that machine. The part they can't do is run the script on the Mac to tell it that new role group is managing it. So I wrote a powershell script while we were in 9.8 that basically asked them for a computer name and uploaded that name into a static group. That static group has a policy bound to it that runs the scripts that does the work.

The script is based off a Powershell script I found here by Corey Thomas, and heavilty modified. It worked great in 9.8, but since we've updated to 9.82 - a lot has changed. Seems that some tables and data is in different locations. So I went through the script and managed to fix almost everything. The only error I'm getting now is during the upload part. Since I can't figure why I'm getting the error...figured I'd ask for help.

Here's the script scrubbed for security:

#========================================================================
# Created by:   Corey Thomas, Modified by Roie Gat
# Organization: Removed for privacy
# Version :   1.4  
#========================================================================

### Pre-reqs:  Create a standard user account for JSS (full access, custom privileges) and grant it read/update to the JSS Objects.  Specify this account below

$JSSAPIURL = "https://XXXXXX.XXXXXXX.com:8443/JSSResource"
$JSSAPIUser = "XXXXXXX"
$JSSAPIPass = "XXXXXXX"
$JSSGroupName = "GROUPNAME"
$VerbosePreference = "SilentlyContinue"  #Optional for extra logging - Change to "Continue"


#First we need to setup the shell to ignore self-signed certs for non-PKI Casper installs:
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

#Next we setup the creds we will be using:
$user = $JSSAPIUser
$pass = ConvertTo-SecureString -String $JSSAPIPass -AsPlainText -Force
$Creds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $user, $pass

$MachineTNumber = Read-Host -Prompt 'Enter name of machine'

#Get group info:
$url = "$JSSAPIURL/computergroups/name/$JSSGroupName"
$groupinfo = Invoke-RestMethod -Uri $url -Credential $Creds

$groupnumber = $groupinfo.computer_group.id
$groupname = $groupinfo.computer_group.name
$groupsize=$groupinfo.computer_group.computers.Count

##check to see if machine is already in the list....
foreach($machine in $groupinfo.computer_group.computers.comp){
$testId = $machine.Name
 If ($testId -eq $MachineTNumber) 
 {
    Write-Output ""
    Write-Output "Computer Already in Group, exit script."
    Write-Output ""
    exit
    }
}


##if not then

#Get Computer info:
$url = "$JSSAPIURL/computers/name/$MachineTNumber"

try {
    $computerinfo = Invoke-RestMethod -Uri $url -Credential $Creds
} catch {
    # Make Sure we got back computer information
    If ($_.Exception.Response.StatusDescription -eq "Not Found") 
    {
        Write-Output ""
        Write-Output "Computer Data Not Found, exit script."
        Write-Output ""
        exit
    }
}

$compid = $computerinfo.computer.general.id
$compname = $computerinfo.computer.general.name
$compmacadd = $computerinfo.computer.general.mac_address
$compaltadd = $computerinfo.computer.general.alt_mac_address
$compserial = $computerinfo.computer.general.serial_number

#create clone to populate new data
$element=$groupinfo.computer_group.computers[0]
$element.id = $compid
$element.name = $compname
$element.mac_address = $compmacadd
$element.alt_mac_address = $compaltadd
$element.serial_number = $compserial

#Add data to xml file now
$groupinfo.computer_group.computers+=$element

#upload data
Write-Output ""
Write-Output ""
Write-Output "Uploading Data"
$url = "$JSSAPIURL/computergroups/name/$JSSGroupName"
$result = Invoke-RestMethod -Uri $url -Credential $Creds -Method Put -Body $groupinfo

Quick breakdown of what it does:
1) Gets computer name for user.
2) Checks to see if that computer is already on the static list.
3) Checks to make sure the computer is valid, and if it is, gets the data needed.
4) Uploads the data to Casper.

The last line is what's giving off the error in 9.82. The error it gets is (again scrubbed for security sake):

Invoke-RestMethod : Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request
You can get technical details here.
Please continue your visit at our home page. 
At XXX:XXXXXXXXX.ps1:98 char:11
+ $result = Invoke-RestMethod -Uri $url -Credential $Creds -Method Put -Body $grou ...
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Looking at the array it adds the computer into it looks ok. I can even use the count command to see that it did in fact add a record to the array. So any idea how to fix the upload issue?

Overall, I'm kinda of liking Powershell for doing things with the API. I have about 6 scripts total to do different things and it is nice to work with overall.

1 REPLY 1

mjames
Contributor

Hi Roiegat,

Did you ever find a solution for this? We are seeing something similar with our scripts now too...

thanks

Matt