PowerShell scripting -Deleting files on multiple servers

First I would like to  share with you the script so you can take a look and analyze how it works.

$Computerlist = get-content C:\XXXXXXXX\Servers.txt

Foreach ($computer in $Computerlist) {
GetChildItem Path \\$computer\c$\XXXXXXX\*.* Include *.* Recurse Force | RemoveItem Force
 {
 

The story of this script

Recently I was in the need to create a PowerShell script to delete content of specific folder on 300+ servers.

It was a critical task since It consisted on canceling software installation because of an emergency.

At the beginning it looked easy, I though it was just a “Remove-Item” script and getting list of servers from a .TXT file. As you can see, that was not big deal! , just go to each server, select the files to be removed and done!

But then I realized it was more complicated than I though.

First, I used the command “Remove-Item” and the path where files were located. It worked fine running it locally on a single server, but when trying to run it on multiple servers, I got an error message stating “Remove-Item: Cannot find path “xxxxx” 

It was weird cause I wrote all the correct lines like “for each” and mapped $computer” list and so for.
I started running in circles and took next step: research on Internet and at the end I learned something very interesting.
I researched on PowerShell base of knowledge and some blogs and found that sometimes PowerShell needs to be pointed specifically to the path we need to work with, this is achieved by using the “GetChildItem” command.

In addition to that, I had to map the $computer variable by adding \\$computer as part of “Get-Childitem “

After that small change and rewriting my script, everything ran correctly

Hope this PowerShell script helps you on your daily activities

signature2