PowerShell copy .bak files and move them to another folder


My boss requested from me to move all the .bak files from one drive to another on the same SQL Server box and then delete the old files.



This is a quick PowerShell script that will get the job done.



<#Changes Directory and removes all the old files .bak and then copies all .bak files to the destination path #>
cd C:\Scripts\
Get-ChildItem | Where-Object {$_.Extension -like “.bak*”} | Remove-Item

#Gets all .bak files and copies them over to destination

cd D:\folder\folder\
Get-ChildItem | Where-Object {$_.Extension -like “.bak*”} | Copy-Item -Destination C:\Scripts


More Information on cmdlets

The Get-ChildItem cmdlet gets the items in one or more specified locations. If the item is a container, it gets the items inside the container, known as child items. You can use the -Recurse parameter to get items in all child containers and use the -Depth parameter to limit the number of levels to recurse.



The Remove-Item cmdlet deletes one or more items. Because it is supported by many providers, it can delete many different types of items, including files, folders, registry keys, variables, aliases, and functions.



The Copy-Item cmdlet copies an item from one location to another location in the same namespace. For instance, it can copy a file to a folder, but it cannot copy a file to a certificate drive.

This cmdlet does not cut or delete the items being copied. The particular items that the cmdlet can copy depend on the Windows PowerShell provider that exposes the item. For instance, it can copy files and directories in a file system drive and registry keys and entries in the registry drive.