Skip to content

Commit

Permalink
Added device audit db updates to the automated billing update.
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisjantzen committed Nov 2, 2021
1 parent 9114a47 commit 1897ec9
Show file tree
Hide file tree
Showing 2 changed files with 111 additions and 1 deletion.
110 changes: 110 additions & 0 deletions User_Billing_Update.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,28 @@ Import-module ITGlueAPI
Add-ITGlueBaseURI -base_uri $APIEndpoint
Add-ITGlueAPIKey $APIKEy

# Install our custom version of the CosmosDB module (if necessary)
$CosmosDBModule = Get-Module -ListAvailable -Name "CosmosDB"

# If installed and not version 0.0.1 (my custom version), uninstall
if ($CosmosDBModule -and ($CosmosDBModule.Version.Major -ne 0 -or $CosmosDBModule.Version.Minor -ne 0 -or $CosmosDBModule.Version.Build -ne 1)) {
Write-Output "Removing old version of CosmosDB module..."
Remove-Module -Name "CosmosDB"
Uninstall-Module -Name "CosmosDB"
Remove-Item -LiteralPath "C:\Program Files\WindowsPowerShell\Modules\CosmosDB" -Force -Recurse -ErrorAction Ignore
$CosmosDBModule = $false
}

if (!$CosmosDBModule) {
$unzipPath = "C:\temp"
if (!(test-path $unzipPath)) {
New-Item -ItemType Directory -Force -Path $unzipPath
}
Expand-Archive "$PSScriptRoot\CosmosDB.zip" -DestinationPath $unzipPath
Move-Item -Path "$($unzipPath)\CosmosDB" -Destination "C:\Program Files\WindowsPowerShell\Modules\" -Force
}
Import-module CosmosDB

Write-Host "Successfully imported required modules and configured the ITGlue API."
Write-PSFMessage -Level Verbose -Message "Configured ITGlue module."

Expand Down Expand Up @@ -1093,6 +1115,7 @@ if ($UserAudit) {
#### Running a Billing Update
#### This will get the contact list from ITG and update the billing document
#### If there were changes from last month it will send an email to accounting
#### This will also update the device audit DB if applicable
#### Use parameter -BillingUpdate $true (default off)
####
#### Note: This code is almost directly pulled from the User Audit powershell script
Expand Down Expand Up @@ -1121,6 +1144,91 @@ if ($BillingUpdate) {
Write-Host "Exported a billing history file."
Write-PSFMessage -Level Verbose -Message "Exported billing history file: $historyPath"

# Update the Device Audit DB if applicable
if ($Device_DB_APIKey -and $Device_DB_APIEndpoint) {
$headers = @{
'x-api-key' = $Device_DB_APIKey
}

$Token = Invoke-RestMethod -Method Post -Uri $Device_DB_APIEndpoint -Headers $headers

if ($Token) {
If (Get-Module -ListAvailable -Name "Az.Accounts") {Import-module Az.Accounts } Else { install-module Az.Accounts -Force; import-module Az.Accounts }
If (Get-Module -ListAvailable -Name "Az.Resources") {Import-module Az.Resources } Else { install-module Az.Resources -Force; import-module Az.Resources }
#If (Get-Module -ListAvailable -Name "CosmosDB") {Import-module CosmosDB} Else { install-module CosmosDB -Force; import-module CosmosDB}

$collectionId = Get-CosmosDbCollectionResourcePath -Database 'DeviceUsage' -Id 'Users'
$contextToken = New-CosmosDbContextToken `
-Resource $collectionId `
-TimeStamp (Get-Date $Token.Timestamp) `
-TokenExpiry $Token.Life `
-Token (ConvertTo-SecureString -String $Token.Token -AsPlainText -Force)

$DB_Name = 'DeviceUsage'
$CustomerAcronym = $Device_DB_APIKey.split('.')[0]
$CosmosDBAccount = "stats-$($CustomerAcronym)".ToLower()
$resourceContext = New-CosmosDbContext -Account $CosmosDBAccount -Database $DB_Name -Token $contextToken

if ($resourceContext) {
$Query = "SELECT * FROM Users u"
$ExistingUsers = Get-CosmosDbDocument -Context $resourceContext -Database $DB_Name -CollectionId "Users" -Query $Query -PartitionKey 'user'

if ($ExistingUsers) {
$Now_UTC = Get-Date (Get-Date).ToUniversalTime() -UFormat '+%Y-%m-%dT%H:%M:%S.000Z'
$UserCount = ($ExistingUsers | Measure-Object).Count
$i = 0
foreach ($User in $ExistingUsers) {
$i++
$Match = $FullMatches | Where-Object { $_.'AD-Username' -eq $User.Username } | Select-Object -First 1

[int]$PercentComplete = ($i / $UserCount * 100)
Write-Progress -Activity "Updating users in Device Audit Database." -PercentComplete $PercentComplete -Status ("Working - " + $PercentComplete + "% (Updating: $($User.Username)")

if (!$Match) {
$EscapedUsername = [Regex]::Escape($User.Username)
$Match = $FullMatches | Where-Object { $_.'ITG-Notes' -match ".*(Username: " + $EscapedUsername + "(\s|W|$)).*" } | Select-Object -First 1

if (!$Match -and $User.DomainOrLocal -eq "Local") {
$Match = $FullMatches | Where-Object { $_.'ITG-Notes' -match ".*(Local Account: " + $EscapedUsername + "(\s|W|$)).*" } | Select-Object -First 1
}

# Still no match, fall back to email-only search
if (!$Match) {
$Match = $FullMatches | Where-Object { $_.'O365-PrimarySmtp' -match "$EscapedUsername\.user@" -or $_.'ITG-Notes' -match ".*(Primary O365 Email: " + $EscapedUsername + "@).*" } | Select-Object -First 1
}
}

$UpdateRequired = $false
# If changing fields, update in device audit as well
$UpdatedUser = $User | Select-Object Id, Domain, DomainOrLocal, Username, LastUpdated, type, O365Email, ITG_ID, ADUsername

if ($Match) {
if ($Match.'AD-Username' -and $User.ADUsername -ne $Match.'AD-Username') {
$UpdatedUser.ADUsername = $Match.'AD-Username'
$UpdateRequired = $true
}
if ($Match.'O365-PrimarySmtp' -and $User.O365Email -ne $Match.'O365-PrimarySmtp') {
$UpdatedUser.O365Email = $Match.'O365-PrimarySmtp'
$UpdateRequired = $true
}
if ($Match.id -and $User.ITG_ID -ne $Match.id) {
$UpdatedUser.ITG_ID = $Match.id
$UpdateRequired = $true
}
}

$UserID = $User.Id
if ($UpdateRequired) {
$UpdatedUser.LastUpdated = $Now_UTC
Set-CosmosDbDocument -Context $resourceContext -Database $DB_Name -CollectionId "Users" -Id $UserID -DocumentBody ($UpdatedUser | ConvertTo-Json) -PartitionKey 'user' | Out-Null
}
}
Write-Progress -Activity "Updating users in Device Audit Database." -Status "Ready" -Completed
}
}
}
}

# Export billing user list to CSV
Write-Host "Generating billing report..."
Write-PSFMessage -Level Verbose -Message "Generating Billing Report."
Expand Down Expand Up @@ -1986,6 +2094,8 @@ if ($BillingUpdate) {
}
}



# Close email sessions
if ($EmailType -eq "O365") {
Disconnect-ExchangeOnline -Confirm:$false
Expand Down
2 changes: 1 addition & 1 deletion currentversion.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.9.6
2.10.0

0 comments on commit 1897ec9

Please sign in to comment.