2

I'm trying to output a list of items pulled from an API we use to connect to our MDM console. I have two functions, both of which work together and I can see all the data in the output of the script, however, I would like to sort this data into a .csv file using the variable names from one of the functions as the column headers. I'm new to PS and have been pulling my hair out. I can see that the variable is an array and all the values in there, but have zero idea how to sort if or if there is a better way to grab the data I need.

    #Current MDM Environment
    $ev = "Q"

    #Define MDM credentials to match environment from above
    if($ev -eq "Q")
    {
    $Code = 'VbvmMGOV0Pd2lF4GurpBqnwD/R6mFmUKI6z3CKAY5tw='
    $ui = 'MDMqualserver'
    }
    else{$Code = 'Pe8w/3jDREgse2gUu3UYZ28FHeafg0xcheu/AYwJ6PE='
    $ui = 'MDMprodserver'}#>


    #API Auth for MDM Console
    $Auth = Get-Content -path 'C:\ProgramData\ScriptAuth\mobilityapi.txt'

    $Contenttype = 'application/json'

    $CurrentDate = Get-Date
    $CurrentDate = $CurrentDate.ToString('MM-dd-yyyy')

    $path = "C:\users\username\desktop\$currentDate.csv"

    Function get_all
    {
    $array =@()

    #Define URL
    $url = "https://$ui.company.gov/api/mdm/devices/extensivesearch? 
    pagesize=10000"

    #Define Headers
    $headers = New-Object "System.Collections.Generic.Dictionary[[String], 
    [String]]"
    $headers.Add("aw-tenant-code", $Code)
    $headers.Add("Authorization", $Auth)

    #Send Rest Request
    try{
    $response = Invoke-RestMethod -uri $url -Headers $headers}
    catch{
    $error = "BDevice Info Not Found"}

    #Close Connection
    $ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($url)
    $SSP = $ServicePoint.CloseConnectionGroup("")
    #Parse Device Info
    $data = $response.DeviceExtensiveSearchResult.Devices.DeviceDetailsExt

    $data | foreach {
    $serial = $_.SerialNumber
    $array += $serial
    }
    return $array
    }

    Function get_devattrib
    {
    Param([string]$serial)

    $array = @()

    #Define URL
    $url = "https://$ui.company.gov/api/mdm/devices? 
    searchby=Serialnumber&id=$serial"

    #Define Headers
    $headers = New-Object "System.Collections.Generic.Dictionary[[String], 
    [String]]"
    $headers.Add("aw-tenant-code", $Code)
    $headers.Add("Authorization", $Auth)
    $headers.Add("Content-Type", $Contenttype)

    #Send Rest Request
    try{
    $response = Invoke-RestMethod -uri $url -Headers $headers}
    catch{
    return $false}

    #Close Connection
    $ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($url)
    $ServicePoint.CloseConnectionGroup("")

    #Parse Device Info (#removed .Device from $data = $response.Device)
    $data = $response

    $data | foreach {
    $ownership = $_.Ownership 
    $friendlyname = $_.DeviceFriendlyName
    $platform = $_.Platform 
    $model = $_.Model 
    $snumber = $_.AssetNumber
    $username = $_.UserName
    $mac = $_.MacAddress
    $phone = $_.PhoneNumber
    $lastseen = $_.LastSeen
    $enrollstatus = $_.EnrollmentStatus
    $compliance = $_.ComplianceStatus 


    return [datetime]$lastseen, $ownership, $friendlyname, $platform, $model, 
    $snumber, $serial, $username, $mac, $phone, $enrollstatus, $compliance
    }
    }

    $devices = @()
    $getdevices = @()

    $devices = get_all 

    foreach ($device in $devices){

       $getdevices += get_devattrib $device  
    }

    $getdevices 

The output of the data looks like this for each device in our console (I have made the info generic to hide company data):

True

Wednesday, September 5, 2018 8:33:21 PM Corporate Owned username - assetnumber Apple iPad Pro with Wi-Fi + Cellular (128 GB Space Gray) asset number serial nubmer username mac address phonenumber Enrolled NonCompliant

A. I don't understand why I get "true" at the beginning of the output for each device in the console and the space afterwards (which seems to come with the [datetime])

B. I don't understand how to place all this data in a .csv file. I do have a path defined before the functions and know how to use export-csv, but the data that it sends to the file appears as just #TYPE System.Boolean so I'm assuming there is something wrong with my last variable. Whew.

3
  • 1
    this line $ServicePoint.CloseConnectionGroup("") looks like it may return something. have you checked to see if that is the source of the True? ///// the way to get the data into a CSV file is to keep it as an array of objects OR to build an array of custom objects. you have broken the "object-ness" with the $data | foreach { section where you disassemble the object into individual $Vars. [grin] Commented Nov 28, 2018 at 23:14
  • @Lee_Dailey it does indeed ([System.Net.ServicePoint].GetMethod('CloseConnectionGroup').ReturnType) Commented Nov 28, 2018 at 23:23
  • @MathiasR.Jessen - thank you for the confirmation! i appreciate it ... and so will the OP. [grin] Commented Nov 28, 2018 at 23:33

1 Answer 1

11

You can sort with Sort-Object.

$ArrayOfStrings = 's', 't', 'a', 'c', 'k'
$ArrayOfStrings | Sort-Object
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the helpful comments guys. I am going to attempt what Lee_Dailey has suggested an "unbreak" the array and sort it out later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.