homepage
Open menu
Go one level top
  • Train and Certify
    Train and Certify

    Immediately apply the skills and techniques learned in SANS courses, ranges, and summits

    • Overview
    • Courses
      • Overview
      • Full Course List
      • By Focus Areas
        • Cloud Security
        • Cyber Defense
        • Cybersecurity and IT Essentials
        • DFIR
        • Industrial Control Systems
        • Offensive Operations
        • Management, Legal, and Audit
      • By Skill Levels
        • New to Cyber
        • Essentials
        • Advanced
        • Expert
      • Training Formats
        • OnDemand
        • In-Person
        • Live Online
      • Course Demos
    • Training Roadmaps
      • Skills Roadmap
      • Focus Area Job Roles
        • Cyber Defence Job Roles
        • Offensive Operations Job Roles
        • DFIR Job Roles
        • Cloud Job Roles
        • ICS Job Roles
        • Leadership Job Roles
      • NICE Framework
        • Security Provisionals
        • Operate and Maintain
        • Oversee and Govern
        • Protect and Defend
        • Analyze
        • Collect and Operate
        • Investigate
        • Industrial Control Systems
    • GIAC Certifications
    • Training Events & Summits
      • Events Overview
      • Event Locations
        • Asia
        • Australia & New Zealand
        • Latin America
        • Mainland Europe
        • Middle East & Africa
        • Scandinavia
        • United Kingdom & Ireland
        • United States & Canada
      • Summits
    • OnDemand
    • Get Started in Cyber
      • Overview
      • Degree and Certificate Programs
      • Scholarships
    • Cyber Ranges
  • Manage Your Team
    Manage Your Team

    Build a world-class cyber team with our workforce development programs

    • Overview
    • Why Work with SANS
    • Group Purchasing
    • Build Your Team
      • Team Development
      • Assessments
      • Private Training
      • Hire Cyber Professionals
      • By Industry
        • Health Care
        • Industrial Control Systems Security
        • Military
    • Leadership Training
  • Security Awareness
    Security Awareness

    Increase your staff’s cyber awareness, help them change their behaviors, and reduce your organizational risk

    • Overview
    • Products & Services
      • Security Awareness Training
        • EndUser Training
        • Phishing Platform
      • Specialized
        • Developer Training
        • ICS Engineer Training
        • NERC CIP Training
        • IT Administrator
      • Risk Assessments
        • Knowledge Assessment
        • Culture Assessment
        • Behavioral Risk Assessment
    • OUCH! Newsletter
    • Career Development
      • Overview
      • Training & Courses
      • Professional Credential
    • Blog
    • Partners
    • Reports & Case Studies
  • Resources
    Resources

    Enhance your skills with access to thousands of free resources, 150+ instructor-developed tools, and the latest cybersecurity news and analysis

    • Overview
    • Webcasts
    • Free Cybersecurity Events
      • Free Events Overview
      • Summits
      • Solutions Forums
      • Community Nights
    • Content
      • Newsletters
        • NewsBites
        • @RISK
        • OUCH! Newsletter
      • Blog
      • Podcasts
      • Summit Presentations
      • Posters & Cheat Sheets
    • Research
      • White Papers
      • Security Policies
    • Tools
    • Focus Areas
      • Cyber Defense
      • Cloud Security
      • Digital Forensics & Incident Response
      • Industrial Control Systems
      • Cyber Security Leadership
      • Offensive Operations
  • Get Involved
    Get Involved

    Help keep the cyber community one step ahead of threats. Join the SANS community or begin your journey of becoming a SANS Certified Instructor today.

    • Overview
    • Join the Community
    • Work Study
    • Teach for SANS
    • CISO Network
    • Partnerships
    • Sponsorship Opportunities
  • About
    About

    Learn more about how SANS empowers and educates current and future cybersecurity practitioners with knowledge and skills

    • SANS
      • Overview
      • Our Founder
      • Awards
    • Instructors
      • Our Instructors
      • Full Instructor List
    • Mission
      • Our Mission
      • Diversity
      • Scholarships
    • Contact
      • Contact Customer Service
      • Contact Sales
      • Press & Media Enquiries
    • Frequent Asked Questions
    • Customer Reviews
    • Press
    • Careers
  • Contact Sales
  • SANS Sites
    • GIAC Security Certifications
    • Internet Storm Center
    • SANS Technology Institute
    • Security Awareness Training
  • Search
  • Log In
  • Join
    • Account Dashboard
    • Log Out
  1. Home >
  2. Blog >
  3. Month of PowerShell - Renaming Groups of Files
370x370_Joshua-Wright.jpg
Joshua Wright

Month of PowerShell - Renaming Groups of Files

Have you ever had to rename hundreds of files ... manually? 😱 Let's look at how to automate a massive file-rename task using PowerShell.

July 29, 2022

#monthofpowershell

Using a loop to rename a group of files is one of the things that I'm often thankful for. Sure, if I have 20, 40, 100 files, I could rename them all manually, but that's some tedious work.

Fortunately, we have PowerShell.

~/Desktop/Images> Get-ChildItem | Select-Object -Property Name

Name
----
DSC_4745.jpg
DSC_4791.jpg
DSC_4830.jpg
DSC_4947.jpg
DSC_4973.jpg
DSC_5035.jpg
DSC_5043.jpg
DSC_5187.jpg
DSC_5217.jpg
DSC_5296.jpg
DSC_5312.jpg

I have 11 files here (I didn't count them; I used code.Count with the grouping operator). These images are from a photo shoot I did with my nephew for his senior photos, all cropped to be printed at 5x7 aspect ratio. Since I'm also printing a different set cropped for 8x10 aspect ratio, I want to make sure I keep the files sorted correctly. To help me remember which files are the different crop aspect ratios, I want to add Crop-5x7- to the beginning of each of these files.

At first, this seemed like a simple task:

~/Desktop/Images> Get-ChildItem | foreach { Rename-Item -Path $_.Name -NewName "Crop-5x7-$_.Name" }
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.
Rename-Item: Cannot rename the specified target, because it represents a path or device name.

Well, that's not right.

To troubleshoot, I did another loop, this time displaying the $_.Name property for each file with Write-Host:

~/Desktop/Images> Get-ChildItem | foreach { Write-Host "Crop-5x7-$_.Name" }
Crop-5x7-/Users/jwright/Desktop/Images/DSC_4745.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_4791.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_4830.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_4947.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_4973.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_5035.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_5043.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_5187.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_5217.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_5296.jpg.Name
Crop-5x7-/Users/jwright/Desktop/Images/DSC_5312.jpg.Name

Well, that's not what I wanted at all.

In the -NewName argument I specified "Crop-5x7-$.Name", thinking that PowerShell would expand the variable \(_.Name as part of the new string. However, PowerShell expanded \) first (which resolved to /Users/jwright/Desktop/Images/DSC_4745.jpg), then added the prefix Crop-5x7- and treated .Name as a suffix.

Subexpressions to the Rescue

What I want is for PowerShell to expand the $_.Name property first, then add the prefix Crop-5x7- to the beginning of the file name. To force PowerShell to expand the string in this manner, I need to use a subexpression.

In PowerShell, subexpressions are specified using a leading dollar sign, then parenthesis: $(). A subexpression tells PowerShell to execute this first and then treat the result like a variable:

~/Desktop/Images> Get-ChildItem | foreach { Write-Host "Crop-5x7-$($_.Name)" }
Crop-5x7-DSC_4745.jpg
Crop-5x7-DSC_4791.jpg
Crop-5x7-DSC_4830.jpg
Crop-5x7-DSC_4947.jpg
Crop-5x7-DSC_4973.jpg
Crop-5x7-DSC_5035.jpg
Crop-5x7-DSC_5043.jpg
Crop-5x7-DSC_5187.jpg
Crop-5x7-DSC_5217.jpg
Crop-5x7-DSC_5296.jpg
Crop-5x7-DSC_5312.jpg

Perfect! The subexpression is evaluated first, and then the result is incorporated as a string into the file name with the specified prefix. Incorporating that into the Rename-Item loop gives me this:

~/Desktop/Images> Get-ChildItem | foreach { Rename-Item -Path $_.Name -NewName "Crop-5x7-$($_.Name)" }
~/Desktop/Images> Get-ChildItem | Select-Object -Property Name

Name
----
Crop-5x7-DSC_4745.jpg
Crop-5x7-DSC_4791.jpg
Crop-5x7-DSC_4830.jpg
Crop-5x7-DSC_4947.jpg
Crop-5x7-DSC_4973.jpg
Crop-5x7-DSC_5035.jpg
Crop-5x7-DSC_5043.jpg
Crop-5x7-DSC_5187.jpg
Crop-5x7-DSC_5217.jpg
Crop-5x7-DSC_5296.jpg
Crop-5x7-DSC_5312.jpg

🙌

There and Back Again

After printing the images, I wanted to rename them back to the original DSC_NNNN.jpg file names again. I could have re-exported them from Lightroom, but I took the opportunity to experiment more with using PowerShell to rename groups of files.

Strings in PowerShell have a method called Replace(). We can look at the methods using an empty string and Get-Member:

~/Desktop/Images> '' | Get-Member -MemberType Method | Select-String 'Replace\('

string Replace(string oldValue, string newValue, bool ignoreCase, cultureinfo culture), string Replace(string oldValue, string
newValue, System.StringComparison comparisonType), string Replace(char oldChar, char newChar), string Replace(string oldValue, string
newValue)

Using Replace(), I can remove the Crop-5x7- part of the file names to rename back to the original names. First, let's test it out to make sure we get what we need:

~/Desktop/Images> Get-ChildItem | foreach { Write-Host "$_.Name.Replace('Crop-5x7-','')" }
/Users/jwright/Desktop/Images/Crop-5x7-DSC_4745.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_4791.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_4830.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_4947.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_4973.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_5035.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_5043.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_5187.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_5217.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_5296.jpg.Name.Replace('Crop-5x7-','')
/Users/jwright/Desktop/Images/Crop-5x7-DSC_5312.jpg.Name.Replace('Crop-5x7-','')

🤦‍♂️

We need to use the subexpression operator again here, to get PowerShell to evaluate the $_.Name.Replace() statement, returning the modified file name as a string:

~/Desktop/Images> Get-ChildItem | foreach { Write-Host "$($_.Name.Replace('Crop-5x7-',''))" }
DSC_4745.jpg
DSC_4791.jpg
DSC_4830.jpg
DSC_4947.jpg
DSC_4973.jpg
DSC_5035.jpg
DSC_5043.jpg
DSC_5187.jpg
DSC_5217.jpg
DSC_5296.jpg
DSC_5312.jpg

Perfect! By adding $( to the beginning of the file name, and a trailing ) to the end, we can apply the subexpression operator, producing the desired file name. Next, we can use Rename-Item in the foreach loop to rename the files:

~/Desktop/Images> Get-ChildItem | foreach { Rename-Item -Path $_.Name -NewName $($_.Name.Replace('Crop-5x7-',''))  }
~/Desktop/Images> Get-ChildItem | Select-Object -Property Name

Name
----
DSC_4745.jpg
DSC_4791.jpg
DSC_4830.jpg
DSC_4947.jpg
DSC_4973.jpg
DSC_5035.jpg
DSC_5043.jpg
DSC_5187.jpg
DSC_5217.jpg
DSC_5296.jpg
DSC_5312.jpg

Conclusion

In this article we looked at the practical skill of using PowerShell to rename a collection of files. First we looked at renaming several files to include a prefix string, and how we need to use the PowerShell subexpression operator $() to expand the desired properties when referencing the file names with Rename-Item. Next we looked at returning the files to their original names, using the subexpression operator again but also with the string method Replace() to strip the leading file name prefixes.

With PowerShell, and some understanding of how expressions are evaluated, it's not too difficult to automate the process of renaming files. Hopefully you'll remember this article and swoop in and help someone less fortunate, next time you see them manually renaming hundreds of files.

-Joshua Wright

Return to Getting Started With PowerShell


Joshua Wright is the author of SANS SEC504: Hacker Tools, Techniques, and Incident Handling, a faculty fellow for the SANS Institute, and a senior technical director at Counter Hack.

Share:
TwitterLinkedInFacebook
Copy url Url was copied to clipboard
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Recommended Training

  • SEC580: Metasploit for Enterprise Penetration Testing
  • SEC660: Advanced Penetration Testing, Exploit Writing, and Ethical Hacking
  • SEC505: Securing Windows and PowerShell Automation

Tags:
  • Cyber Defense
  • Cybersecurity and IT Essentials
  • Penetration Testing and Red Teaming

Related Content

Blog
CD_Blog_HowtoautomateinAzure_Part1_2.jpg
Cyber Defense, Cloud Security
October 11, 2022
How to Automate in Azure Using PowerShell - Part 1
In this post, we’ll cover how to automate the assessment and reporting of your cloud security configuration opportunities.
370x370_josh-johnson.jpg
Josh Johnson
read more
Blog
powershell_option_340x340.jpg
Cybersecurity and IT Essentials, Cyber Defense, Penetration Testing and Red Teaming
August 4, 2022
Month of PowerShell - Discoveries from the Month of PowerShell
A final wrap-up from the Month of PowerShell: discoveries, recommendations, complaints, and successes.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
Blog
powershell_option_340x340.jpg
Cybersecurity and IT Essentials, Cyber Defense, Penetration Testing and Red Teaming
July 31, 2022
Month of PowerShell - Keyboard Shortcuts Like a Boss
Let's look at several keyboard shortcuts to speed up your PowerShell sessions.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
  • Register to Learn
  • Courses
  • Certifications
  • Degree Programs
  • Cyber Ranges
  • Job Tools
  • Security Policy Project
  • Posters & Cheat Sheets
  • White Papers
  • Focus Areas
  • Cyber Defense
  • Cloud Security
  • Cybersecurity Leadership
  • Digital Forensics
  • Industrial Control Systems
  • Offensive Operations
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
  • © 2023 SANS™ Institute
  • Privacy Policy
  • Contact
  • Careers
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn