Inconsistent Behavior with Get-ADGroup

Welcome Forums General PowerShell Q&A Inconsistent Behavior with Get-ADGroup

This topic contains 1 reply, has 1 voice, and was last updated by

 
Participant
1 month, 4 weeks ago.

  • Author
    Posts
  • #114121

    Participant
    Points: 26
    Rank: Member

    I am working on a script for a company to decommission old VMware Servers. Part of this is to remove the A.D. object, any Security Groups associated with the server name, DNS entries, etc. Most of the script is working, but the deletion of security groups is giving me fits. Security groups for the server are usually along the lines of _RDP, _LocalAdmins, _UserAccess_DL, etc. So this works just fine for finding all of the associated groups:

    
    Get-ADGroup -Filter {(name -like "MyServer7101*")} | Out-GridView
    
    

    However, this does not work:

    
    $sMachine = "MyServer7101"
    
    Get-ADGroup -Filter {(name -like "$($sMachine)*")} | Out-GridView
    
    

    I even tried something like this, but no joy:

    
    $sMachine = "MyServer7101"
    
    Get-ADGroup -Filter {(name -like "$($sMachine)*RDP*")} | Out-GridView
    
    

    This does work, but obviously is going to be very slow (10 seconds rather than sub-one second), so is not my first choice.

    
    Get-ADGroup -Filter * | where {$_.Name -match $sMachine} | Out-GridView
    
    

    Just curious if I am somehow borking the syntax. I have looked up examples online and they all seem to be the same way I am doing it, but using hard-coded strings rather than a variable. I did not find any examples using a variable in a for loop.

  • #114123

    Participant
    Points: 26
    Rank: Member

    Sorry, on two counts. Not sure why it duplicated my post. Also, as always happens, no sooner do I give up searching and post a question than I find the answer. Apparently, it is better to build a string for the filter when using a variable, rather than a code block. So this:

    
    $sMachine = "MyServer7101"
    
    Get-ADGroup -Filter "name -like '$($sMachine)*'" | Out-GridView
    
    

    ...works just fine once I lose the block

You must be logged in to reply to this topic.