Fix: Initial connection check when failed would not exit

This commit is contained in:
Gal Szkolnik 2023-07-21 00:01:04 +00:00
parent 77b84f819b
commit 8fe24d44bb
1 changed files with 281 additions and 281 deletions

View File

@ -1,282 +1,282 @@
# establish Logging mechanism # establish Logging mechanism
class LogEntry { class LogEntry {
[bool]$Active=$true [bool]$Active=$true
[DateTime]$Timestamp [DateTime]$Timestamp
[string]$Operation [string]$Operation
[string]$Description [string]$Description
[TimeSpan]$Duration [TimeSpan]$Duration
[String]$Status [String]$Status
LogEntry( LogEntry(
[String]$Operation, [String]$Operation,
[String]$Description, [String]$Description,
[switch]$Closed=$false [switch]$Closed=$false
){ ){
if( $Closed ) { $this.Active=$false } if( $Closed ) { $this.Active=$false }
$this.Timestamp=[DateTime]::Now $this.Timestamp=[DateTime]::Now
$this.Operation=$Operation $this.Operation=$Operation
$this.Description=$Description $this.Description=$Description
$this.Duration=[TimeSpan]::Zero $this.Duration=[TimeSpan]::Zero
$this.Status="Open" $this.Status="Open"
} }
[LogEntry]UpdateLogEntry( [LogEntry]UpdateLogEntry(
[Switch]$Close, [Switch]$Close,
[String]$Status, [String]$Status,
[switch]$Quiet [switch]$Quiet
){ ){
if( $Close ) { if( $Close ) {
$this.Active = $false $this.Active = $false
} }
$this.Duration = [DateTime]::Now - $this.Timestamp $this.Duration = [DateTime]::Now - $this.Timestamp
if($Status) { $this.Status = $Status } if($Status) { $this.Status = $Status }
if( -not $Quiet ) { if( -not $Quiet ) {
Write-Host -ForegroundColor Gray "Update " -NoNewline Write-Host -ForegroundColor Gray "Update " -NoNewline
Write-Host "$($this.Operation)/$($this.Description), $($this.Status)" Write-Host "$($this.Operation)/$($this.Description), $($this.Status)"
} }
return $this; return $this;
} }
} }
class LogTrail { class LogTrail {
[System.Collections.Generic.List[LogEntry]]$logs [System.Collections.Generic.List[LogEntry]]$logs
LogTrail(){ LogTrail(){
$this.logs = [System.Collections.Generic.List[LogEntry]]::new() $this.logs = [System.Collections.Generic.List[LogEntry]]::new()
} }
[LogEntry]NewLogEntry( [LogEntry]NewLogEntry(
[LogEntry]$LogEntry, [LogEntry]$LogEntry,
[switch]$Quiet=$false [switch]$Quiet=$false
){ ){
if( -not $Quiet ) { if( -not $Quiet ) {
Write-Host -ForegroundColor Cyan "Starting " -NoNewline Write-Host -ForegroundColor Cyan "Starting " -NoNewline
Write-Host "$($LogEntry.Operation) / $($LogEntry.Description)..." Write-Host "$($LogEntry.Operation) / $($LogEntry.Description)..."
} }
$this.logs.Add($LogEntry) $this.logs.Add($LogEntry)
return $LogEntry return $LogEntry
} }
[LogEntry]NewLogEntry( [LogEntry]NewLogEntry(
[String]$Operation, [String]$Operation,
[String]$Description, [String]$Description,
[bool]$Quiet=$false [bool]$Quiet=$false
){ ){
return $this.NewLogEntry( return $this.NewLogEntry(
[LogEntry]::new( [LogEntry]::new(
$Operation,$Description,$false $Operation,$Description,$false
) )
,$Quiet ,$Quiet
) )
} }
[LogEntry]NewLogEntry( [LogEntry]NewLogEntry(
[String]$Operation, [String]$Operation,
[String]$Description [String]$Description
){ ){
return $this.NewLogEntry( return $this.NewLogEntry(
$Operation, $Operation,
$Description, $Description,
$false $false
) )
} }
[LogEntry]NewClosedLogEntry( [LogEntry]NewClosedLogEntry(
[String]$Operation, [String]$Operation,
[String]$Description, [String]$Description,
[switch]$Quiet=$false [switch]$Quiet=$false
){ ){
return $this.NewLogEntry( return $this.NewLogEntry(
[LogEntry]::new( [LogEntry]::new(
$Operation,$Description,$false $Operation,$Description,$false
) )
,$Quiet ,$Quiet
) )
} }
} }
$script:LogTrail = [LogTrail]::new() $script:LogTrail = [LogTrail]::new()
function Invoke-LoggedAction{ function Invoke-LoggedAction{
[CmdletBinding()]param( [CmdletBinding()]param(
[Parameter(Mandatory,Position=0)] [Parameter(Mandatory,Position=0)]
[scriptblock]$Action, [scriptblock]$Action,
[Parameter(Mandatory,Position=1)] [Parameter(Mandatory,Position=1)]
[String]$Operation, [String]$Operation,
[Parameter(Mandatory,Position=2)] [Parameter(Mandatory,Position=2)]
[String]$Description, [String]$Description,
[switch]$Quiet, [switch]$Quiet,
[Parameter(ValueFromRemainingArguments,Position=3)] [Parameter(ValueFromRemainingArguments,Position=3)]
$more_args $more_args
) )
$log = $LogTrail.NewLogEntry( $log = $LogTrail.NewLogEntry(
$Operation, $Operation,
$Description, $Description,
$Quiet $Quiet
) )
try { try {
Invoke-Command -ScriptBlock $Action -ArgumentList @( Invoke-Command -ScriptBlock $Action -ArgumentList @(
$log, $Quiet, $more_args $log, $Quiet, $more_args
) -ErrorAction Stop ) -ErrorAction Stop
} catch { } catch {
$local:Err = $_ $local:Err = $_
$local:formatstring = "ERROR: {0} : {1}`n {2}`n" + $local:formatstring = "ERROR: {0} : {1}`n {2}`n" +
" + CategoryInfo : {3}`n" + " + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n" + " + FullyQualifiedErrorId : {4}`n" +
" + Invoke-LoggedAction args: {5}`n" " + Invoke-LoggedAction args: {5}`n"
$local:fields = $Err.InvocationInfo.MyCommand.Name, $local:fields = $Err.InvocationInfo.MyCommand.Name,
(@($Err.ErrorDetails, $Err.Exception) | Where-Object {$_.Message} | Select-Object -First 1 -ExpandProperty Message), (@($Err.ErrorDetails, $Err.Exception) | Where-Object {$_.Message} | Select-Object -First 1 -ExpandProperty Message),
$Err.ScriptStackTrace, $Err.ScriptStackTrace,
$Err.CategoryInfo.ToString(), $Err.CategoryInfo.ToString(),
$Err.FullyQualifiedErrorId, $Err.FullyQualifiedErrorId,
($more_args -join ', ') ($more_args -join ', ')
$log = $log.UpdateLogEntry($true,($formatstring -f $fields),$Quiet) $log = $log.UpdateLogEntry($true,($formatstring -f $fields),$Quiet)
throw $Err throw $Err
} finally { } finally {
if( $log.Active ) { if( $log.Active ) {
$log.UpdateLogEntry($true,"",$Quiet) $log.UpdateLogEntry($true,"",$Quiet)
} }
} }
} }
# Initial tests # Initial tests
# Create the group if it does not already exist. # Create the group if it does not already exist.
# Iterate through the list of users, for each # Iterate through the list of users, for each
# If the user doesn't exist, it will create the user. # If the user doesn't exist, it will create the user.
# If the user isn't a member of the above mentioned group, add it to it. # If the user isn't a member of the above mentioned group, add it to it.
# Display a report. # Display a report.
$script:Domain="unknown" $script:Domain="unknown"
$Automation = @( $Automation = @(
[ordered]@{ [ordered]@{
Operation="Get-Command Get-MgContext" Operation="Get-Command Get-MgContext"
Description="Checking Microsoft.Graph Module command is available" Description="Checking Microsoft.Graph Module command is available"
Action={param([LogEntry]$log,$Quiet) Action={param([LogEntry]$log,$Quiet)
$null = Get-Command Get-MgContext -ErrorAction Stop $null = Get-Command Get-MgContext -ErrorAction Stop
$log.UpdateLogEntry($true,"Success",$Quiet) $log.UpdateLogEntry($true,"Success",$Quiet)
} }
}, },
[ordered]@{ [ordered]@{
Operation="Get-MgOrganization" Operation="Get-MgOrganization"
Description="Testing connection to Microsoft.Graph" Description="Testing connection to Microsoft.Graph"
Action={param([LogEntry]$log,$Quiet) Action={param([LogEntry]$log,$Quiet)
$org = Get-MgOrganization $org = Get-MgOrganization -ErrorAction Stop
$script:Domain = $org.VerifiedDomains | $script:Domain = $org.VerifiedDomains |
Where-Object IsDefault | Where-Object IsDefault |
Select-Object -ExpandProperty Name Select-Object -ExpandProperty Name
$log.UpdateLogEntry( $log.UpdateLogEntry(
$true, $true,
"Connected to $($org.DisplayName) on $Domain", "Connected to $($org.DisplayName) on $Domain",
$Quiet $Quiet
) )
} }
}, },
[ordered]@{ [ordered]@{
Operation="Create Group" Operation="Create Group"
Description="Varonis Assignment Group" Description="Varonis Assignment Group"
Action={param([LogEntry]$log,$Quiet) Action={param([LogEntry]$log,$Quiet)
$Group = Get-MgGroup -Filter "DisplayName eq 'Varonis Assignment Group'" $Group = Get-MgGroup -Filter "DisplayName eq 'Varonis Assignment Group'"
if( $Group ) { if( $Group ) {
$log.UpdateLogEntry($true, "Group already exists $($Group.Id)", $Quiet ) $log.UpdateLogEntry($true, "Group already exists $($Group.Id)", $Quiet )
} else { } else {
$NewGroup = @{ $NewGroup = @{
DisplayName = "Varonis Assignment Group" DisplayName = "Varonis Assignment Group"
Description = "Varonis Assignment Group" Description = "Varonis Assignment Group"
GroupTypes = @() GroupTypes = @()
MailNickname = 'vrns-assign-grp' MailNickname = 'vrns-assign-grp'
MailEnabled = $false MailEnabled = $false
SecurityEnabled = $true SecurityEnabled = $true
} }
$Group = New-MgGroup @NewGroup -ErrorAction Stop $Group = New-MgGroup @NewGroup -ErrorAction Stop
$log.UpdateLogEntry($true, "Group Created $($Group.Id)", $Quiet ) $log.UpdateLogEntry($true, "Group Created $($Group.Id)", $Quiet )
} }
} }
} }
) )
function Main{ function Main{
foreach( $local:Action in $Automation ) { foreach( $local:Action in $Automation ) {
Invoke-LoggedAction @Action -Quiet -ErrorAction Stop Invoke-LoggedAction @Action -Quiet -ErrorAction Stop
} }
$Group = Get-MgGroup -Filter "DisplayName eq 'Varonis Assignment Group'" $Group = Get-MgGroup -Filter "DisplayName eq 'Varonis Assignment Group'"
foreach( $local:i in @(1..20) ) { foreach( $local:i in @(1..20) ) {
$local:UserName = "Test User {0:D2}" -f $i $local:UserName = "Test User {0:D2}" -f $i
try { try {
$local:CreateNewUserAction = @{ $local:CreateNewUserAction = @{
Operation="Create User" Operation="Create User"
Description="$UserName" Description="$UserName"
Action={param([LogEntry]$log,$Quiet,$more) Action={param([LogEntry]$log,$Quiet,$more)
$UserName=$more[0] $UserName=$more[0]
$local:User = Get-MgUser -Filter "DisplayName eq '$UserName'" $local:User = Get-MgUser -Filter "DisplayName eq '$UserName'"
if( $User ) { if( $User ) {
$log.UpdateLogEntry($true, "User '$UserName' already exists $($User.Id)", $Quiet ) $log.UpdateLogEntry($true, "User '$UserName' already exists $($User.Id)", $Quiet )
} else { } else {
$NewUser = @{ $NewUser = @{
AccountEnabled = $true AccountEnabled = $true
DisplayName = $UserName DisplayName = $UserName
MailNickname = $UserName -replace ' ','.' MailNickname = $UserName -replace ' ','.'
UserPrincipalName = "$($UserName -replace ' ','.')@$script:Domain" UserPrincipalName = "$($UserName -replace ' ','.')@$script:Domain"
PasswordProfile = @{ PasswordProfile = @{
ForceChangePasswordNextSignIn = $true ForceChangePasswordNextSignIn = $true
Password = "MyP@ssw0rd!" Password = "MyP@ssw0rd!"
} }
} }
# Create the user # Create the user
$User = New-MgUser @NewUser -ErrorAction Stop $User = New-MgUser @NewUser -ErrorAction Stop
$log.UpdateLogEntry($true, "User '$UserName' created $($User.Id)", $Quiet ) $log.UpdateLogEntry($true, "User '$UserName' created $($User.Id)", $Quiet )
} }
$User $User
} }
} }
$local:User = Invoke-LoggedAction @CreateNewUserAction $UserName -Quiet $local:User = Invoke-LoggedAction @CreateNewUserAction $UserName -Quiet
$local:AddUserToGroup = @{ $local:AddUserToGroup = @{
Operation="Add User to Group: $($Group.DisplayName)" Operation="Add User to Group: $($Group.DisplayName)"
Description="$UserName" Description="$UserName"
Action={param([LogEntry]$log,$Quiet,$more) Action={param([LogEntry]$log,$Quiet,$more)
$Group=$more[0] $Group=$more[0]
$User=$more[1] $User=$more[1]
$UserName = $User.DisplayName $UserName = $User.DisplayName
$GroupName = $Group.DisplayName $GroupName = $Group.DisplayName
$Groups = Get-MgUserMemberOf -UserId $User.Id | Where-Object Id -eq $Group.Id $Groups = Get-MgUserMemberOf -UserId $User.Id | Where-Object Id -eq $Group.Id
if( $Groups ) { if( $Groups ) {
$log.UpdateLogEntry($true, "User '$UserName' already a member of $GroupName", $Quiet ) $log.UpdateLogEntry($true, "User '$UserName' already a member of $GroupName", $Quiet )
} else { } else {
$AssignGroupMember = @{ $AssignGroupMember = @{
GroupId=$Group.Id GroupId=$Group.Id
DirectoryObjectId=$User.Id DirectoryObjectId=$User.Id
} }
# Create the user # Create the user
$User = New-MgGroupMember @AssignGroupMember -ErrorAction Stop $User = New-MgGroupMember @AssignGroupMember -ErrorAction Stop
$log.UpdateLogEntry($true, "Success", $Quiet ) $log.UpdateLogEntry($true, "Success", $Quiet )
} }
} }
} }
Invoke-LoggedAction @AddUserToGroup $Group $User $User.Id $User.DisplayName -Quiet Invoke-LoggedAction @AddUserToGroup $Group $User $User.Id $User.DisplayName -Quiet
} catch { } catch {
# In case of error, continue to the next user. # In case of error, continue to the next user.
} }
} }
} }
try { try {
Main Main
} catch { } catch {
# We are relying on the LogTrail to show us any problems. # We are relying on the LogTrail to show us any problems.
} }
finally { finally {
Write-Host -ForegroundColor Cyan "Run complete, reprinting complete log:" Write-Host -ForegroundColor Cyan "Run complete, reprinting complete log:"
$LogTrail.logs | Format-Table -Wrap $LogTrail.logs | Format-Table -Wrap
} }