How to remove computers from a group (PowerShell)

Introduction

This script could be used to remove computers from a group.

Scenarios

Sometimes, AD admin need to remove some computers from a group.

Script

This script contains one advanced function, Remove-OSCComputer. You can use this script in following ways:

Method 1:

  1. Download the script and open the script file with Notepad or any other script editors.
  2. Scroll down to the end of the script file, and then add the example command which you want to run.
  3. Save the file then run the script in PowerShell.

Method 2:

  1. Rename scriptname.ps1 to scriptname.psm1 (PowerShell Module file)
  2. Run Import-Module cmdlet to import this module file.
    Import-Module filepath\scriptname.psm1

Examples

Example 1: Remove computer "test1","test2" form group GPO
Command: Remove-OSCComputer -ComputerName "test1","test2" -GroupName GPO
Screenshot:

Example 2: Remove computers form group GPO according to a text file
Command: Remove-OSCComputer -FilePath "C:\ComputerList.txt" -GroupName GPO
Screenshot:

Note  The file format should be like this:

test1
test2
test3

Here are some code snippets for your references. To get the complete script sample, please click the download button at the beginning of this page.

PowerShell
Edit|Remove
If($ComputerName) 
{ 
    #Remove specified computer from specified group 
    Foreach($Item in $ComputerName) 
    { 
     RemoveCompter $Item $GroupName 
    }} 
Else 
{ 
    #Get the content of the specified file 
    $ComputerName =  Get-Content -Path $FilePath  
    Foreach($Item in $ComputerName ) 
    { 
        #Remove one by one 
        RemoveCompter $Item $GroupName 
    }}

Prerequisite

PowerShell

Windows Server 2008R2 or later version