- Rename-Item
- Syntax
- Description
- Examples
- Example 1: Rename a file
- Example 2: Rename and move an item
- Example 3: Rename a registry key
- Example 4: Rename multiple files
- Parameters
- Inputs
- Outputs
- Notes
- Use PowerShell to Rename Files in Bulk
- Как переименовать файл или папку в PowerShell
- Пример переименования нескольких файлов
- Ошибка «Rename-Item: Access to the path ‘…’ is denied».
- auberginehill / Rename-Files.ps1
- This comment has been minimized.
- auberginehill commented Feb 23, 2017 •
- This comment has been minimized.
- jonathan987 commented Sep 6, 2017 •
- This comment has been minimized.
- csharpforevermore commented Feb 27, 2020
Rename-Item
Renames an item in a PowerShell provider namespace.
Syntax
Description
The Rename-Item cmdlet changes the name of a specified item. This cmdlet does not affect the content of the item being renamed.
You can’t 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.
Examples
Example 1: Rename a file
This command renames the file daily_file.txt to monday_file.txt .
Example 2: Rename and move an item
You can’t use Rename-Item to both rename and move an item. Specifically, you can’t supply a path for the value of the NewName parameter, unless the path is identical to the path specified in the Path parameter. Otherwise, only a new name is permitted.
This example attempts to rename the project.txt file in the current directory to old-project.txt in the D:\Archive directory. The result is the error shown in the output.
Example 3: Rename a registry key
This example renames a registry key from Advertising to Marketing. When the command is complete, the key is renamed, but the registry entries in the key are unchanged.
Example 4: Rename multiple files
This example renames all the *.txt files in the current directory to *.log .
The Get-ChildItem cmdlet gets all the files in the current folder that have a .txt file extension then pipes them to Rename-Item . The value of NewName is a script block that runs before the value is submitted to the NewName parameter.
In the script block, the $_ automatic variable represents each file object as it comes to the command through the pipeline. The script block uses the -replace operator to replace the file extension of each file with .log . Notice that matching using the -replace operator is not case sensitive.
Parameters
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
This parameter is not supported by any providers installed with PowerShell. To impersonate another user, or elevate your credentials when running this cmdlet, use Invoke-Command.
Type: | PSCredential |
Position: | Named |
Default value: | Current user |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Forces the cmdlet to rename items that can’t otherwise be changed, such as hidden or read-only files or read-only aliases or variables. The cmdlet can’t change constant aliases or variables. Implementation varies from provider to provider. For more information, see about_Providers.
Even using the Force parameter, the cmdlet can’t override security restrictions.
Type: | SwitchParameter |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a path to one or more locations. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences.
Type: | String |
Aliases: | PSPath, LP |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the new name of the item. Enter only a name, not a path and name. If you enter a path that differs from the path that is specified in the Path parameter, Rename-Item generates an error. 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.
Type: | String |
Position: | 1 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Returns an object that represents the item to the pipeline. By default, this cmdlet does not generate any output.
Type: | SwitchParameter |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the path of the item to rename.
Type: | String |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
You can pipe a string that contains a path to this cmdlet.
Outputs
None or an object that represents the renamed item.
This cmdlet generates an object that represents the renamed item, if you specify the PassThru parameter. Otherwise, this cmdlet does not generate any output.
Notes
Rename-Item is designed to work with the data exposed by any provider. To list the providers available in your session, type Get-PsProvider . For more information, see about_Providers.
Use PowerShell to Rename Files in Bulk
November 22nd, 2013
Summary: Learn how to use Windows PowerShell to rename files in bulk. Microsoft Scripting Guy, Ed Wilson, is here. Matt Tisdale is back today with another solution to a situation at work… I received a call from a gentleman named Cristofer this afternoon. He had a business need and he heard from someone that Windows PowerShell could help. I told him that I am sure Windows PowerShell can help—and that was before I even heard the question. His immediate need was to rename almost 250 files that are located in various folders on the file system. He needed to find all files with a specific character string in the name and replace this character string with a new character string. For example purposes, let’s say he needed to find all files with “current” in the name and replace “current” with “old”. I have never attempted this specific task, but by using Get-Command and Get-Help, we were able to find exactly how to do this in a couple of minutes. Assuming we need to find all files located under C:temp (including all subfolders) with “current” in the name and rename them using “old” in place of “current”, here are the steps.
- Open Windows PowerShell.
- Navigate to C:temp.
- Run the following Windows PowerShell command:
Get-ChildItem -Filter “*current*” -Recurse | Rename-Item -NewName <$_.name -replace ‘current’,’old’ >4. Sit back and let Windows PowerShell do all of the work for you. Anyone who has access to modify the files and is running Windows 7 can follow these steps. No special tools or elevated rights are required. Let’s pick the command apart and explain each piece.
- Get-ChildItem -Filter “*current*”
Finds all files with the string “current” anywhere in the name.
Instructs Get-ChildItem to search recursively through all subfolders under the start point (the current directory where the command is run from).
- | (the pipe character)
Instructs Windows PowerShell to take each item (object) found with the first command (Get-ChildItem) and pass it to the second command (Rename-Item)
Renames files and other objects
Tells Rename-Item to find the string “current” in the file name and replace it with “old”. For an added bonus, I also recommended that Cristofer use the –WhatIf parameter with this command on his first run to get an output that shows what the command will do before he actually pulls the trigger. Using -WhatIf will tell Windows PowerShell to run the Rename-Item portion of this command in Report Only mode. It will not actually rename anything—it will simply show what files were found that match the filter criteria and what each new name would be. Here is the command with the -WhatIf parameter added.
Get-ChildItem -Filter “*current*” -Recurse | Rename-Item -NewName <$_.name -replace ‘current’,’old’ >-whatif Unfortunately, when we use –WhatIf, we cannot send our output to a text log file. If you need a log file that shows the results of using -WhatIf, you can follow these steps:
- Open Windows PowerShell.
- Run Start-Transcript.
- Run your command (including the -WhatIf parameter).
- After the command completes, run Stop-Transcript.
- Note the location and file name of the transcript file, and open this file to see the results.
It is always fun to solve business challenges with Windows PowerShell commands. Cristofer said he will probably need to use these commands for renaming 1000+ files in the near future, and he will share this process with other members of his team. Imagine how much “fun” it would be to rename all of these files manually or with some clunky old batch file. No thank you. I will stick with Windows PowerShell. Keep the requests coming in. I always enjoy helping fellow employees find ways to be more efficient and save time and money.
Matt Thanks again, Matt, for sharing your time and knowledge. This is awesome. I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Как переименовать файл или папку в PowerShell
Командлет «Rename-Item» изменяет имя указанного элемента. Этот командлет не влияет на содержимое переименованного элемента.
Вы не можете использовать Rename-Item для перемещения элемента, например, указав путь вместе с новым именем. Чтобы переместить и переименовать элемент, используйте командлет «Move-Item».
Общий вид команды переименования файла:
Пример изменения имени файла в PowerShell:
Ещё один пример использования Rename-Item (обратите внимание, что с опцией -NewName указан не полный путь до файла, а только его имя):
Попытка переименовать и переместить файл:
Эта попытка завершиться ошибкой, поскольку командлет Rename-Item может только переименовывать файлы, но не перемещать их:
Командлет Rename-Item используется также и для переименования ключей регистра:
Пример переименования нескольких файлов
Смотрим содержимое папки:
Выполняем переименование, обратите внимание, что имена файлов передаются по трубе (конвейеру):
Смотрим содержимое папки после переименования файлов:
В последнем примере командлет «Get-ChildItem» получает все файлы в текущей папке с расширением «.txt», а затем передаёт их в «Rename-Item». Значением NewName становится результат выполнения блока скрипта, который выполняется до того, как значение будет передано в параметр NewName.
В блоке скрипта автоматическая переменная «$ _» представляет каждый файловый объект, когда он поступает в команду через конвейер. Блок скрипта использует оператор «-replace» для замены расширения каждого файла на «.log». Обратите внимание, что при сопоставлении с использованием оператора «-replace» регистр не учитывается.
Ошибка «Rename-Item: Access to the path ‘…’ is denied».
При попытке переименовать системные папки и файлы может возникнуть ошибка, что доступ отклонён. Пример команды:
Дело в UAC, которая не позволяет обычным пользователям без прав администратора изменять системные файлы и папки. Необходимо открыть PowerShell с правами администратора. Для этого нажмите Win+x и выберите «Windows PowerShell (администратор)»:
auberginehill / Rename-Files.ps1
Rename-Files.ps1 |
#> |
# Find all wmv-files with a string «oldstring» and replace «oldstring» with «newstring» in the filename |
Get-ChildItem * .wmv — Filter » *oldstring* » | ForEach |
# Change the file extension of all .jpeg files to .jpg |
# Credit: Ohad Schneider: «How can I bulk rename files in PowerShell?» |
Get-ChildItem * .jpeg | Rename-Item — NewName |
# Rename all PDF-files in a folder to lowercase |
Get-ChildItem * .pdf | Rename-Item — NewName |
# Replace the space character(s) with an underscore in all the filenames found in the current folder and the successive subfolders |
Get-ChildItem — Recurse — Force — Filter » * * » | Rename-Item — NewName |
# Rename files with an increasing number |
Get-ChildItem * .jpg | ForEach-Object — Begin < $count = 1 >— Process |
# Rename files with an increasing number |
Get-ChildItem * .jpg | ForEach-Object — Begin < $count = 1 >— Process |
# Inserting a prefix into filenames |
$source_path = » C:\Temp « |
$filter = » *.pdf « |
$new_prefix = » ACertainNewPrefix « |
# Retrieve files with the $source_path and $filter parameters, for example all PDF-files from C:\Temp |
# $filter = «» parameter value would retrieve all available instances, i.e. no filtering |
$files = Get-ChildItem — Path $source_path — Filter $filter |
# Process each file and add the $new_prefix to the filenames |
ForEach ( $file in $files ) < |
$old_file_name = $file .Name |
$new_full_name = » $ ( $file .DirectoryName ) » + » \ » + » $ ( $new_prefix ) » + » $ ( $old_file_name ) « |
# Rename the file (perhaps first with the -WhatIf parameter?) |
# Rename-Item $file.FullName -NewName $new_full_name -WhatIf |
Rename-Item $file .FullName — NewName $new_full_name |
> # ForEach $file |
# Source: Don Jones: «Appending text to the beginning of a variable file name» https://powershell.org/forums/topic/appending-text-to-the-beginning-of-a-variable-file-name/ |
Renaming Multiple Files in Windows Explorer (known as File Explorer in Windows 10) |
(1) Start by selecting a bunch of files: one can hold down for example. |
(a) the Ctrl key to select multiple files with multiple clicks or |
(b) the Shift key to select a range of files. |
(2) After the files are selected, use a rename command: |
(a) the button on the Home menu, |
(b) the command on the context menu or |
(c) the F2 key |
Result: All the files remain selected, but the first one in the group gets its name highlighted. |
(3) Type a new name for the (highlighted) file. |
(4) Hit Enter or click somewhere else in the window. |
Result: All the selected files are renamed using the name that was just typed in |
and are appended with a number in parentheses to differentiate them. |
# Source: http://www.howtogeek.com/111859/how-to-batch-rename-files-in-windows-4-ways-to-rename-multiple-files/ |
#> |
# Source: help Rename-Item -Full |
# Source: Jeffrey Snover: «Renaming Files»: https://blogs.msdn.microsoft.com/powershell/2007/03/06/renaming-files/ |
# Source: John Savill: «Use Windows PowerShell to Rename Files»: http://windowsitpro.com/powershell/use-windows-powershell-rename-files |
# Source: Ed Wilson: «Use PowerShell to Rename Files in Bulk»: https://blogs.technet.microsoft.com/heyscriptingguy/2013/11/22/use-powershell-to-rename-files-in-bulk/ |
# Source: Ohad Schneider: «How can I bulk rename files in PowerShell?»: http://stackoverflow.com/questions/13382638/how-can-i-bulk-rename-files-in-powershell/36241702#36241702 |
# Source: http://tweaks.com/windows/49459/batch-file-rename-with-windows-powershell/ |
# Source: http://www.howtogeek.com/111859/how-to-batch-rename-files-in-windows-4-ways-to-rename-multiple-files/ |
This comment has been minimized.
Copy link Quote reply
auberginehill commented Feb 23, 2017 •
Changelog
- 20180716: typo
- 20190124: added a «Inserting a prefix into filenames» -section
This comment has been minimized.
Copy link Quote reply
jonathan987 commented Sep 6, 2017 •
Very useful code but I use Batch Rename Files Tool because is easier to used. You can found hier BatchRenameFiles.org that allows you to quickly rename all the files in a specified directory.
This comment has been minimized.
Copy link Quote reply
csharpforevermore commented Feb 27, 2020
Nice example code. I prefer this script rather than being constrained with some BatchRenameFiles tool. Funny when I see someone trying to market their own terrible products by spamming boards like this.
Nice work with the script. Thank you for providing it!
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.