Technical Article

PowerShell Query to remove backup folders against multiple servers

,

Open Powershell IDE in Admin mode

Copy and paste the script

Change the serverlist path and output path

Change the location of the backup folders as per your requirement

Run the script.

Note: To achieve this task, your system should have Powershell 2.0 or later version installed.

import-module "SQLPS" -DisableNameChecking
set-executionpolicy unrestricted

set-location "C:\Delete_backup_folders\";
$ErrorActionPreference = "SilentlyContinue";

$servers = get-content "C:\Delete_backup_folders\serverlist.txt";

$filePathOutput = "C:\Delete_backup_folders\Output_serverlist.txt";

$cyclecount = 1;

try
{

foreach ($server in $servers)
{


    "****SERVER NAME****:$($server)" | out-file $filePathOutput  -append
"----------------------------------------------------------------------" | out-file $filePathOutput  -append
  Remove-Item "\\$server\C$\MSSQL`$XX1\backup\Folder1" -force -Recurse
  Remove-Item "\\$server\E$\MSSQL`$XX1\backup2\Folder2" -force -Recurse
  Remove-Item "\\$server\F$\MSSQL`$XX1\backup\Folder3" -force -Recurse
  Remove-Item "\\$server\D$\MSSQL`$XX1\backup\Folder4" -force -Recurse
  

  Write-Host "Processing Server: $($server), Cycle : $($cyclecount)" -Fore Red
  Invoke-Sqlcmd -ServerInstance $server -Database "master" -Connectiontimeout 20 -QueryTimeout 40 | Out-File -filePath "C:\Delete_backup_folders\Output_serverlist.txt" -Append
     
  Write-Host "Processing completed on Server: $($server)" -Fore Green;

    $cyclecount += 1

  }
  
 }

 catch
      {
                Write-Warning "Error processing command";
                $error[0];
                $Exception = $Error[0].Exception
               
     }

finally
  {
   $ErrorActionPrefernce = $eap
  }

Rate

3 (2)

You rated this post out of 5. Change rating

Share

Share

Rate

3 (2)

You rated this post out of 5. Change rating