Powershell GPO Backup - want to delete old backup

Hi Powershell Folks

I have a good working Powershell script that takes GPO backup

I want the backup will remove the old folder and put a new folder,

like that :wink:

**************************************** REMOVE OLD FOLDER*****

##Check for an existing backup at Target Network Location
$oldbackup = Test-Path -Path "\\SERVER\GPO_Backup\GPO\"
if ($oldbackup){
remove-item -Path "\\SERVER\GPO_Backup\GPO\" -Recurse -Force
}

*************************************************************************GPO BACKUP****

Import-Module grouppolicy
$date = get-date -format yyyy-MM-d
New-Item -Path \\SERVER\GPO_Backup\GPO\$date -ItemType directory
Backup-Gpo -All -Path \\SERVER\GPO_Backup\GPO\$date

Please help me

Sokoban

@Sokoban you can try below Style as well :slight_smile:

Function Remove-backup {
if(Test-Path -path "\\SERVER\GPO_Backup\GPO"){
Remove-Item -path "\\SERVER\GPO_Backup\GPO\" -ErrorAction stop 
}
else{
Write-Error "Share Path Is not Found" -ErrorAction continue
}
try{ 
New-Item -Path "\\SERVER\GPO_Backup\GPO\$($(Get-date).tostring('yyyy-MM-d'))" -ItemType directory -ErrorAction Stop
$newfolder=$($(Get-date).tostring('yyyy-MM-d')) 
}
catch{
Write-Error "[Error:]$error[0].Exception.Message"

}
Return $newfolder
}

Import-Module grouppolicy
$removebackup=Remove-backup
Backup-Gpo -All -Path "\\SERVER\GPO_Backup\GPO\$removebackup"

 

Thanks,
Nitesh

You can do like this as well

Function Remove-backup {
if(Test-Path -path "\\SERVER\GPO_Backup\GPO"){
Remove-Item -path "\\SERVER\GPO_Backup\GPO\" -ErrorAction stop 
}
else{
Write-Error "Share Path Is not Found" -ErrorAction continue
}
try{ 
New-Item -Path "\\SERVER\GPO_Backup\GPO\$($(Get-date).tostring('yyyy-MM-d'))" -ItemType directory -ErrorAction Stop
$newfolder=$($(Get-date).tostring('yyyy-MM-d')) 
}
catch{
Write-Error "[Error:]$error[0].Exception.Message"

}
Return $newfolder
}

Import-Module grouppolicy
$removebackup=Remove-backup
Backup-Gpo -All -Path "\\SERVER\GPO_Backup\GPO\$removebackup"