Powershell AD computer add to group help RRS feed

  • Question

  • I have created a script its running fine i just want to add a logic in the script if the computer object is not exists in AD it will give a pop up "Computer not exists in AD"

    Any help is appreciated. 

       $ListApps = "Office"
       $Global:computers = gc C:\Serverlist.txt
       if (!$ListApps) {
            [System.Windows.Forms.MessageBox]::Show("Please select an AD group","Sorry!",[windows.forms.messageboxbuttons]::Ok, [windows.forms.messageboxicon]::Warning) 
        else {
            $AppGroup = $ListApps
            $Group = Get-ADGroup -Identity $AppGroup 
                foreach ($Hostname in $Computers){
                    $member = Get-ADComputer -Identity "$Hostname" -Properties MemberOf | Select-Object MemberOf
                    $pc = Get-ADComputer "$Hostname" | Select -expand SamAccountName
                    if ($member.Memberof -like "$Group"){
                        [System.Windows.Forms.MessageBox]::Show("$Hostname is already a member of $AppGroup","Whoops!",[windows.forms.messageboxbuttons]::Ok, [windows.forms.messageboxicon]::Question)
                    else {
                        Add-ADGroupMember $AppGroup $pc -passthru
                        [System.Windows.Forms.MessageBox]::Show("$Hostname has been added to $AppGroup", "Success!",[windows.forms.messageboxbuttons]::Ok, [windows.forms.messageboxicon]::Information)  


    Tuesday, December 12, 2017 8:38 AM

All replies

  • If the computer doesn't exist the code will cause an error.

    if(Get-AdComputer -Filter "Name -eq 'mypc'"){
         # computer found
         # computer not found


    Tuesday, December 12, 2017 9:39 AM