PowerShell: Create, Delete, Copy, Rename and Move Files (2023)

Every day, sysadmins have to perform various standard operations on the numerous files and folders on their Windows servers. These tasks often include managing users’ data on shared resources and maintaining backups properly. You can use PowerShell to reduce amount of manual work involved.

Before you start, make sure your system policy allows running PowerShell scripts as described in “Windows PowerShell Scripting Tutorial for Beginners.”

View the objects in a directory

To view the content of a directory on a Windows file server, use the Get-ChildItem cmdlet. To show all hidden files, add the -Force parameter. The command below shows all root objects in the Shared folder:

Get-ChildItem -Force \fsShared

If you want to also check all subfolders and their content, add -Recurse parameter:

Get-ChildItem -Force \fsShared -Recurse

To filter the output, add the Filter, Exclude, Include and Path parameters to the Get-ChildItem cmdlet. For advanced object filtering, use the Where-Object cmdlet. The script below searches for all executable files in the IT folder that were modified after April 1, 2018:

Get-ChildItem -Path \fsSharedIT -Recurse -Include *.exe | Where-Object -FilterScript {($_.LastWriteTime -gt '2018-04-01')}

Create files and folders with PowerShell

To create new objects with Windows PowerShell, you can use the New-Item cmdlet and specify the type of item you want to create, such as a directory, file or registry key.

For example, this command creates a folder:

New-Item -Path '\fsSharedNewFolder' -ItemType Directory

And this command creates an empty file:

New-Item -Path '\fsSharedNewFoldernewfile.txt' -ItemType File

Create files and writing data to them

There are at least two built-in methods to create a file and write data to it. The first is to use the Out-File cmdlet:

$text = 'Hello World!' | Out-File $text -FilePath C:datatext.txt

To overwrite an existing file, use the –Force switch parameter.

You can also create files using the Export-Csv cmdlet, which exports the output into a csv file that can be opened in Excel:

Get-ADuser -Filter * | Export-Csv -Path C:dataADusers.csv

Create files after checking that they don’t already exist

The following script checks whether a specific file (pc.txt) already exists in a particular folder; if not, it generates a list of all AD computers and saves it to a new file named pc.txt:

#create array of text files$files=Get-ChildItem C:data*.txt | select -expand fullname#check if file exists inside the array$files -match "pc.txt"#if matching return “True” key then exit, if “False” then create a reportif($files -eq 'False'){Get-ADComputer -Filter * | Export-Csv -Path C:datapc.txt}else{exit}

Delete files and folders with PowerShell

To delete objects, use the Remove-Item cmdlet. Please note that it requires your confirmation upon execution if the object is not empty. The example below demonstrates how to delete the IT folder and all the subfolders and files inside it:

Remove-Item -Path '\fssharedit'ConfirmThe item at \pdcsharedit has children and the Recurse parameter was notspecified. If you continue, all children will be removed with the item. Are yousure you want to continue?[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help(default is "Y"):

If you have already made sure that every object inside the folder should be deleted, you can use the ?Recurse switch to skip the confirmation step:

Remove-Item -Path '\fssharedit' -Recurse

Delete files and folders older than X days

Sometimes you need to clean up old files from a certain directory. Here’s the way to accomplish that:

$Folder = "C:Backups"#delete files older than 30 daysGet-ChildItem $Folder -Recurse -Force -ea 0 |? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-30)} |ForEach-Object { $_ | del -Force $_.FullName | Out-File C:logdeletedbackups.txt -Append}#delete empty folders and subfolders if any existGet-ChildItem $Folder -Recurse -Force -ea 0 |? {$_.PsIsContainer -eq $True} |? {$_.getfiles().count -eq 0} |ForEach-Object { $_ | del -Force $_.FullName | Out-File C:logdeletedbackups.txt -Append}

Delete files after checking they exist

Here’s how to check whether a file exists and delete it if it does:

$FileName = 'C:datalog.txt'If (Test-Path $FileName){ Remove-Item $FileName}

Delete files from multiple computers in one script

To delete files from remote PCs, you must have the appropriate security permissions to access them. Be sure to use UNC paths so the script will correctly resolve the file locations.

$filelist = @(" c$Temp", "c$Backups") #variable to delete files and folder$computerlist = Get-Content C:datapc.txt #get list of remote pc's foreach ($computer in $computerlist){ foreach ($file in $filelist){ $filepath= Join-Path "\$computer" "$filelist" #generate unc paths to files or folders if (Test-Path $filepath) { Remove-Item $filepath -force -recurse -ErrorAction Continue}}}

Copy files and folders with PowerShell

The Copy-Item cmdlet enables you to copy objects from one path to another. The following command creates a backup by copying the file users.xlsx from one remote computer (fs) and saving it to another (fs2) over the network:

Copy-Item -Path \fsShareditusers.xlsx -Destination \fs2Backupsitusers.xlsx

If the target file already exists, the copy attempt will fail. To overwrite the existing file, even if it is in Read-Only mode, use the -Force parameter:

Copy-Item -Path \fsShareditusers.xlsx -Destination \fs2Backupsitusers.xlsx -Force

Copy files with PowerShell to or from a remote computer

If you’re copying files to or from remote computers, be sure to use UNC paths.

For example, use this command to copy files from a remote file server to the local C: directory:

Copy-Item \fsc$temp -Recurse C:data

To copy files from your local directory to the remote folder, simply reverse the source and destination locations:

Copy-Item C:data -Recurse \fsc$temp

Copy multiple files from one server to another over the network in one script

You can also copy files from one remote server to another. The following script recursively copies the \fsSharedtemp folder to \fsSharedtest:

Copy-Item \fsSharedtemp -Recurse \fsSharedtest

Copy only certain types of files

To copy only certain files from the source content to the destination, use the -Filter parameter. For instance, the following command copies only txt files from one folder to another:

Copy-Item -Filter *.txt -Path \fsSharedit -Recurse -Destination \fs2Sharedtext

Copy files using XCOPY and ROBOCOPY commands or COM objects

You can also run XCOPY and ROBOCOPY commands to copy files, or use COM objects as in the example below:

(New-Object -ComObject Scripting.FileSystemObject).CopyFile('\fsShared', 'fs2Backup')

Move files and directories with PowerShell

The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location to another. It can also move a file or subdirectory from one directory to another location.

The following command moves a specific backup file from one location to another:

Move-Item -Path \fsSharedBackups1.bak -Destination \fs2Backupsarchive1.bak

This script moves the entire Backups folder and its content to another location:

Move-Item -Path \fsSharedBackups -Destination \fs2Backupsarchive

The Backups directory and all its files and subfolders will then appear in the archive directory.

Rename files with PowerShell

The Rename-Item cmdlet enables you to change the name of an object while leaving its content intact. It’s not possible to move items with the Rename-Item command; for that functionality, you should use the Move-Item cmdlet as described above.

The following command renames a file:

Rename-Item -Path "\fsSharedtemp.txt" -NewName "new_temp.txt"

Rename multiple files

To rename multiple files at once, use a script like this:

$files = Get-ChildItem -Path C:Temp #create list of filesforeach ($file in $files){ $newFileName=$file.Name.Replace("A","B") #replace "A" with "B" Rename-Item $file $newFileName}

Change file extensions with PowerShell

You can also use the Rename-Item to change file extensions. If you want to change the extensions of multiple files at once, use the Rename-Item cmdlet with the Get-ChildItem cmdlet.

The following script changes all “txt” file extensions to “bak”. The wildcard character (*)ensures that all text files are included:

Get-ChildItem \fsSharedLogs*.txt | Rename-Item -NewName { $_.name -Replace '.txt$','.bak' }

Using the information in this article, you can automate a variety of simple operations related to file management on your file storages and save time for more important tasks. Good luck!

FAQ

How can I create a file?

Use the New-Item cmdlet to create a file:

New-Item -Path '\fsSharedNewFoldernewfile.txt' -ItemType File

Creating a file overwrites any existing one with the same name, so you might need to check whether the file already exists.
You can also use the New-Item cmdlet to create folders, directories or registry keys.

How do I create a text file

To create a new object with Windows PowerShell, use the New-Item cmdlet and specify the type of item you want to create, like this:

New-Item -Path '\fsSharedNewFoldernewfile.txt' -ItemType File

You can use the New-Item cmdlet to create files, folders, directories and registry keys.

How do I create a directory

To create a new directory with PowerShell, use the New-Item cmdlet:

New-Item -Path '\fsSharedNewFolder' -ItemType Directory

You can also use the New-Item cmdlet to create files, folders or registry keys

How do I delete a file?

To delete an object, use the Remove-Item cmdlet. Confirmation will be requested upon execution if the object is not empty.

Remove-Item -Path '\fssharedit'

You can also delete all files older than X days or delete files from multiple computers with PowerShell.

How do I copy a file?

Use the Copy-Item cmdlet to copy objects from one path to another. The following command creates a backup by copying the file users.xlsx from one remote computer (fs) and to another (fs2) over the network:

Copy-Item -Path \fsShareditusers.xlsx -Destination \fs2Backupsitusers.xlsx

Note that if the target file already exists, the copy attempt will fail. Learn how to overwrite files when copying them from or to a remote computer.

How do I move a file?

The Move-Item cmdlet moves an item, including its properties, contents and child items, from one location to another:

Move-Item -Path \fsSharedBackups1.bak -Destination \fs2Backupsarchive1.bak

You can also move an entire folder with PowerShell.

How do I rename a file?

To rename a single file using PowerShell, use the following command:

Rename-Item -Path "\fsSharedtemp.txt" -NewName "new_temp.txt"

You can also rename multiple files using PowerShell.

PowerShell: Create, Delete, Copy, Rename and Move Files (1)

Ian Skur

Ian is a former Technical Marketing Specialist at Netwrix. He is an IT professional with more than 15 years of experience and an avid PowerShell blogger.

FAQs

How do I rename and move a file in PowerShell? ›

Use the Move-Item cmdlet in PowerShell to move the file to a different folder and rename it with the current date. What is this? In the above PowerShell script, the Move-Item cmdlet uses the -Path parameter to specify the source file name and the -Destination parameter to specify the destination folder path.

How do you move and rename multiple files in PowerShell? ›

To rename and move an item, use Move-Item . You can't use wildcard characters in the value of the NewName parameter. To specify a name for multiple files, use the Replace operator in a regular expression. For more information about the Replace operator, see about_Comparison_Operators.

How do I copy and move a file in PowerShell? ›

Make sure you are logged into the server or PC with an account that has full access to the objects you want to move.
  1. Open a PowerShell prompt by clicking Start and type PowerShell. ...
  2. In the PowerShell console, type Move-Item –Path c:\testfolder -Destination c:\temp and press ENTER.
Sep 20, 2021

What is the difference between rename-item and move-item in PowerShell? ›

The Rename-Item cmdlet changes the name of a specified item. This cmdlet does not affect the content of the item being renamed. You cannot use Rename-Item to move an item, such as by specifying a path together with the new name. To move and rename an item, use the Move-Item cmdlet.

What command can be used to both rename and move files? ›

Use the mv command to move files and directories from one directory to another or to rename a file or directory.

How do you delete files in PowerShell? ›

To delete files with PowerShell we need to use the Remove-Item cmdlet. This cmdlet can delete one or more items based on the criteria. The Remove-Item cmdlet can not only be used to delete files but also for deleting folders, registry keys, variables, functions, and more.

How do I bulk rename files in PowerShell? ›

PowerShell to Rename multiple files. You may have experienced the need to rename multiple files at once. To rename multiple files in PowerShell, you can use the Get-ChildItem cmdlet to get a list of the files you want to rename, and then pipe the list to the Rename-Item cmdlet.

How do you move and rename multiple files? ›

Open File Explorer, select the files you want to rename, and then press F2. The last file in the list is selected. Type the name you wish to use and press Enter. All the files you selected are given the same name with successive numbers in parentheses.

How do I copy multiple files in PowerShell? ›

A folder may contain files along with one or more subfolders that also need to be copied. In those situations, you can still use the Copy-Item cmdlet, but you will need to append the -Recurse parameter. The -Recurse parameter tells PowerShell to apply the command to the current folder and to all subfolders.

How do I move a file in shell script? ›

To move files, use the mv command (man mv), which is similar to the cp command, except that with mv the file is physically moved from one place to another, instead of being duplicated, as with cp.

What is the move-item command in PowerShell? ›

The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location to another location. The locations must be supported by the same provider. For example, it can move a file or subdirectory from one directory to another or move a registry subkey from one key to another.

How do I move multiple items in PowerShell? ›

The Move-Item cmdlet is used to move single and multiple files using PowerShell by specifying the source and destination path. Its syntax is given as Move-Item [-Path] <sourcepath> [-Destination] <destinationpath>.

What is the difference between the move and copy commands? ›

Copying – make a duplicate of the selected file or folder and place it in another location. Moving – move the original files or folder from one place to another (change the destination). The move deletes the original file or folder, while copy creates a duplicate.

How do I rename files in PowerShell? ›

To rename multiple files with PowerShell we will first need to get the files using the Get-ChildItem cmdlet. We can then pipe the Rename-Item cmdlet behind it, which will automatically take the file path. For the new file name, we will need to use the string replace function.

How do I move and rename a folder? ›

Rename files or folders

Go to the location where stores your file or folder. Right click the name of the file or folder you wish to rename. Click Rename (on the menu that opens up). Type a new name for the file and press Enter.

How do I rename or move files in git? ›

We use the git mv command in git to rename and move files. We only use the command for convenience. It does not rename or move the actual file, but rather deletes the existing file and creates a new file with a new name or in another folder.

How do I move to another folder in PowerShell? ›

Typing CD\ causes PowerShell to move to the root directory. As you can see, you can use the CD.. or CD\ command to move to a lower level within the folder hierarchy. You can also use the CD command to enter a folder. Just type CD, followed by the folder name.

Top Articles
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated: 11/12/2023

Views: 5513

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.