Delete files based on the list of computers

Delete Files from Remote computers

The following PowerShell script recipe will help you delete a remote file based on a list of computers stored in a text file. New PowerShell function will be created during the session which will be piped from the text file.

############################## Script – 1###########################################

function delete-remotefile {
    PROCESS {
                $file = “\\$_\c$\install.exe”
                if (test-path $file)
                {
                echo “$_ install.exe exists”
                Remove-Item $file -force
                echo “$_ install.exe file deleted”
                }
            }
}
 
Get-Content  C:\Scripts\Serverlist.txt| delete-remotefile

 

 

#############################Script – 2 ###########################################

function delete-remotefile1 {
PROCESS {
$file = “\\$_\c$\Common Folders”
if (test-path $file)
{
echo “$_ file exists”
Remove-Item $file -force -recurse
echo “$_ file deleted”
}
}
}

function delete-remotefile2 {
PROCESS {
$file = “\\$_\c$\Profiles”
if (test-path $file)
{
echo “$_ file exists”
Remove-Item $file -force -recurse
echo “$_ file deleted”
}
}
}

Get-Content  C:\Users\sfa\Desktop\PCList.txt | delete-remotefile1 | delete-remotefile2

 

#########################Script – 3 ############################################

#Creating an array of your folders
$filelist = @(” \c$\Common Folders”, “\c$\Profiles”)
#Storing file content as computerlist
$computerlist = Get-Content  C:\Users\sfa\Desktop\PCList.txt
#We go for a loop for every computer…
foreach ($computer in $computerlist)
{
Write-Host -ForegroundColor Yellow “Analysing $computer”
#And for every file in the filelist
foreach ($file in $filelist)
{
#We recreate the UNC filepath
$newfilepath = Join-Path “\\$computer\” “$filelist”
if (test-path $newfilepath)
{
Write-Host “$newfilepath file exists”
try
{
#We try to remove…
Remove-Item $newfilepath -force -recurse -ErrorAction Stop
}
catch
{
#And there will be an error message if it fails
Write-host “Error while deleting $newfilepath on $computer.`n$($Error[0].Exception.Message)”
#We skip the rest and go back to the next object in the loop
continue
}
#if SUCCESS!!1!1! …
Write-Host  “$newfilepath file deleted”
}
}

}

Be the first to comment

Leave a Reply

Your email address will not be published.


*