Remote Item Removal Script

Remotely remove items from systems such as registry items or file system objects.
Define the $servers variable using one of the provided methods.

Define the $items variable with the items you wish to remove from the remote systems.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Remote Removal Script
# Removes items such as registry keys and files
#
# Define each item within the $items variable.
# 'C:\My\File\Path.txt'
# 'HKLM:\Software\abc\123'
#
# Define the targets with the $servers variable
# Use hardcoded, Get-ADComputer, Get-ADDomainController, or Get-Content to populate the variable.
#
# ======================================================
cls

$servers = ""
#$servers = Get-ADComputer                            
#$servers = Get-ADDomainController                    
#$servers = Get-Content "C:\Users\Public\servers.txt"  

$Scriptblock = {
   
    #region LocalCode
    # Run just the portion in this region to clean the local machine only
    $server = $env:COMPUTERNAME
    $items = @('C:\Program Files\123','C:\ProgramData\123','C:\ProgramData\456',`
    'HKLM:\Software\abcd32\folder32.2','HKLM:\Software\abcd64\Folder32.1',`
    'HKLM:\software\abcd64\Folder32.2')

    ForEach($item in $items){
        if (test-path $item -ErrorAction SilentlyContinue ){
            Remove-Item $item -WhatIf
            sleep -Milliseconds 250
            if (test-path $item -ErrorAction SilentlyContinue){
                    Write-Host "$server : Removal of $item failed..." -ForegroundColor Red
            }else{
                    Write-Host "$server : Removal of $item was successful..." -ForegroundColor Green
            }
        }
    }
    #endregion LocalCode
}

Invoke-Command -ComputerName $servers -ScriptBlock $Scriptblock

# CMDLET Reference Documentation
#
# https://docs.microsoft.com/en-us/powershell/module/activedirectory/get-adcomputer?view=winserver2012-ps
# https://docs.microsoft.com/en-us/powershell/module/activedirectory/get-addomaincontroller?view=winserver2012-ps
# https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content?view=powershell-5.0

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.