So here in the environment I am in, We have a MSSQL database where we hold information on what access new users get in Active Directory and other applications. I have converted a large amount of the Logic from .NET to Powershell for team support as not everyone here on the team knows .NET to support it in an event I’m out sick or injured.
So over the last day or so I’ve been converting the Logic over. The Scripts review’s the Active Directory Account’s wwwHomepage field and apply’s the correct permissions using that as the key to crossing the Data in the SQL database to locate the SecurityGroups to apply.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
Private Function QuerySecurityGroups() As Boolean Console.WriteLine(Now.ToString & " " & System.Reflection.MethodInfo.GetCurrentMethod().ToString) Try Dim Command As String = "select * FROM dbo.AppRights WHERE (AppName='ActiveDirectory' and RightsItem='SecurityGroup') order by Dept, JobCode" Dim myCommand = New System.Data.SqlClient.SqlCommand(Command, MySQLConnectionProvisoningRoleModel) Dim MyReader As SqlDataReader = myCommand.ExecuteReader Dim I As Integer = 0 Dim Flag As Boolean = False While MyReader.Read() SecurityGroup.Add(MyReader(0) & "|" & MyReader(1) & "|" & MyReader(2) & "|" & MyReader(3) & "|" & MyReader(4) & "|" & MyReader(5)) Debug.WriteLine(MyReader(0) & " " & MyReader(1) & " " & MyReader(2) & " " & MyReader(3) & " " & MyReader(4) & " " & MyReader(5)) I += 1 End While myCommand.Dispose() MyReader.Close() 'I = 0 if row does not exist. Return Flag Catch ex As Exception EisenhowerErrorHandler.ErrorHandlerFunction(ex, False, True, False) Return False End Try End Function Private Sub ApplyMissingSecurityGroups() Console.WriteLine(Now.ToString & " " & System.Reflection.MethodInfo.GetCurrentMethod().ToString) Try For Each Result As SearchResult In ActiveDirectory If TermedUsers.Contains(Result.Properties("samAccountName")(0)) Then 'Do not add security groups for termed users! Debug.WriteLine("User is termed, Not adding MissingSecurityGroups for: " & Result.Properties("samAccountName")(0)) Continue For End If If Result.Properties.Contains("wwwHomePage") Then 'Check to see if they have a webpage assigned to them. If Result.Properties("wwwHomePage")(0).ToString.Split("|").Length < 2 Then Continue For End If 'Debug.WriteLine(Result.Path & " " & Result.Properties("wwwHomePage")(0).ToString) 'If Result.Properties("wwwHomePage")(0).ToString.EndsWith("0200") Then 'Debugger.Break() 'End If If False And (Result.Properties("wwwHomePage")(0).ToString.Split("|")(0).StartsWith("0") Or Result.Properties("wwwHomePage")(0).ToString.Split("|")(1).StartsWith("0")) Then 'This removed Appending Zeros from homepage... 9480|0013 -> 9480|13 Dim MyEntry As DirectoryEntry = Result.GetDirectoryEntry Dim CorrectAddress As String = (Result.Properties("wwwHomePage")(0).ToString.Split("|")(0).TrimStart("0").ToString & "|" & Result.Properties("wwwHomePage")(0).ToString.Split("|")(1).TrimStart("0")) ChangeList &= Result.Properties("samAccountName")(0) & " wwwHomePage updated: " & Result.Properties("wwwHomePage")(0).ToString & " => " & CorrectAddress & vbCrLf MyEntry.InvokeSet("wwwHomePage", CorrectAddress) MyEntry.CommitChanges() Else If Result.Properties("wwwHomePage")(0).ToString.Length <> 9 Then 'If Result.Properties("wwwHomePage")(0).ToString.Length > 9 Then 'System.Diagnostics.Debugger.Break() 'End If Dim MyEntry As DirectoryEntry = Result.GetDirectoryEntry Dim TmpDept, TmpJobcode As String TmpDept = Result.Properties("wwwHomePage")(0).ToString.Split("|")(0).PadLeft(4, "0") TmpJobcode = Result.Properties("wwwHomePage")(0).ToString.Split("|")(1).PadLeft(4, "0") Dim CorrectAddress As String = (TmpDept & "|" & TmpJobcode) ChangeList &= Result.Properties("samAccountName")(0) & " wwwHomePage updated: " & Result.Properties("wwwHomePage")(0).ToString & " => " & CorrectAddress & vbCrLf 'Debug.WriteLine(Result.Properties("samAccountName")(0) & " | " & Result.Properties("wwwHomePage")(0).ToString & " - " & Result.Properties("wwwHomePage")(0).ToString.Length & " => " & CorrectAddress) MyEntry.InvokeSet("wwwHomePage", CorrectAddress) MyEntry.CommitChanges() End If End If Dim ADDept, ADJobCode, ADEntity As Integer If False Then ADDept = Result.Properties("wwwHomePage")(0).ToString.Split("|")(0).TrimStart("0") ADJobCode = Result.Properties("wwwHomePage")(0).ToString.Split("|")(1).TrimStart("0") Else ADDept = Result.Properties("wwwHomePage")(0).ToString.Split("|")(0).PadLeft(4, "0") ADJobCode = Result.Properties("wwwHomePage")(0).ToString.Split("|")(1).PadLeft(4, "0") If Result.Properties.Contains("Company") Then If CompanyDictionary.ContainsKey(Result.Properties("Company")(0)) Then ADEntity = CompanyDictionary(Result.Properties("Company")(0)) 'Convert String to INT Else ChangeList &= ("Invalid Company!: " & Result.Properties("samAccountName")(0) & " - " & Result.Properties("Company")(0)) & vbCrLf Continue For End If End If End If 'Debug.WriteLine(vbTab & "CURRENTLY A MEMBER OF") 'For Each MemberGroup In Result.Properties("MemberOf") 'Debug.WriteLine(vbTab & MemberGroup) 'Next If Result.Properties("samAccountName")(0).ToString = "15997" Then 'Debugger.Break() End If If Result.Properties.Contains("company") Then 'Debug.WriteLine(Result.Properties("company")(0)) 'Debug.WriteLine(CompanyDictionary(Result.Properties("company")(0))) Else Try Dim SamAccountName As String = Result.Properties("samAccountName")(0).ToString If SamAccountName.StartsWith("dr", vbTextCompare) Then If SamAccountName.Length > 2 Then If Char.IsNumber(SamAccountName(2)) Then Dim MyEntry As DirectoryEntry = Result.GetDirectoryEntry 'MyEntry.InvokeSet("company", "Contractor") 'It does not exist and can not be set so use .ADD MyEntry.Properties("company").Add("Contractor") MyEntry.CommitChanges() ChangeList &= ("Missing Company - Added Contractor: " & SamAccountName) & vbCrLf End If End If Else ChangeList &= ("Missing Company: " & SamAccountName) & vbCrLf Continue For End If Catch ex As Exception Continue For End Try End If Dim FoundSecGroup As Boolean = False For Each Entry In SecurityGroup 'Cycles through each entry in SentTable Dim Dept, JobCode, Entity As Integer Dim SecGroup As String Dept = Entry.ToString.Split("|")(1) JobCode = Entry.ToString.Split("|")(2) Entity = Entry.ToString.Split("|")(5) If Entry.ToString.Split("|")(4).Contains(",") Then SecGroup = Entry.ToString.Split("|")(4).Split(",")(0).Substring(3) 'Check if DN Else SecGroup = Entry.ToString.Split("|")(4) 'Not a DN End If If (Dept = ADDept Or Dept = 0) And (JobCode = ADJobCode Or JobCode = 0) And (Entity = ADEntity Or Entity = 0) Then If Dept = 0 Or JobCode = 0 Then 'System.Diagnostics.Debugger.Break() End If If Dept = 0 Then 'System.Diagnostics.Debugger.Break() End If If Dept = 0 And ADDept = 7010 Then 'Don't apply wildcards to ED. Continue For End If 'Debug.WriteLine(vbTab & vbTab & Entry.ToString) 'If Result.Properties("PrimaryGroupID")(0) = "" Then 'End If For Each MemberGroup In Result.Properties("MemberOf") 'Check to see if the user is already a member of the group Dim Pre2000name As String = GetSamAccountNameFromdistinguishedNameOrCN(MemberGroup) Dim CurrentMemberof As String = MemberGroup.ToString.Split(",")(0).Substring(3) 'Debug.WriteLine("Sam: " & Pre2000name) If StrComp(CurrentMemberof, SecGroup, CompareMethod.Text) = 0 Or StrComp(Pre2000name, SecGroup, CompareMethod.Text) = 0 Then FoundSecGroup = True Exit For End If Next If Not FoundSecGroup Then Try If ADEntity = Entity Or Entity = 0 Then 'Debug.WriteLine("Missing SecGroup: " & SecGroup & " - " & Dept & " - " & JobCode) Dim match As Match = Regex.Match(SecGroup, "[\d]{4}_.+", RegexOptions.IgnoreCase) If match.Success Then 'Debug.WriteLine("Group that needs to be added is a CostCenter group " & match.Value) For Each MemberGroup In Result.Properties("MemberOf") 'Check to see if the user is already a member of a CostCenter group Dim Pre2000name As String = GetSamAccountNameFromdistinguishedNameOrCN(MemberGroup) Dim CurrentMemberof As String = MemberGroup.ToString.Split(",")(0).Substring(3) Dim matcher As Match = Regex.Match(CurrentMemberof, "^[\d]{4}_.+", RegexOptions.IgnoreCase) If matcher.Success Then Debug.WriteLine("Found Group: " & matcher.Value) Dim MyEntry As DirectoryEntry = Result.GetDirectoryEntry Dim TheGroup As DirectoryEntry = New DirectoryEntry("LDAP://" + MemberGroup, Nothing, Nothing) TheGroup.Invoke("Remove", New Object() {MyEntry.Path}) TheGroup.CommitChanges() End If Next End If AddUserToPre2000Group(Result.Properties("samAccountName")(0), SecGroup) End If Catch ex As Exception ChangeList &= ex.Message & " - " & Result.Properties("samAccountName")(0) & "|" & SecGroup & vbCrLf End Try End If FoundSecGroup = False End If Next Else 'Debug.WriteLine("No homepage for: " & Result.Path) End If Next Catch ex As Exception EisenhowerErrorHandler.ErrorHandlerFunction(ex, False, True, False) End Try End Sub Private Function AddUserToPre2000Group(ByVal UserName As String, ByVal GroupName As String) As Boolean Try 'Create the object Dim Group As Object Try If GroupName Is Nothing Then ChangeList &= ("Blank Group name: " & UserName) Return False End If Group = GetObject("WinNT://" & DomainComputer & "/" & GroupName & ",group") Catch ex As Exception Dim Pre2000Name As String = GetSamAccountNameFromdistinguishedNameOrCN(GroupName) If StrComp(Pre2000Name, GroupName, CompareMethod.Text) <> 0 Then If AddUserToPre2000Group(UserName, GetSamAccountNameFromdistinguishedNameOrCN(GroupName)) Then Return True End If End If Debug.WriteLine("No Such group Exist: " & GroupName) ChangeList &= ("No Such group Exist: " & GroupName) Return False End Try Dim User = GetObject("WinNT://" & DomainComputer & "/" & UserName & ",user") Group.add(User.adspath) Catch ex As Exception ChangeList &= UserName & " failed to be added to: " & GroupName & vbCrLf & "GetGroup(): " & ex.Message Debug.WriteLine("GetGroup(): " & ex.Message & " - " & ex.InnerException.Message) Return False End Try ChangeList &= UserName & " has been added to: " & GroupName & vbCrLf Debug.WriteLine(UserName & " has been added to: " & GroupName & vbCrLf) Return True End Function |
And my work in progress to get it converted over to Powershell.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |
Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear(); Clear-Host $ConnectionString = "Server=SQLServer;Database=ProvisioningRoleModel;Trusted_Connection=yes;" $sqlConnection = new-object System.Data.SqlClient.SqlConnection $ConnectionString $sqlConnection.Open() $ActiveFeed = @{} $TermFeed = @{} $ADDict = @{} $ADTags = @{} $GroupMembershipsAdded = "" $Footer = "<br><br><br><br><br><br>*********************************<br>REPORT DETAILS<br>*********************************<br><table border=`"5`"><tr><td>Type:</td><td>Scheduled Task</td></tr><tr><td>Task Name:</td><td>ApplyMissingSecurityGroups</td></tr><tr><td>Schedule:</td><td>Every Day @ 5:00 AM</td></tr><tr><td>Run As:</td><td>svc_provision</td></tr><tr><td>Server:</td><td>Computer.FQDN.COM</td></tr><tr><td>Script Location:</td><td>\\MyComputer\c$\Extra</td></tr><tr><td>Script Name:</td><td>ApplyMissingSecurityGroups.ps1</td></tr><tr><td>Output Dir:</td><td>N/A</td></tr></table>*********************************<br>" foreach($line in get-content "\\Mycomputer\c$\active and leave empl.txt") { $recipients = $line -split [RegEx]::Escape("|") $FullName = [string] $FullName = $recipients[6].trim() #Last name $FullName = $FullName + ", " + $recipients[8].trim() #First name $samAccountName = $recipients[1].trim() $CostCenter = $recipients[2].trim() $Jobcode = $recipients[4].trim() $EmpType = $recipients[17].trim() $WWW = $CostCenter + '|' + $Jobcode if (-Not [string]::IsNullOrEmpty($recipients[11].trim())) { $FullName = $FullName + " (" + $recipients[11].trim() + ")" } if (-Not [string]::IsNullOrEmpty($recipients[7].trim())) { $FullName = $FullName + " " + $recipients[7].trim().Substring(0,1) } Write-Host $recipients[1].trim() $WWW $ActiveFeed.Add($samAccountName,$WWW) $ADTags.Add($samAccountName,$EmpType) #$User = get-aduser -f {samAccountName -eq $samAccountName} #Set-ADUser -Identity $User.sAMAccountName -HomePage $WWW } $sqlCommand = $sqlConnection.CreateCommand() $sqlCommand.CommandText = "select DISTINCT * FROM dbo.AppRights WHERE (AppName='ActiveDirectory' and RightsItem='DIR_SecurityGroup') and ((Dept = '0') and (Jobcode = '0') and (Entity = '0')) order by Dept, JobCode" $DirectorTags = $sqlCommand.ExecuteReader() try { while ($DirectorTags.Read()) { $ADTags.GetEnumerator() | ForEach-Object { if ($_.value -eq "DIR") { Add-ADGroupMember -Identity "app_JiraAutoApprove" -Member $_.key $message = '{0} is a {1}, it gets {2}!' -f $_.key, $_.value, $DirectorTags.GetValue(4) Write-Output $message } } } } catch { } $DirectorTags.Close() $sqlCommand = $sqlConnection.CreateCommand() $sqlCommand.CommandText = "select DISTINCT * FROM dbo.AppRights WHERE (AppName='ActiveDirectory' and RightsItem='ELT_SecurityGroup') and ((Dept = '0') and (Jobcode = '0') and (Entity = '0')) order by Dept, JobCode" $ELTTags = $sqlCommand.ExecuteReader() try { while ($ELTTags.Read()) { $ADTags.GetEnumerator() | ForEach-Object { if ($_.value -eq "ELT") { Add-ADGroupMember -Identity "app_JiraAutoApprove" -Member $_.key $message = '{0} is a {1}, it gets {2}!' -f $_.key, $_.value, $ELTTags.GetValue(4) Write-Output $message } } } } catch { } $ELTTags.Close() foreach($line in get-content "\\MyComputer\c$\all terms.csv") { try { $recipients = $line -split [RegEx]::Escape(",") $samAccountName = $recipients[3].trim() #$User = Get-ADUser -LDAPFilter "(sAMAccountName=$samAccountName)" | Select-Object -Property samaccountname,enabled #If ($User -ne $Null) #{ #Write-Host $samAccountName "User Termed " $User.Enabled #!DELETE_USER|30861|7010|2508|Amanda||Sellers|22817|20170110|20171024 Write-Host ("!DELETE_USER|{0}" -f $samAccountName) $TermFeed.Add($samAccountName,$samAccountName) #} } catch { } } Get-ADUser -SearchBase "OU=SomeOU,DC=Domain,DC=Com" -Filter 'Enabled -eq $true' -Properties SamAccountName, DisplayName, wWWHomePage, company, memberOf | sort SamAccountName | ForEach { #if ($_.SamAccountName -match "^[\d\.]+$") #{ Write-Host $_.SamAccountName $_.DisplayName $_.wWWHomePage $_.company $ADDict.Add($_.SamAccountName,$_.wWWHomePage) if ($TermFeed.ContainsKey($_.SamAccountName)) { Write-Host "User is termed, Not adding MissingSecurityGroups for: " $_.SamAccountName return #For object based ForEach loops you must use return and not continue } if (![string]::IsNullOrEmpty($_.wWWHomePage)) { $wwwSplit = $_.wWWHomePage -split [RegEx]::Escape("|") if ($wwwSplit.length -lt 2) { Write-Host "User does not have a | delimited WWWpage: " $_.SamAccountName " - " $_.wWWHomePage return #For object based ForEach loops you must use return and not continue } if ($_.wWWHomePage.length -ne 9) { Write-Host "User needs WWW.length<>9 updated: " $_.SamAccountName " - " $_.wWWHomePage return #For object based ForEach loops you must use return and not continue } } else { return #Return if no wWWHomePage } $Entity = [string] switch ($_.company) { # #The if conditions below can be combined into one if ( -or ) statement to stop UpdateADCostCenterFields from being called twice. # "Eisenhower Medical Center" { $Entity = 1 } "Barbara Sinatra Children's Center" { $Entity = 3 } "Annenberg Center for Health Sciences" { $Entity = 14 } "Contractor" { $Entity = 88 } default { Write-Host "Invalid Company Name for" $_.SamAccountName " - " $_.Company return } } $wwwSplit = $_.wWWHomePage -split [RegEx]::Escape("|") $Dept = [string] $Jobcode = [string] $Dept = $wwwSplit[0].trim() #Last $Jobcode = $wwwSplit[1].trim() #Last $sqlCommand = $sqlConnection.CreateCommand() $sqlCommand.CommandText = "select DISTINCT * FROM dbo.AppRights WHERE (AppName='ActiveDirectory' and RightsItem='SecurityGroup') and ((Dept = '0' or Dept = '" + $Dept + "') and (Jobcode = '0' or Jobcode = '" + $Jobcode + "') and (Entity = '0' or Entity = '" + $Entity + "')) order by Dept, JobCode" $costcenterReader = $sqlCommand.ExecuteReader() #Get-ADPrincipalGroupMembership $_.SamAccountName | select name try { while ($costcenterReader.Read()) { [bool] $HasThisGroup = $false #foreach ($mymember in Get-ADPrincipalGroupMembership $_.SamAccountName) #$mymember.SamAccountName foreach ($mymember in $_.memberOf) { #Write-Host "Comparing " ($mymember -split ',')[0].Replace('CN=', '') " -> " $costcenterReader.GetValue(4) if (($mymember -split ',')[0].Replace('CN=', '') -like $costcenterReader.GetValue(4)) { $HasThisGroup = $true } } if ($HasThisGroup -eq $true) { Write-Host `t "Already has: " + $costcenterReader.GetValue(4) } else { Write-Host `t "Needs: " + $costcenterReader.GetValue(4) + "<br>" Add-ADGroupMember -Identity $costcenterReader.GetValue(4) -Member $_.SamAccountName $GroupMembershipsAdded += $_.SamAccountName + " => " + $costcenterReader.GetValue(4) } } } catch { } $costcenterReader.Close() #Check to see if these users should have EPIC SecurityGroup from the AppRights Table $sqlCommand = $sqlConnection.CreateCommand() $sqlCommand.CommandText = "select TOP 1 * FROM dbo.AppRights WHERE (AppName='EPIC') and (RightsValue='T%') and ((Dept = '0' or Dept = '" + $Dept + "') and (Jobcode = '0' or Jobcode = '" + $Jobcode + "') and (Entity = '0' or Entity = '" + $Entity + "'))" $costcenterReader = $sqlCommand.ExecuteScalar() [bool] $Citrix_EPIC_Hyperspace_Prod = $false [bool] $Citrix_EPIC_Hyperspace_Trnply = $false [bool] $Citrix_EPIC_Hyperspace_ACES = $false try { if ($costcenterReader -ne $null) { Write-Host `t EPIC foreach ($mymember in $_.memberOf) { #Write-Host "Comparing " ($mymember -split ',')[0].Replace('CN=', '') " -> " $costcenterReader.GetValue(4) if (($mymember -split ',')[0].Replace('CN=', '') -like 'Citrix_EPIC_Hyperspace_Prod') { $Citrix_EPIC_Hyperspace_Prod = $true } if (($mymember -split ',')[0].Replace('CN=', '') -like 'Citrix_EPIC_Hyperspace_Trnply') { $Citrix_EPIC_Hyperspace_Trnply = $true } if (($mymember -split ',')[0].Replace('CN=', '') -like 'Citrix_EPIC_Hyperspace_ACES') { $Citrix_EPIC_Hyperspace_ACES = $true } } if ($Citrix_EPIC_Hyperspace_Prod -ne $true) { Write-Host "Needs Citrix_EPIC_Hyperspace_Prod" Add-ADGroupMember -Identity "Citrix_EPIC_Hyperspace_Prod" -Member $_.SamAccountName $GroupMembershipsAdded += $_.SamAccountName + " => Citrix_EPIC_Hyperspace_Prod<br>" } if ($Citrix_EPIC_Hyperspace_Trnply -ne $true) { Write-Host "Needs Citrix_EPIC_Hyperspace_Trnply" Add-ADGroupMember -Identity "Citrix_EPIC_Hyperspace_Trnply" -Member $_.SamAccountName $GroupMembershipsAdded += $_.SamAccountName + " => Needs Citrix_EPIC_Hyperspace_Trnply<br>" } if ($Citrix_EPIC_Hyperspace_ACES -ne $true) { Write-Host "Needs Citrix_EPIC_Hyperspace_ACES" Add-ADGroupMember -Identity "Citrix_EPIC_Hyperspace_ACES" -Member $_.SamAccountName $GroupMembershipsAdded += $_.SamAccountName + " => Citrix_EPIC_Hyperspace_ACES<br>" } } } catch { Write-Host $_.Exception.Message } #Check to see if these users should have EPIC SecurityGroup from the AppRights Table $sqlCommand = $sqlConnection.CreateCommand() $sqlCommand.CommandText = "select TOP 1 * FROM dbo.AppRights WHERE (AppName='EPIC') and (RightsValue='L%') and ((Dept = '0' or Dept = '" + $Dept + "') and (Jobcode = '0' or Jobcode = '" + $Jobcode + "') and (Entity = '0' or Entity = '" + $Entity + "'))" $costcenterReader = $sqlCommand.ExecuteScalar() [bool] $Citrix_Epic_Care_Link = $false try { if ($costcenterReader -ne $null) { Write-Host `t EPIC foreach ($mymember in $_.memberOf) { #Write-Host "Comparing " ($mymember -split ',')[0].Replace('CN=', '') " -> " $costcenterReader.GetValue(4) if (($mymember -split ',')[0].Replace('CN=', '') -like 'Citrix_Epic_Care_Link') { $Citrix_Epic_Care_Link = $true } } if ($Citrix_Epic_Care_Link -ne $true) { Write-Host "Needs Citrix_Epic_Care_Link" Add-ADGroupMember -Identity "Citrix_Epic_Care_Link" -Member $_.SamAccountName $GroupMembershipsAdded += $_.SamAccountName + " => Citrix_Epic_Care_Link<br>" } } } catch { Write-Host $_.Exception.Message } } if ($GroupMembershipsAdded -eq "") { Send-MailMessage -To "Nhall <myemail@domain.com>" -From "Provision Powershell" -Subject "Group Membership Compliance - No Changes" -SmtpServer "exchange" -BodyAsHtml "No Security Group Changes $footer" } else { Send-MailMessage -To "Nhall <myemail@domain.com>" -From "Provision Powershell" -Subject "Group Membership Compliance" -SmtpServer "exchange" -BodyAsHtml "$GroupMembershipsAdded $footer" } exit |