{"id":12396,"date":"2022-09-30T16:03:51","date_gmt":"2022-09-30T10:33:51","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/"},"modified":"2022-09-30T16:03:51","modified_gmt":"2022-09-30T10:33:51","slug":"solved-script-for-renaming-files-in-a-specific-way","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/","title":{"rendered":"[Solved] Script for renaming files in a specific way"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-58137307\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"58137307\" data-parentid=\"58130410\" data-score=\"3\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>As commented, it would be a lot simpler if you put the old and new ID values in a CSV file like this:<\/p>\n<pre><code>\"OldID\",\"NewID\"\n\"12345\",\"98765\"\n\"23456\",\"87654\"\n\"34567\",\"76543\"\n<\/code><\/pre>\n<p>Then, something like below should work:<\/p>\n<pre><code># read this CSV to get an array of PSObjects\n$ids = Import-CSV -Path 'D:\\ReplaceId.csv'\n\n# build a lookup table from the $ids variable\n$hash = @{}\n$ids | ForEach-Object { $hash[$_.OldID] = $_.NewID }\n\n# next, get a list of all files that have names starting with any \n# of the 5 digits from column 'OldID' and loop through\nGet-ChildItem -Path 'THE PATH TO YOUR DIRECTORY' -Filter '*.pdf' -File | \n    Where-Object { $hash.Keys -contains $_.Name.Substring(0,5) } | \n    ForEach-Object {\n        # get the value for the new ID from the lookup hashtable\n        # and combine it with the remainder of the filename\n        $newName=\"{0}{1}\" -f $hash[$($_.Name.Substring(0,5))], $_.Name.Substring(5)\n        $_ | Rename-Item -NewName $newName -WhatIf\n    }\n<\/code><\/pre>\n<p>If the console info shows the correct replacement names, remove the <code>-WhatIf<\/code> switch to actually start renaming the files<\/p>\n<p>If you add the <code>-Recurse<\/code> switch to the <code>Get-ChildItem<\/code> cmdlet, the code will also rename files inside any subfolder.<\/p>\n<\/p>\n<hr>\n<p><strong>Update<\/strong><\/p>\n<hr>\n<p>Of course, the above assumes there is <strong>no mix<\/strong> of Old and New Id numbers in the folder. Since you commented that this is the case you will get <em>file already exists<\/em> errors.<br \/>\nTo overcome that, you need to make sure the new filenames are unique inside the folder. You can do that for instance like this.<\/p>\n<p>It appends an index number between brackets to the name if a file with that name already exists.<\/p>\n<pre><code>Get-ChildItem -Path 'D:\\Test' -Filter '*.pdf' -File | \n    Where-Object { $hash.Keys -contains $_.Name.Substring(0,5) } | \n    ForEach-Object {\n        # get the value for the new ID from the lookup hashtable\n        # and combine it with the remainder of the filename\n        $newId = $hash[$($_.Name.Substring(0,5))]\n        $newName=\"{0}{1}\" -f $newId, $_.Name.Substring(5)\n        # since a filename with the new ID may already exist, \n        # you need to create a unique filename by appending an indexnumber\n        $fullName = Join-Path -Path $_.DirectoryName -ChildPath $newName\n        $index = 1\n        while (Test-Path -Path $fullName -PathType Leaf) {\n            $newName=\"{0}{1}({2}){3}\" -f $newId, $_.BaseName.Substring(5), $index++, $_.Extension\n            $fullName = Join-Path -Path $_.DirectoryName -ChildPath $newName\n        }\n        $_ | Rename-Item -NewName $newName -WhatIf\n    }\n<\/code><\/pre>\n<p><strong>Before:<\/strong><\/p>\n<blockquote>\n<pre><code>D:\\TEST\n    12345_id_user.pdf\n    12345_id_user2.pdf\n    12345_id_user3.pdf\n    23456_id_user.pdf\n    34567_id_user.pdf\n    34567_id_user2.pdf\n    76543_id_user2.pdf\n    98765_id_user.pdf\n<\/code><\/pre>\n<\/blockquote>\n<p><strong>After:<\/strong><\/p>\n<blockquote>\n<pre><code>D:\\TEST\n    76543_id_user.pdf\n    76543_id_user2(1).pdf\n    76543_id_user2.pdf\n    87654_id_user.pdf\n    98765_id_user(1).pdf\n    98765_id_user.pdf\n    98765_id_user2.pdf\n    98765_id_user3.pdf\n<\/code><\/pre>\n<\/blockquote>\n<p><strong>Or<\/strong> if you want to increase the index number you already seem to apply, use this:<\/p>\n<pre><code>Get-ChildItem -Path 'D:\\Test' -Filter '*.pdf' -File | \n    Where-Object { $hash.Keys -contains $_.Name.Substring(0,5) } | \n    ForEach-Object {\n        # get the value for the new ID from the lookup hashtable\n        # and combine it with the remainder of the filename\n        $newId    = $hash[$($_.Name.Substring(0,5))]\n        $newName=\"{0}{1}\" -f $newId, $_.Name.Substring(5)\n        # since a filename with the new ID may already exist, \n        # you need to create a unique filename by incrementing the indexnumber\n\n        # get the basename of the new name without any index numbers at the end\n        $baseName  = [System.IO.Path]::GetFileNameWithoutExtension($newName) -replace '\\d+$'\n        $extension = $_.Extension\n        # get an array of all file and folder names of items with a similar name already present in the folder\n        $similar = @(Get-ChildItem $_.DirectoryName -Filter \"$baseName*$extension\" | Select-Object -ExpandProperty Name)\n        $index = 1\n        while ($similar -contains $newName) {\n            $newName=\"{0}{1}{2}\" -f $baseName, $index++, $extension\n        }\n\n        $_ | Rename-Item -NewName $newName -WhatIf\n    }\n<\/code><\/pre>\n<p><strong>Before:<\/strong><\/p>\n<blockquote>\n<pre><code>D:\\TEST\n    12345_id_user.pdf\n    12345_id_user2.pdf\n    12345_id_user3.pdf\n    23456_id_user.pdf\n    34567_id_user.pdf\n    34567_id_user2.pdf\n    76543_id_user2.pdf\n    98765_id_user.pdf\n<\/code><\/pre>\n<\/blockquote>\n<p><strong>After:<\/strong><\/p>\n<blockquote>\n<pre><code>D:\\TEST\n    76543_id_user.pdf\n    76543_id_user1.pdf\n    76543_id_user2.pdf\n    87654_id_user.pdf\n    98765_id_user.pdf\n    98765_id_user1.pdf\n    98765_id_user2.pdf\n    98765_id_user3.pdf\n<\/code><\/pre>\n<\/blockquote><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">5<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Script for renaming files in a specific way <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] As commented, it would be a lot simpler if you put the old and new ID values in a CSV file like this: &#8220;OldID&#8221;,&#8221;NewID&#8221; &#8220;12345&#8221;,&#8221;98765&#8243; &#8220;23456&#8221;,&#8221;87654&#8243; &#8220;34567&#8221;,&#8221;76543&#8243; Then, something like below should work: # read this CSV to get an array of PSObjects $ids = Import-CSV -Path &#8216;D:\\ReplaceId.csv&#8217; # build a lookup table from &#8230; <a title=\"[Solved] Script for renaming files in a specific way\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/\" aria-label=\"More on [Solved] Script for renaming files in a specific way\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[1153,1212,1080],"class_list":["post-12396","post","type-post","status-publish","format-standard","hentry","category-solved","tag-powershell","tag-replace","tag-text"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Script for renaming files in a specific way - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Script for renaming files in a specific way - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] As commented, it would be a lot simpler if you put the old and new ID values in a CSV file like this: &quot;OldID&quot;,&quot;NewID&quot; &quot;12345&quot;,&quot;98765&quot; &quot;23456&quot;,&quot;87654&quot; &quot;34567&quot;,&quot;76543&quot; Then, something like below should work: # read this CSV to get an array of PSObjects $ids = Import-CSV -Path &#039;D:ReplaceId.csv&#039; # build a lookup table from ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-30T10:33:51+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Script for renaming files in a specific way\",\"datePublished\":\"2022-09-30T10:33:51+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/\"},\"wordCount\":180,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"powershell\",\"replace\",\"text\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/\",\"name\":\"[Solved] Script for renaming files in a specific way - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-09-30T10:33:51+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Script for renaming files in a specific way\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Script for renaming files in a specific way - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Script for renaming files in a specific way - JassWeb","og_description":"[ad_1] As commented, it would be a lot simpler if you put the old and new ID values in a CSV file like this: \"OldID\",\"NewID\" \"12345\",\"98765\" \"23456\",\"87654\" \"34567\",\"76543\" Then, something like below should work: # read this CSV to get an array of PSObjects $ids = Import-CSV -Path 'D:ReplaceId.csv' # build a lookup table from ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/","og_site_name":"JassWeb","article_published_time":"2022-09-30T10:33:51+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Script for renaming files in a specific way","datePublished":"2022-09-30T10:33:51+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/"},"wordCount":180,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["powershell","replace","text"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/","url":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/","name":"[Solved] Script for renaming files in a specific way - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-09-30T10:33:51+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-script-for-renaming-files-in-a-specific-way\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Script for renaming files in a specific way"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/12396","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=12396"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/12396\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=12396"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=12396"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=12396"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}