If you would like to delete a file or folder using PowerShell, check out How Can I Delete a File or Folder from the Command Line Using Windows PowerShell? on Petri instead.
Let’s start by running a simple command to move a single file or folder. Make sure you are logged into the server or PC with an account that has full access to the objects you want to move.
The command above will move ‘testfolder’, and all its contents, to c:\temp. Additionally, the –Force parameter can be added to move hidden or read-only files.
Before you can perform more complex move operations, you need to select the files that you want to move using either Get-Item or Get-ChildItem. I’ll explain the difference between the cmdlets below.
If you want to get all .txt files in testfolder and any subfolders, use Get-ChildItem with the -Recurse parameter instead of Get-Item. Get-Item doesn’t support the -Recurse parameter.
Get-ChildItem –Path c:\testfolder\*.txt -Recurse
And then pipe the results to Move-Item:
Get-ChildItem –Path c:\testfolder\*.txt -Recurse | Move-Item -Destination c:\temp
Because the above command line doesn’t recreate the directory structure in the destination folder, you cannot move two files with the same name. So, when using PowerShell to move files, it’s best to work with one source and destination folder at a time. Robocopy is a good tool for managing large and complex move operations.
Let’s make things simpler and go back to using Get-Item.
Get-Item –Path c:\testfolder\* -Include *test*
Any file or folder in c:\testfolder, with the word test in its name will be displayed in the results.
Get-Item –Path c:\testfolder\* -Exclude *test* | Move-Item -Destination c:\temp -WhatIf
Get-Item –Path c:\testfolder\* -Exclude *test* | Move-Item -Destination c:\temp
With the basic operations that I’ve shown you in this article, using Move-Item, Get-Item, and Get-ChildItem, you should be able to perform most file/folder move tasks with PowerShell.
If you have more complex requirements, check out Robocopy. It’s a built-in command-line tool in Windows and Windows Server. And if you would like to delete files using PowerShell, check out How Can I Delete a Folder or File from the Command Line Using Windows PowerShell? on Petri.