skyline-comm.ps1

function displayusage {
    ''
    'USAGE: skyline-comm ARG VARIABLE' 
    ' (arg1): [prep]'
    ' (arg2): [get-access-token]'
    ' (arg3): [get-findings list|listmore|listlong] [send2slack|send2servicenow|send2jira|send2csv]'
    ' (arg4): [get-findings detail|longdetail findingid source] [send2slack|send2servicenow|send2jira|send2csv]'
    ' (arg5): [get-findings top 5|10|50|200] [send2slack|send2servicenow|send2jira|send2csv]'
    ' (arg6): [get-findings custom] [send2slack|send2servicenow|send2jira]'
    ' (arg7): [get-findings search VALUE]'
    ' (arg8): [get-findings detailall FILE.CSV] [send2slack|send2servicenow|send2jira|send2csv]'
    ' (arg9): [get-findings category SECURITY|NETWORK|COMPUTE|STORAGE] [send2slack|send2servicenow|send2jira|send2csv]'
    ' (arg10): [get-findings type CONFIGURATION|UPGRADE] [send2slack|send2servicenow|send2jira|send2csv]'
    ' (arg11): [get-findings severity CRITICAL|MODERATE|TRIVIAL] [send2slack|send2servicenow|send2jira|send2csv]'
    ' (arg12): [email SMTP-SERVER FROM-EMAIL TO-EMAIL FILE.CSV]'
    ' (arg13): [misc API-PATH]'
    ''
}

function jiraint {
    write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-jira.csv"
    buildCSV

    send3jira
}

function servicenowint {
    write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-servicenow.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings | foreach-object {
     add-content $filecsv $_
    }
    send3servicenow
}

function slackint {
    write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-slack.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings | foreach-object {
     add-content $filecsv $_
    }
    send3slack
}

function buildCSV {
    if (-not(Test-Path -Path $filecsv -PathType Leaf)) {
         try {
             $null = New-Item -ItemType File -Path $filecsv -Force -ErrorAction Stop
         }
         catch {
             throw $_.Exception.Message
         }
    }
    clear-content $filecsv
}

function listmoreint {
                 add-content $file2 '{ "query" : "'
            add-content $file2 '{'
            add-content $file2 ' activeFindings(limit: 200) {'
            add-content $file2 ' findings {'
            add-content $file2 ' findingId'
            add-content $file2 ' products'
            add-content $file2 ' totalAffectedObjectsCount'
            add-content $file2 ' }'
            add-content $file2 ' totalRecords'
            add-content $file2 ' timeTaken'
            add-content $file2 ' }'
            add-content $file2 '}'
            add-content $file2 '"}'
}

function listmoreint2 {
    $file2 = "skyline.json"
    if (Test-Path $file2) {
      clear-content $file2
    }

                 add-content $file2 '{ "query" : "'
            add-content $file2 '{'
            add-content $file2 " activeFindings(limit: 200, start: $STARTX) {"
            add-content $file2 ' findings {'
            add-content $file2 ' findingId'
            add-content $file2 ' products'
            add-content $file2 ' totalAffectedObjectsCount'
            add-content $file2 ' }'
            add-content $file2 ' totalRecords'
            add-content $file2 ' timeTaken'
            add-content $file2 ' }'
            add-content $file2 '}'
            add-content $file2 '"}'
}

function InvokeRest {
    $file = checkfile
    . $file
    $MYTOKEN2 = getaccesstoken2
    $FINDINGS = invoke-restmethod -method post -Uri "$ACCESSSERVER" -Headers @{Authorization = "Bearer $MYTOKEN2"} -sessionvariable "SkylineAutomationToolkit" -infile skyline.json -ContentType "application/json"

return $FINDINGS.data.activeFindings.findings
}


function listint  {
    $file2 = "skyline.json"
    if (Test-Path $file2) {
      clear-content $file2
    }


      switch ($CHOICE2) {
       "list" {
             add-content $file2 '{ "query" : "'
        add-content $file2 '{'
        add-content $file2 ' activeFindings(limit: 200) {'
        add-content $file2 ' findings {'
        add-content $file2 ' findingId'
        add-content $file2 ' products'
        add-content $file2 ' totalAffectedObjectsCount'
        add-content $file2 ' }'
        add-content $file2 ' }'
        add-content $file2 '}'
        add-content $file2 '"}'

        $SENDX = $CHOICE3
        }

       "listmore" {
            listmoreint

            $SENDX = $CHOICE3
        }

        "listlong" {
        genjson
        $SENDX = $CHOICE3
        }

        "top" {
        topjson
        $SENDX = $CHOICE4
      }

        "category" {
        categoryjson
        $SENDX = $CHOICE4
        }

        "type" {
        typejson
        $SENDX = $CHOICE4
      }

        "severity" {
        severityjson
        $SENDX = $CHOICE4
      }
    }

    InvokeRest

 switch ($SENDX) {
 "send2slack" { slackint } 
 
  "send2servicenow" { servicenowint }  

  "send2jira" { jiraint }

  "send2csv" {
    switch ($CHOICE2) {
    "list" {
    write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-getfinding-list.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings | select findingId, @{name="products"; expression={$_.products}}, totalAffectedObjectsCount | export-csv $filecsv -notypeinformation
     }

     "listlong" {
    write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-getfinding-listlong.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings  | select findingId, accountId, findingDisplayName, severity, @{name="products"; expression={$_.products}}, findingDescription , findingImpact, @{name="recommendations"; expression={$_.recommendations}},  @{name="kbLinkURLs"; expression={$_.kbLinkURLs}}, @{name="recommendationsVCF"; expression={$_.recommendationsVCF}}, @{name="kbLinkURLsVCF"; expression={$_.kbLinkURLsVCF}}, categoryName, @{name="findingTypes"; expression={$_.findingTypes}}, @{name="firstObserved"; expression={$_.firstObserved}}, totalAffectedObjectsCount | export-csv $filecsv -notypeinformation
     }
    
     "top" {
    write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-getfinding-top.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings | select findingId, @{name="products"; expression={$_.products}}, totalAffectedObjectsCount | export-csv $filecsv -notypeinformation
     }

     "category" {
         write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-getfinding-category.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings | select findingId, @{name="products"; expression={$_.products}}, totalAffectedObjectsCount | export-csv $filecsv -notypeinformation
     }

     "type" {
         write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-getfinding-type.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings | select findingId, @{name="products"; expression={$_.products}}, totalAffectedObjectsCount | export-csv $filecsv -notypeinformation
     }

     "severity" {
    write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-getfinding-severity.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings | select findingId, @{name="products"; expression={$_.products}}, totalAffectedObjectsCount | export-csv $filecsv -notypeinformation
     }
    }
    
   }

  default {
    
    switch ($CHOICE2) {
    "listmore" {
    $TotalRecords = $FINDINGS.data.activeFindings.totalRecords
    
    $CurrentCount = 0
    while ($CurrentCount -lt $TotalRecords) {
        $STARTX = $CurrentCount
        listmoreint2        

        InvokeRest

        write-output $FINDINGS.data.activeFindings.findings

        $CurrentCount = $CurrentCount + 200
    }

    }
    default {
    write-output $FINDINGS.data.activeFindings.findings
     }
    }

  }
 }

}



function detailint {
    $file2 = "skyline.json"
    if (Test-Path $file2) {
      clear-content $file2
    }

    detailjson

    InvokeRest

 switch ($CHOICE5) {
 "send2slack" {

    write-output $FINDINGS.data.activeFindings.findings.affectedObjects

    $filecsv = "skyline-slack.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings.affectedObjects | foreach-object {
     add-content $filecsv $_
    }
    send3slack
    
  } 
 
  "send2servicenow" {
    write-output $FINDINGS.data.activeFindings.findings.affectedObjects

    $filecsv = "skyline-servicenow.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings.affectedObjects | foreach-object {
     add-content $filecsv $_
    }
    send3servicenow
   }  

  "send2jira" {
    write-output $FINDINGS.data.activeFindings.findings

    $filecsv = "skyline-jira.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings.affectedObjects | foreach-object {
     add-content $filecsv $_
    }
    send3jira
   }


  "send2csv" {
    switch ($CHOICE2) {
    "detail" {
    write-output $FINDINGS.data.activeFindings.findings.affectedObjects

    $filecsv = "skyline-getfinding-details.csv"
    buildCSV

    $FINDINGS.data.activeFindings.findings.affectedObjects | select sourceName, objectName | export-csv $filecsv -notypeinformation
     }

     "longdetail" {
    write-output $FINDINGS.data.activeFindings.findings    

    $filecsv = "skyline-getfinding-longdetails.csv"
    if (-not(Test-Path -Path $filecsv -PathType Leaf)) {
         try {
             $null = New-Item -ItemType File -Path $filecsv -Force -ErrorAction Stop
         }
         catch {
             throw $_.Exception.Message
         }
    }
    #clear-content $filecsv

    $FINDINGS.data.activeFindings.findings.affectedObjects | foreach-object {
     $sourceX = $_.sourceName
     $objectX = $_.objectName
    
    $FINDINGS.data.activeFindings.findings | select findingId, accountId, findingDisplayName, severity, @{name="products"; expression={$_.products}}, findingDescription, findingImpact, @{name="recommendations"; expression={$_.recommendations}}, @{name="kbLinkURLs"; expression={$_.kbLinkURLs}}, @{name="recommendationsVCF"; expression={$_.recommendationsVCF}}, @{name="kbLinkURLsVCF"; expression={$_.kbLinkURLsVCF}}, categoryName, @{name="findingTypes"; expression={$_.findingTypes}}, @{name="firstObserved"; expression={$_.firstObserved}}, totalAffectedObjectsCount, @{name="affectedObjects.sourceName"; expression={$sourceX}}, @{name="affectedObjects.objectName"; expression={$objectX}} | export-csv $filecsv -notypeinformation -append
    }
     }
    }
   }


  default {
   switch ($CHOICE2) {
    "detail" {
    write-output $FINDINGS.data.activeFindings.findings.affectedObjects
    }
    "longdetail" {
    write-output $FINDINGS.data.activeFindings.findings
     }
    }
  }
 }

}

function detailjson {
    add-content $file2 '{ "query" : "'
    add-content $file2 '{'
    add-content $file2 ' activeFindings('
    add-content $file2 ' filter: {'
    add-content $file2 " findingId: `\`"$CHOICE3`\`","
    add-content $file2 " product: `\`"$CHOICE4`\`""
    add-content $file2 ' }'
    add-content $file2 ' limit: 200) {'
    add-content $file2 ' findings {'
    add-content $file2 ' findingId'
    add-content $file2 ' accountId'
    add-content $file2 ' findingDisplayName'
    add-content $file2 ' severity'
    add-content $file2 ' products'
    add-content $file2 ' findingDescription'
    add-content $file2 ' findingImpact'
    add-content $file2 ' recommendations'
    add-content $file2 ' kbLinkURLs'
    add-content $file2 ' recommendationsVCF'
    add-content $file2 ' kbLinkURLsVCF'
    add-content $file2 ' categoryName'
    add-content $file2 ' findingTypes'
    add-content $file2 ' firstObserved'
    add-content $file2 ' totalAffectedObjectsCount'
    add-content $file2 ' affectedObjects(start: 0, limit: 200) {'
    add-content $file2 ' sourceName'
    add-content $file2 ' objectName'
    add-content $file2 ' }'
    add-content $file2 ' }'
    add-content $file2 ' totalRecords'
    add-content $file2 ' timeTaken'
    add-content $file2 ' }'
    add-content $file2 '}'
    add-content $file2 '"}'
}


function genjson {
    add-content $file2 '{ "query" : "'
    add-content $file2 '{'
    add-content $file2 ' activeFindings(limit: 200) {'
    add-content $file2 ' findings {'
    add-content $file2 ' findingId'
    add-content $file2 ' accountId'
    add-content $file2 ' findingDisplayName'
    add-content $file2 ' severity'
    add-content $file2 ' products'
    add-content $file2 ' findingDescription'
    add-content $file2 ' findingImpact'
    add-content $file2 ' recommendations'
    add-content $file2 ' kbLinkURLs'
    add-content $file2 ' recommendationsVCF'
    add-content $file2 ' kbLinkURLsVCF'
    add-content $file2 ' categoryName'
    add-content $file2 ' findingTypes'
    add-content $file2 ' firstObserved'
    add-content $file2 ' totalAffectedObjectsCount'
    add-content $file2 ' }'
    add-content $file2 ' totalRecords'
    add-content $file2 ' timeTaken'
    add-content $file2 ' }'
    add-content $file2 '}'
    add-content $file2 '"}'

}


function topjson {
    add-content $file2 '{ "query" : "'
    add-content $file2 '{'
    add-content $file2 " activeFindings(limit:$CHOICE3) {"
    add-content $file2 ' findings {'
    add-content $file2 ' findingId'
    add-content $file2 ' accountId'
    add-content $file2 ' findingDisplayName'
    add-content $file2 ' severity'
    add-content $file2 ' products'
    add-content $file2 ' findingDescription'
    add-content $file2 ' findingImpact'
    add-content $file2 ' recommendations'
    add-content $file2 ' kbLinkURLs'
    add-content $file2 ' recommendationsVCF'
    add-content $file2 ' kbLinkURLsVCF'
    add-content $file2 ' categoryName'
    add-content $file2 ' findingTypes'
    add-content $file2 ' firstObserved'
    add-content $file2 ' totalAffectedObjectsCount'
    add-content $file2 ' }'
    add-content $file2 ' totalRecords'
    add-content $file2 ' timeTaken'
    add-content $file2 ' }'
    add-content $file2 '}'
    add-content $file2 '"}'
}

function typejson {
    add-content $file2 '{ "query" : "'
    add-content $file2 '{'
    add-content $file2 ' activeFindings('
    add-content $file2 ' filter: {'
    add-content $file2 " findingTypes: [$CHOICE3]" 
    add-content $file2 ' }'
    add-content $file2 ' limit: 200)'
    add-content $file2 '{'
    add-content $file2 ' findings {'
    add-content $file2 ' findingId'
    add-content $file2 ' products'
    add-content $file2 ' totalAffectedObjectsCount'
    add-content $file2 ' }'
    add-content $file2 ' }'
    add-content $file2 '}'
    add-content $file2 '"}'
}

function categoryjson {
    add-content $file2 '{ "query" : "'
    add-content $file2 '{'
    add-content $file2 ' activeFindings('
    add-content $file2 ' filter: {'
    add-content $file2 " categoryName: [$CHOICE3]" 
    add-content $file2 ' }'
    add-content $file2 ' limit: 200)'
    add-content $file2 '{'
    add-content $file2 ' findings {'
    add-content $file2 ' findingId'
    add-content $file2 ' products'
    add-content $file2 ' totalAffectedObjectsCount'
    add-content $file2 ' }'
    add-content $file2 ' }'
    add-content $file2 '}'
    add-content $file2 '"}'
}

function severityjson {
    add-content $file2 '{ "query" : "'
    add-content $file2 '{'
    add-content $file2 ' activeFindings('
    add-content $file2 ' filter: {'
    add-content $file2 " severity: [$CHOICE3]" 
    add-content $file2 ' }'
    add-content $file2 ' limit: 200)'
    add-content $file2 '{'
    add-content $file2 ' findings {'
    add-content $file2 ' findingId'
    add-content $file2 ' products'
    add-content $file2 ' totalAffectedObjectsCount'
    add-content $file2 ' }'
    add-content $file2 ' }'
    add-content $file2 '}'
    add-content $file2 '"}'
}

function getaccesstoken2 {
$Header = @{
 "Accept" = "application/json"
 "Content-Type" = "application/x-www-form-urlencoded"
}

$Body = @{
 refresh_token = "$APITOKEN"
}


$MYTOKEN = Invoke-RestMethod -method Post -Uri "$APITOKENSERVER" -Headers $Header -Body $Body

return $MYTOKEN.access_token
}

function send3servicenow {
$SNComment = get-content $filecsv 

$params = @{
    Url =  "$SERVICENOWSERVER"
    Credential = $userCred
}
New-ServiceNowSession @params

New-ServiceNowIncident -caller $SERVICENOWUSER -shortdescription "Skyline Findings - List" -comment "$SNComment"

}

function send3jira {
$JIRACONTEXT = get-content $filecsv
$filejira2 = "jira.json"

if (-not(Test-Path -Path $filejira2 -PathType Leaf)) {
 try {
  $null = New-Item -ItemType File -Path $filejira2 -Force -ErrorAction Stop
 }
 catch {
  throw $_.Exception.Message
 }
}
 clear-content $filejira2


add-content $filejira2 '{'
add-content $filejira2 ' "fields": {'
add-content $filejira2 ' "project":'
add-content $filejira2 ' {'
add-content $filejira2 ' "key": "SKYLINE"'
add-content $filejira2 ' },'
add-content $filejira2 ' "summary": "Skyline - Findings",'
add-content $filejira2 " `"description`": `"$JIRACONTEXT`" ,"
add-content $filejira2 ' "issuetype": {'
add-content $filejira2 ' "id": "3"'
add-content $filejira2 ' }'
add-content $filejira2 ' }'
add-content $filejira2 '}'

$credjira = get-credential
invoke-restmethod -method post -uri $JIRASERVER -authentication basic -credential $credjira -infile $filejira2 -contenttype "application/json"
}


function confirmX {
 $file = checkfile
 . $file

if (-not($CONFIRM -eq "NO")) 
{
 write-host ""
 write-host "Here are the changes you are about to do:"
 write-host ""
 write-host "Management Host: $VCENTER"
 write-host "Affected Host: $ESX"
 write-host "KB Reference: $KB"
 write-host "Detail: $DETAILX"
 write-host ""
 $confirmation = Read-Host "Do you want to continue (y/n)"
 return $confirmation
} else {
 $confirmation = "y"
 return $confirmation
}
}

function send3slack {
import-csv $filecsv | foreach-object {
 $Body = @{
    channel = $SLACKCHANNEL
    text = "$_"
    color = "#3AA3E3"
    attachment_type = "default"
 }

 $headers = @{Authorization = "Bearer $SLACKTOKEN"}
 Invoke-RestMethod -Method Post -Uri "https://slack.com/api/chat.postMessage" -Headers $headers -Body $body

}
}


function skyline-comm {
[CmdletBinding()] 
param(
 [string]$CHOICE1,
 [string]$CHOICE2,
 [string]$CHOICE3,
 [string]$CHOICE4,
 [string]$CHOICE5
)

switch ( $CHOICE1 )
{

prep {
$file = checkfile
    . $file

    if ($APITOKEN -eq $null)
    {
        $SAMPLEAPITOKEN = select-string -path $file -pattern APITOKEN
        if ( $SAMPLEAPITOKEN.Matches.Count -lt 1)
        {

         if (get-module -listavailable -name servicenow) { 
            write-host "...ServiceNow has already been installed..."    
            }
        else {
            install-module servicenow -force
            write-host "...install ServiceNow..."
            }

        $file2 = "skyline.json"

        add-content $file '#APITOKEN = "NEED-API-TOKEN"'
        add-content $file '#APITOKENSERVER = "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize?grant_type=refresh_token"'
        add-content $file '#ACCESSSERVER = "https://skyline.vmware.com/public/api/data"'
        add-content $file '#SLACKTOKEN = "NEED-SLACK-TOKEN"'
        add-content $file '#SLACKCHANNEL = "NEED-SLACK-CHANNEL"'
        add-content $file '#SERVICENOWSERVER = "NEED-SERVICENOW-SERVER"'
        add-content $file '#SERVICENOWUSER = "NEED-SERVICENOW-USER"'
        add-content $file '#JIRASERVER = "NEED-JIRA-SERVER"'

        genjson 

        write-host ''
        write-host "please update API entries in $file"
        write-host ''
        }
    }
}

get-this-access-token {

    $APITOKENSERVER = "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize?grant_type=refresh_token"
    $APITOKEN = $CHOICE2

    $MYTOKEN2 = getaccesstoken2
    write-output $MYTOKEN2
}

get-access-token {
     $file = checkfile
     . $file

    $MYTOKEN2 = getaccesstoken2
    write-output $MYTOKEN2
}

email {
 send-mailmessage -UseSsl -smtpserver $CHOICE2 -from $CHOICE3 -to $CHOICE4 -subject "Skyline Findings Report" -body "attach is the latest report" -credential get-credential 
}

misc {

    if ($CHOICE2 -ne "")
    {

        $file = checkfile
        . $file
        $MYTOKEN2 = getaccesstoken2
        $FINDINGS = invoke-restmethod -method get -Uri "$CHOICE2" -Headers @{Authorization = "Bearer $MYTOKEN2"} -sessionvariable "SkylineAutomationToolkit" -ContentType "application/json"

    }else{
    
    write-host ""
    write-host "USAGE: skyline-comm.ps1 misc ARG"
    write-host " https://console.cloud.vmware.com/csp/gateway/am/api/userinfo"    
    write-host " https://console.cloud.vmware.com/csp/gateway/am/api/orgs/XXXXXXXXXXX"
    write-host " https://console.cloud.vmware.com/csp/gateway/am/api/orgs/XXXXXXXXXXX/users"
    write-host ""

    }
}


get-findings {
 switch ($CHOICE2)
 {

top { listint }

list { listint }

listmore { listint }

listlong { listint }

detail { detailint }

longdetail { detailint }

category { listint }

type { listint }

severity { listint  }

detailall {
    import-csv $CHOICE3 | foreach-object {
        $CHOICE2 = "longdetail"
        $CHOICE3 = $_."findingId"
        $PRODUCTALL = $_."products"
        $CHOICE5 = "send2csv"

        foreach ($sourcex in $PRODUCTALL) {
            $sourcey = $sourcex -split " "
            foreach ($sourcez in $sourcey) {
                $CHOICE4 = $sourcez
                detailint
            }
        }

    }
}

custom {

    InvokeRest


switch ($CHOICE3) {
 "send2slack" { slackint } 
 
 "send2servicenow" { servicenowint }  

 "send2jira" { jiraint }

 default { write-output $FINDINGS.data.activeFindings.findings }
 }
 }

search {
    
    InvokeRest

switch ($CHOICE4) {
 "send2slack" { slackint } 
 
  "send2servicenow" { servicenowint }  

  "send2jira" { jiraint }

   default {
    $SEARCHX = write-output $FINDINGS.data.activeFindings.findings | select-string $CHOICE3
        if ($SEARCHX.Matches.Count -gt 0)
        {
            write-output $FINDINGS.data.activeFindings.findings
        }

    }
 }
 }

default { 
     displayusage
     createsource
    }
 }
}

default { 
     displayusage
     createsource
    }
}
} #skyline-comm