none
Help on Windows PowerShell

    Question

  • Hi All,

    I got his windows power script downloaded from the gallery.technet.com  This Termination script can do several different functions; Disable AD User account and set user description to Account Terminated on $date; remove Group Membership from User account and email and display the results; Move user to Disabled Users OU.; Change the user password; Set an expiration date.

    For each function I have set the email notification.

    Wanted to have the following change done on this

    Instead of using samaccountname and we replace it employee ID

    $emailbody = $user.memberof give me garbled up data. Can we do a change

    One consolidated Email notification for all the functions into a html format.

    Request help.


    Regards, Sumanth

    Tuesday, February 28, 2012 4:38 AM

Answers

  • You can use the following Function to get a User by a Given Property:

    Function Get-User {
    # Universal Function to get a Active Directory User over a unique Property
    
    Param ($PropertyName=$(throw "you must enter the Name of a User-Property, to search for the User!"), `
    $PropertyValue=$(throw 'you must enter the Value of the User-Property ($PropertyName), to search for the User!!'))
    
    $searcher=New-Object DirectoryServices.DirectorySearcher
    $searcher.Filter="(&(objectcategory=person)(objectclass=user)($PropertyName=$PropertyValue))"
    $results=$searcher.FindOne()
    
        if ($results.path.length -gt 1)
        {
           Return [ADSI]$results.Path
        }
        else
        {
           [System.Windows.Forms.MessageBox]::Show("User not found! With Property: $PropertyName = $PropertyValue", "User not found!", [Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning, [System.Windows.Forms.MessageBoxDefaultButton]::Button1, [System.Windows.Forms.MessageBoxOptions]::DefaultDesktopOnly) | Out-Null 
           Return $Null
        }
    } # END Function Get-User
    
    #Example to get the user over the sAMAccountname
    $User = Get-User "sAMAccountname" "Put-sAMAccountname-Here"
    
    #Example to get the user over the employeeID
    $User = Get-User "employeeID" "Put-employeeId-Here"

    For the RemoveGroups Function you have to Provide a USER !!!
    To provide a User you can here even use the Get-User Function from above, or you Stor the User Global in your script and use this global stored one.

    Function RemoveGroups {
    
    Param ($ADUser=$(throw "you must enter a User!"))
    
    try   {  
            foreach ($group in $ADuser.memberof)
            {
              $groupDE = [ADSI]"LDAP://$group" 
              #$groupDE.remove("LDAP://$($user.distinguishedName)")
              #$Rsltstxtbx.AppendText("Removed Group, $group`r`n")
              $Script:emailbody += "`n$group"
            } # END foreach
           
            # $Rsltstxtbx.AppendText("Groups Removed `r`n") 
            # send_email
            
          } # END try
    catch {
              #$errorProvider1.SetError($RsltsTxtbx.AppendText("Access Denied, Please verify actions with Active Directory tools`r`n"))}
          } # END catch
    } # END Function RemoveGroups
    
    
    $emailbody = ""
    RemoveGroups $(Get-User "sAMAccountname" "ekriegp")
    $emailbody

    To send e-mail in HTML see:

    Get-Help ConvertTo-Html

    Please click “Mark as Answer” if my post answers your question and click Vote as Help if my Post helps you.
    Bitte markiere hilfreiche Beiträge von mir als Hilfreich und Beiträge die deine Frage ganz oder teilweise beantwortet haben als Antwort.
    My PowerShell Blog http://www.admin-source.info
    [string](0..21|%{[char][int]([int]("{0:d}" -f 0x28)+('755964655967-86965747271757624-8796158066061').substring(($_*2),2))})-replace



    Tuesday, February 28, 2012 1:28 PM

All replies

  •  

     Please find the script here

     ########################################################################### 
    # Code Generated By: SAPIEN Technologies, Inc., PrimalForms 2009 v1.1.16.0 
    # Generated On: 1/4/2012 8:48 AM 
    # Generated By: Administrator 
    ########################################################################### 


    #----------------------------------------------
    #region Application Functions
    #----------------------------------------------


    function OnApplicationLoad {
    #Note: This function runs before the form is created
    #Note: To get the script directory in the Packager use: Split-Path $hostinvocation.MyCommand.path
    #Note: To get the console output in the Packager (Windows Mode) use: $ConsoleOutput (Type: System.Collections.ArrayList)
    #Important: Form controls cannot be accessed in this function
    #TODO: Add snapins and custom code to validate the application load

    return $true #return true for success or false for failure
    }


    function OnApplicationExit {
    #Note: This function runs after the form is closed
    #TODO: Add custom code to clean up and unload snapins when the application exits

    $script:ExitCode = 0 #Set the exit code for the Packager
    }


    #endregion


    #----------------------------------------------
    # Generated Form Function
    #----------------------------------------------
    function GenerateForm {


    #----------------------------------------------
    #region Import Assemblies
    #----------------------------------------------
    [void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    [void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    [void][reflection.assembly]::Load("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    [void][reflection.assembly]::Load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    [void][reflection.assembly]::Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    #endregion

    #----------------------------------------------
    #region Generated Form Objects
    #----------------------------------------------
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form1 = New-Object System.Windows.Forms.Form
    $ResetFormBtn = New-Object System.Windows.Forms.Button
    $datetimepicker1 = New-Object System.Windows.Forms.DateTimePicker
    $ExpDateChk = New-Object System.Windows.Forms.CheckBox
    $PwdLbl = New-Object System.Windows.Forms.Label
    $PwdTxtBx = New-Object System.Windows.Forms.TextBox
    $CancelButton = New-Object System.Windows.Forms.Button
    $OKbtn = New-Object System.Windows.Forms.Button
    $RsltsTxtbx = New-Object System.Windows.Forms.TextBox
    $RmvGrpCHK = New-Object System.Windows.Forms.CheckBox
    $MvAccountCHK = New-Object System.Windows.Forms.CheckBox
    $ResetPwdCHK = New-Object System.Windows.Forms.CheckBox
    $DisableAccountCHK = New-Object System.Windows.Forms.CheckBox
    $UserNameTxtbx = New-Object System.Windows.Forms.TextBox
    $DomainComboBox = New-Object System.Windows.Forms.ComboBox
    $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
    #endregion Generated Form Objects


    #----------------------------------------------
    # User Generated Script
    #----------------------------------------------


    $FormEvent_Load={
    Import-Module ActiveDirectory

    }
    $handler_OKbtn_Click={
    #TODO: Place custom script here
    $Date = Get-Date
    $Domain = $DomainComboBox.text
    $samaccountname = $UserNameTxtbx.text

    # Define Functions

    #Send email function

    $EmailFrom = "EmailFrom"
    $EmailTo = "Emailto"
            $SMTPServer = "SMTPSERVER"
            $SMTPAuthUsername = "Username"
            $SMTPAuthPassword = "PAssword"
            $EmailSubject = "Email From Termination Tool"    

    function send_email {
       $mailmessage = New-Object system.net.mail.mailmessage 
       $mailmessage.from = ($emailfrom) 
       $mailmessage.To.add($emailto)
       $mailmessage.Subject = $emailsubject
       $mailmessage.Body = $emailbody
     

       #$mailmessage.IsBodyHTML = $true
           $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
                $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword")  
           $SMTPClient.Send($mailmessage)
                
    }

       #Disable User Function

    Function DisableUser {
       
    try{ 

            $user.description = "Account Disabled on $date"
        $user.setinfo()#End description

        # Sets user account to disabled
            $user.AccountDisabled = $True
        $user.SetInfo()
    $RsltsTxtbx.AppendText("$user.AccountDisabled `r`n")
        $RsltsTxtbx.AppendText("$samaccountname has been Disabled on $date `r`n")
        $emailbody = "Disabled $samaccountname Account"
                 send_email
    }
                           
    catch{
    $errorProvider1.SetError($RsltsTxtbx.AppendText("Access Denied, Please verify actions with Active Directory tools`r`n"))}
    }

    # Function to Remove Groups from user account

    Function RemoveGroups {
    try{  
       foreach ($group in $user.memberof)
    {
       $groupDE = [ADSI]"LDAP://$group" 
       $groupDE.remove("LDAP://$($user.distinguishedName)")
    $Rsltstxtbx.AppendText("Removed Group, $group`r`n")
    $emailbody = $user.memberof
                    }
    $Rsltstxtbx.AppendText("Groups Removed `r`n") 
                    send_email
    }
    catch{
    $errorProvider1.SetError($RsltsTxtbx.AppendText("Access Denied, Please verify actions with Active Directory tools`r`n"))}
    }

    # Function to move user account to Disabled Users OU

    Function MoveUser {

    # Move user account to Diabled Users OU
    Switch ($DomainComboBox.text)
    {
    DOMAIN1{
       $ADSPath = $User.Properties.adspath
       $MoveToOU = [ADSI]("LDAP://OU=Test,OU=XXX,DC=XXXX,DC=XX")
       $User.PSBase.MoveTo($MoveToOU)
       $Rsltstxtbx.AppendText("$samaccountname moved from $userpath to Disabled Users OU `r`n")
                    $emailbody = "$samaccountname moved from $userpath to Disabled Users OU"
                    send_email
    }

    DOMAIN2{
    $ADSPath = $User.Properties.adspath
    $MoveToOUSSP = [ADSI]("LDAP://OU=Test,OU=XXX,DC=XXXX,DC=XX")
    $User.PSBase.MoveTo($MoveToOUSSP)
    $Rsltstxtbx.AppendText("$samaccountname moved from $userpath to Disabled Users OU `r`n")
    $emailbody = "$samaccountname moved from $userpath to Disabled Users OU"
                    send_email
                    }
     }
               }

    # Function to create Random Password

    function CreatePassword([int]$length)

    {

      $specialCharacters = "@#$%^&*()_!+"

      $lowerCase = "abcdefghijklmnopqrstuvwxyz"

      $upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

      $numbers = "1234567890"

      $res = ""

      $rnd = New-Object System.Random

      do

      {

          $flag = $rnd.Next(4); 

          if ($flag -eq 0)

          {$res += $specialCharacters[$rnd.Next($specialCharacters.Length)];

          } elseif ($flag -eq 1)

          {$res += $lowerCase[$rnd.Next($lowerCase.Length)];

          } elseif ($flag -eq 2)

          {$res += $upperCase[$rnd.Next($upperCase.Length)];

          } else

          {$res += $numbers[$rnd.Next($numbers.Length)];

          }

      } while (0 -lt $length--)

      return $res

    }

    # Function to Set Expiration Date on User Account
    function SetEXPdate
               {

    $datetimepicker1.CustomFormat = "MM/dd/yyyy h"
    [adsi]$user="WinNT://$domain/$samaccountname" 
    $user.psbase.InvokeSet('AccountExpirationDate', $datetimepicker1)
    $user.psbase.CommitChanges()
    $RsltsTxtbx.AppendText("Account Expiration Date set to $datetimepicker1 `r`n")
    }

    $mbYesNoAsk = [System.Windows.Forms.MessageBox]  
    $btnChoices = [Windows.Forms.MessageBoxButtons]::YesNo  
    $MsgType = [windows.forms.MessageBoxIcon]::Warning 
    $Confirm = ($mbYesNoAsk::show("Are you sure "+$SelectedSnapshotGUID+"?","Warning",$btnChoices,$MsgType))
            
    if ($Confirm -eq [Windows.Forms.DialogResult]::Yes)  
           {



    # Searcher
       $ds = new-object DirectoryServices.DirectorySearcher([ADSI]"LDAP://$Domain")
       $ds.filter = "(&(objectCategory=person)(objectClass=user)(samAccountName=$samaccountname))"
                $dn = $ds.findOne() 
       $user = [ADSI]$dn.path
    $userpath = $user.distinguishedname
       if (-not $user.path) {
       $RsltsTxtbx.AppendText("Could Not Find $samaccountname `r`n")
       End

    }
    else {

    if ($DisableAccountCHK.Checked)
    {       
    DisableUser
    }

    if ($RmvGrpCHK.Checked)
    {
    RemoveGroups
    }

    if ($MvAccountCHK.Checked)
    {
    MoveUser
    }

    if ($ResetPwdCHK.Checked)
    {

    $Pwd = CreatePassword 7

       [adsi]$user="WinNT://$domain/$samaccountname" 
    $user.SetPassword("$pwd")
    $user.SetInfo()
    $PwdTxtBx.Text = "$Pwd"

    }
    }
    }
    if ($ExpDateChk.Checked)
    {
    SetEXPdate
    }
    $RsltsTxtbx.AppendText("Action performed on $date `r`n")
    }



    $hanlder_txtbox_Click={
    $UserNameTxtbx.Clear()
    }

    $handler_ExpDateChk_CheckStateChanged={
    switch ($ExpDateChk.Checked)
    {
    $true{
    $DisableAccountCHK.Checked = $false
    $DisableAccountCHK.Enabled = $false
    $MvAccountCHK.Checked = $false
    $MvAccountCHK.Enabled = $false
    $RmvGrpCHK.Checked = $false
    $RmvGrpCHK.Enabled = $false
    }

    $false{
    $DisableAccountCHK.Enabled = $true
    $MvAccountCHK.Enabled = $true
    $RmvGrpCHK.Enabled = $true
    }
    }

    }

    $handler_ClearRsltsBtn_Click={
    $RsltsTxtbx.Clear()
    $DisableAccountCHK.Checked = $false
    $MvAccountCHK.Checked = $false
    $RmvGrpCHK.Checked = $false
    $ResetPwdCHK.Checked = $false
    $ExpDateChk.Checked = $false
    }

    #----------------------------------------------
    # Generated Events
    #----------------------------------------------

    $Form_StateCorrection_Load=
    {
    #Correct the initial state of the form to prevent the .Net maximized form issue
    $form1.WindowState = $InitialFormWindowState
    }

    #----------------------------------------------
    #region Generated Form Code
    #----------------------------------------------
    #
    # form1
    #
    $form1.Controls.Add($ResetFormBtn)
    $form1.Controls.Add($datetimepicker1)
    $form1.Controls.Add($ExpDateChk)
    $form1.Controls.Add($PwdLbl)
    $form1.Controls.Add($PwdTxtBx)
    $form1.Controls.Add($CancelButton)
    $form1.Controls.Add($OKbtn)
    $form1.Controls.Add($RsltsTxtbx)
    $form1.Controls.Add($RmvGrpCHK)
    $form1.Controls.Add($MvAccountCHK)
    $form1.Controls.Add($ResetPwdCHK)
    $form1.Controls.Add($DisableAccountCHK)
    $form1.Controls.Add($UserNameTxtbx)
    $form1.Controls.Add($DomainComboBox)
    $form1.AcceptButton = $OKbtn
    $form1.CancelButton = $CancelButton
    $form1.ClientSize = New-Object System.Drawing.Size(557,412)
    $form1.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $form1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,0,3,1)
    $form1.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)


    $form1.KeyPreview = $True
    $form1.Name = "form1"
    $form1.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen 
    $form1.Text = "Employee Termination Tool"
    $form1.add_Load($FormEvent_Load)
    #
    # ResetFormBtn
    #
    $ResetFormBtn.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $ResetFormBtn.Location = New-Object System.Drawing.Point(454,9)
    $ResetFormBtn.Name = "ResetFormBtn"
    $ResetFormBtn.Size = New-Object System.Drawing.Size(91,23)
    $ResetFormBtn.TabIndex = 15
    $ResetFormBtn.Text = "Reset Form"
    $ResetFormBtn.UseVisualStyleBackColor = $True
    $ResetFormBtn.add_Click($handler_ClearRsltsBtn_Click)
    #
    # datetimepicker1
    #
    $datetimepicker1.CustomFormat = "MM/dd/yyyy 12:00:00"
    $datetimepicker1.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $datetimepicker1.Location = New-Object System.Drawing.Point(334,69)
    $datetimepicker1.Name = "datetimepicker1"
    $datetimepicker1.Size = New-Object System.Drawing.Size(211,20)
    $datetimepicker1.TabIndex = 14
    $datetimepicker1.TabStop = $False
    $datetimepicker1.Value = "12/21/2011 23:59:00"
    #
    # ExpDateChk
    #
    $ExpDateChk.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $ExpDateChk.Location = New-Object System.Drawing.Point(334,41)
    $ExpDateChk.Name = "ExpDateChk"
    $ExpDateChk.Size = New-Object System.Drawing.Size(130,20)
    $ExpDateChk.TabIndex = 13
    $ExpDateChk.Text = "Set Expiration Date"
    $ExpDateChk.UseVisualStyleBackColor = $True
    $ExpDateChk.add_CheckStateChanged($handler_ExpDateChk_CheckStateChanged)
    #
    # PwdLbl
    #
    $PwdLbl.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left 
    $PwdLbl.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $PwdLbl.Location = New-Object System.Drawing.Point(6,362)
    $PwdLbl.Name = "PwdLbl"
    $PwdLbl.Size = New-Object System.Drawing.Size(100,14)
    $PwdLbl.TabIndex = 12
    $PwdLbl.Text = "Password"
    #
    # PwdTxtBx
    #
    $PwdTxtBx.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left 
    $PwdTxtBx.BackColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
    $PwdTxtBx.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $PwdTxtBx.Location = New-Object System.Drawing.Point(6,377)
    $PwdTxtBx.Name = "PwdTxtBx"
    $PwdTxtBx.ReadOnly = $True
    $PwdTxtBx.Size = New-Object System.Drawing.Size(162,20)
    $PwdTxtBx.TabIndex = 11
    $PwdTxtBx.TabStop = $False
    #
    # CancelButton
    #
    $CancelButton.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right 
    $CancelButton.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel 
    $CancelButton.Location = New-Object System.Drawing.Point(389,377)
    $CancelButton.Name = "CancelButton"
    $CancelButton.Size = New-Object System.Drawing.Size(75,23)
    $CancelButton.TabIndex = 7
    $CancelButton.Text = "Close"
    $CancelButton.UseVisualStyleBackColor = $True
    #
    # OKbtn
    #
    $OKbtn.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right 
    $OKbtn.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $OKbtn.Location = New-Object System.Drawing.Point(470,377)
    $OKbtn.Name = "OKbtn"
    $OKbtn.Size = New-Object System.Drawing.Size(75,23)
    $OKbtn.TabIndex = 6
    $OKbtn.Text = "OK"
    $OKbtn.UseVisualStyleBackColor = $True
    $OKbtn.add_Click($handler_OKbtn_Click)
    #
    # RsltsTxtbx
    #
    $RsltsTxtbx.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right 
    $RsltsTxtbx.BackColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
    $RsltsTxtbx.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $RsltsTxtbx.Location = New-Object System.Drawing.Point(6,99)
    $RsltsTxtbx.Multiline = $True
    $RsltsTxtbx.Name = "RsltsTxtbx"
    $RsltsTxtbx.ReadOnly = $True
    $RsltsTxtbx.ScrollBars = [System.Windows.Forms.ScrollBars]::Both 
    $RsltsTxtbx.Size = New-Object System.Drawing.Size(539,260)
    $RsltsTxtbx.TabIndex = 8
    $RsltsTxtbx.TabStop = $False
    #
    # RmvGrpCHK
    #
    $RmvGrpCHK.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $RmvGrpCHK.Location = New-Object System.Drawing.Point(158,69)
    $RmvGrpCHK.Name = "RmvGrpCHK"
    $RmvGrpCHK.Size = New-Object System.Drawing.Size(180,24)
    $RmvGrpCHK.TabIndex = 5
    $RmvGrpCHK.Text = "Remove Group Membership"
    $RmvGrpCHK.UseVisualStyleBackColor = $True
    #
    # MvAccountCHK
    #
    $MvAccountCHK.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $MvAccountCHK.Location = New-Object System.Drawing.Point(158,39)
    $MvAccountCHK.Name = "MvAccountCHK"
    $MvAccountCHK.Size = New-Object System.Drawing.Size(170,24)
    $MvAccountCHK.TabIndex = 3
    $MvAccountCHK.Text = "Move to Disabled Users OU"
    $MvAccountCHK.UseVisualStyleBackColor = $True
    #
    # ResetPwdCHK
    #
    $ResetPwdCHK.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $ResetPwdCHK.Location = New-Object System.Drawing.Point(11,69)
    $ResetPwdCHK.Name = "ResetPwdCHK"
    $ResetPwdCHK.Size = New-Object System.Drawing.Size(139,24)
    $ResetPwdCHK.TabIndex = 4
    $ResetPwdCHK.Text = "Reset AD Password"
    $ResetPwdCHK.UseVisualStyleBackColor = $True
    #
    # DisableAccountCHK
    #
    $DisableAccountCHK.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $DisableAccountCHK.Location = New-Object System.Drawing.Point(11,39)
    $DisableAccountCHK.Name = "DisableAccountCHK"
    $DisableAccountCHK.Size = New-Object System.Drawing.Size(139,24)
    $DisableAccountCHK.TabIndex = 2
    $DisableAccountCHK.Text = "Disable AD Account"
    $DisableAccountCHK.UseVisualStyleBackColor = $True
    #
    # UserNameTxtbx
    #
    $UserNameTxtbx.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $UserNameTxtbx.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
    $UserNameTxtbx.Location = New-Object System.Drawing.Point(158,12)
    $UserNameTxtbx.Name = "UserNameTxtbx"
    $UserNameTxtbx.Size = New-Object System.Drawing.Size(164,20)
    $UserNameTxtbx.TabIndex = 1
    $UserNameTxtbx.Text = "Enter SAM Account Name"
    $UserNameTxtbx.add_Click($hanlder_txtbox_Click)
    #
    # DomainComboBox
    #
    $DomainComboBox.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $DomainComboBox.FormattingEnabled = $True
    [void]$DomainComboBox.Items.Add("DOMAIN1")
    [void]$DomainComboBox.Items.Add("DOMAIN2")
    $DomainComboBox.Location = New-Object System.Drawing.Point(11,12)
    $DomainComboBox.Name = "DomainComboBox"
    $DomainComboBox.Size = New-Object System.Drawing.Size(121,21)
    $DomainComboBox.TabIndex = 0
    $DomainComboBox.Text = "Select Domain"
    #endregion Generated Form Code


    #----------------------------------------------


    #Save the initial state of the form
    $InitialFormWindowState = $form1.WindowState
    #Init the OnLoad event to correct the initial state of the form
    $form1.add_Load($Form_StateCorrection_Load)
    #Show the Form
    return $form1.ShowDialog()


    } #End Function


    #Call OnApplicationLoad to initialize
    if(OnApplicationLoad -eq $true)
    {
    #Create the form
    GenerateForm | Out-Null
    #Perform cleanup
    OnApplicationExit
    }

    Regards, Sumanth

    Tuesday, February 28, 2012 4:40 AM
  • You can use the following Function to get a User by a Given Property:

    Function Get-User {
    # Universal Function to get a Active Directory User over a unique Property
    
    Param ($PropertyName=$(throw "you must enter the Name of a User-Property, to search for the User!"), `
    $PropertyValue=$(throw 'you must enter the Value of the User-Property ($PropertyName), to search for the User!!'))
    
    $searcher=New-Object DirectoryServices.DirectorySearcher
    $searcher.Filter="(&(objectcategory=person)(objectclass=user)($PropertyName=$PropertyValue))"
    $results=$searcher.FindOne()
    
        if ($results.path.length -gt 1)
        {
           Return [ADSI]$results.Path
        }
        else
        {
           [System.Windows.Forms.MessageBox]::Show("User not found! With Property: $PropertyName = $PropertyValue", "User not found!", [Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning, [System.Windows.Forms.MessageBoxDefaultButton]::Button1, [System.Windows.Forms.MessageBoxOptions]::DefaultDesktopOnly) | Out-Null 
           Return $Null
        }
    } # END Function Get-User
    
    #Example to get the user over the sAMAccountname
    $User = Get-User "sAMAccountname" "Put-sAMAccountname-Here"
    
    #Example to get the user over the employeeID
    $User = Get-User "employeeID" "Put-employeeId-Here"

    For the RemoveGroups Function you have to Provide a USER !!!
    To provide a User you can here even use the Get-User Function from above, or you Stor the User Global in your script and use this global stored one.

    Function RemoveGroups {
    
    Param ($ADUser=$(throw "you must enter a User!"))
    
    try   {  
            foreach ($group in $ADuser.memberof)
            {
              $groupDE = [ADSI]"LDAP://$group" 
              #$groupDE.remove("LDAP://$($user.distinguishedName)")
              #$Rsltstxtbx.AppendText("Removed Group, $group`r`n")
              $Script:emailbody += "`n$group"
            } # END foreach
           
            # $Rsltstxtbx.AppendText("Groups Removed `r`n") 
            # send_email
            
          } # END try
    catch {
              #$errorProvider1.SetError($RsltsTxtbx.AppendText("Access Denied, Please verify actions with Active Directory tools`r`n"))}
          } # END catch
    } # END Function RemoveGroups
    
    
    $emailbody = ""
    RemoveGroups $(Get-User "sAMAccountname" "ekriegp")
    $emailbody

    To send e-mail in HTML see:

    Get-Help ConvertTo-Html

    Please click “Mark as Answer” if my post answers your question and click Vote as Help if my Post helps you.
    Bitte markiere hilfreiche Beiträge von mir als Hilfreich und Beiträge die deine Frage ganz oder teilweise beantwortet haben als Antwort.
    My PowerShell Blog http://www.admin-source.info
    [string](0..21|%{[char][int]([int]("{0:d}" -f 0x28)+('755964655967-86965747271757624-8796158066061').substring(($_*2),2))})-replace



    Tuesday, February 28, 2012 1:28 PM
  • Hello Peter,

    Thanks for reply Group display got resolved.

    And for searching user with employee ID using get-user i am getting error

    "The term 'Get-User' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again".

    Please help.


    Regards, Sumanth

    Thursday, March 01, 2012 10:08 AM
  • Do you have included the Function Get-User from my Post above BEVORE you call this Function !?

    Please click “Mark as Answer” if my post answers your question and click Vote as Help if my Post helps you.
    Bitte markiere hilfreiche Beiträge von mir als Hilfreich und Beiträge die deine Frage ganz oder teilweise beantwortet haben als Antwort.
    My PowerShell Blog http://www.admin-source.info
    [string](0..21|%{[char][int]([int]("{0:d}" -f 0x28)+('755964655967-86965747271757624-8796158066061').substring(($_*2),2))})-replace

    Thursday, March 01, 2012 11:03 AM
  • Thanks did miss to add Function get-user. Thanks for the support.


    Regards, Sumanth

    Monday, March 05, 2012 6:25 AM