PowerShell - Loop through files and rename












2















newbie here. I am trying to write a PowerShell script to:




  1. loop through all files in directory

  2. List item


  3. Get all .pdf files ONLY



    Rename them-the file names are long - over 30 chars
    -They contain 2 numbers which I need to extract
    -Example:



    Cumulative Update 11 for Microsoft Dynamics NAV 2018 (Build 25480).pdf ->
    RESULT : = 18CU11.pdf




I tried examples from bunch of sites and I can't seem to even loop successfully.
Either get an error - that path doesn't exist or that can't rename files as somehow loop gets a filepath and that I can't rename



Get-ChildItem "C:Users******DesktopPowerShell Practice" -Filter *.pdf |  #create list of files

ForEach-Object{
$oldname = $_.FullName;
$newname = $_.FullName.Remove(0,17);
#$newname = $_.FullName.Insert(0,"CU")

Rename-Item $oldname $newname;

$oldname;
$newname; #for testing
}


That's just latest attempt, but any other ways of doing it will be fine - as long as it does the job.










share|improve this question




















  • 2





    How do your original filenames look exactly?

    – TobyU
    Nov 13 '18 at 8:39






  • 4





    If it says the path doesn't exist, then probably .. the path doesn't exist? You should include the actual output from your attempts!

    – marsze
    Nov 13 '18 at 8:53


















2















newbie here. I am trying to write a PowerShell script to:




  1. loop through all files in directory

  2. List item


  3. Get all .pdf files ONLY



    Rename them-the file names are long - over 30 chars
    -They contain 2 numbers which I need to extract
    -Example:



    Cumulative Update 11 for Microsoft Dynamics NAV 2018 (Build 25480).pdf ->
    RESULT : = 18CU11.pdf




I tried examples from bunch of sites and I can't seem to even loop successfully.
Either get an error - that path doesn't exist or that can't rename files as somehow loop gets a filepath and that I can't rename



Get-ChildItem "C:Users******DesktopPowerShell Practice" -Filter *.pdf |  #create list of files

ForEach-Object{
$oldname = $_.FullName;
$newname = $_.FullName.Remove(0,17);
#$newname = $_.FullName.Insert(0,"CU")

Rename-Item $oldname $newname;

$oldname;
$newname; #for testing
}


That's just latest attempt, but any other ways of doing it will be fine - as long as it does the job.










share|improve this question




















  • 2





    How do your original filenames look exactly?

    – TobyU
    Nov 13 '18 at 8:39






  • 4





    If it says the path doesn't exist, then probably .. the path doesn't exist? You should include the actual output from your attempts!

    – marsze
    Nov 13 '18 at 8:53
















2












2








2








newbie here. I am trying to write a PowerShell script to:




  1. loop through all files in directory

  2. List item


  3. Get all .pdf files ONLY



    Rename them-the file names are long - over 30 chars
    -They contain 2 numbers which I need to extract
    -Example:



    Cumulative Update 11 for Microsoft Dynamics NAV 2018 (Build 25480).pdf ->
    RESULT : = 18CU11.pdf




I tried examples from bunch of sites and I can't seem to even loop successfully.
Either get an error - that path doesn't exist or that can't rename files as somehow loop gets a filepath and that I can't rename



Get-ChildItem "C:Users******DesktopPowerShell Practice" -Filter *.pdf |  #create list of files

ForEach-Object{
$oldname = $_.FullName;
$newname = $_.FullName.Remove(0,17);
#$newname = $_.FullName.Insert(0,"CU")

Rename-Item $oldname $newname;

$oldname;
$newname; #for testing
}


That's just latest attempt, but any other ways of doing it will be fine - as long as it does the job.










share|improve this question
















newbie here. I am trying to write a PowerShell script to:




  1. loop through all files in directory

  2. List item


  3. Get all .pdf files ONLY



    Rename them-the file names are long - over 30 chars
    -They contain 2 numbers which I need to extract
    -Example:



    Cumulative Update 11 for Microsoft Dynamics NAV 2018 (Build 25480).pdf ->
    RESULT : = 18CU11.pdf




I tried examples from bunch of sites and I can't seem to even loop successfully.
Either get an error - that path doesn't exist or that can't rename files as somehow loop gets a filepath and that I can't rename



Get-ChildItem "C:Users******DesktopPowerShell Practice" -Filter *.pdf |  #create list of files

ForEach-Object{
$oldname = $_.FullName;
$newname = $_.FullName.Remove(0,17);
#$newname = $_.FullName.Insert(0,"CU")

Rename-Item $oldname $newname;

$oldname;
$newname; #for testing
}


That's just latest attempt, but any other ways of doing it will be fine - as long as it does the job.







powershell scripting






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 12:44







Arthur

















asked Nov 13 '18 at 8:34









ArthurArthur

185




185








  • 2





    How do your original filenames look exactly?

    – TobyU
    Nov 13 '18 at 8:39






  • 4





    If it says the path doesn't exist, then probably .. the path doesn't exist? You should include the actual output from your attempts!

    – marsze
    Nov 13 '18 at 8:53
















  • 2





    How do your original filenames look exactly?

    – TobyU
    Nov 13 '18 at 8:39






  • 4





    If it says the path doesn't exist, then probably .. the path doesn't exist? You should include the actual output from your attempts!

    – marsze
    Nov 13 '18 at 8:53










2




2





How do your original filenames look exactly?

– TobyU
Nov 13 '18 at 8:39





How do your original filenames look exactly?

– TobyU
Nov 13 '18 at 8:39




4




4





If it says the path doesn't exist, then probably .. the path doesn't exist? You should include the actual output from your attempts!

– marsze
Nov 13 '18 at 8:53







If it says the path doesn't exist, then probably .. the path doesn't exist? You should include the actual output from your attempts!

– marsze
Nov 13 '18 at 8:53














3 Answers
3






active

oldest

votes


















0














Try this logic:



[string]$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'DesktopPowerShell Practice'
[string]$listOfFilesToRename = Get-ChildItem -Path $rootPathForFiles -Filter '*.PDF' | Select-Object -ExpandProperty FullName
$listOfFilesToRename | ForEach-Object {
#get the filename wihtout the directory
[string]$newName = Split-Path -Path $_ -Leaf
#use regex replace to apply the new format
$newName = $newName -replace '^Cumulative Update (d+) .*NAV 20(d+).*$', '$2CU$1.pdf' # Assumes a certain format; if the update doesn't match this expectation the original filename is maintained
#Perform the rename
Write-Verbose "Renaming '$_' to '$newName'" -Verbose #added the verbose switch here so you'll see the output without worrying about the verbose preference
Rename-Item -Path $_ -NewName $newName
}





share|improve this answer



















  • 1





    Thank you very much that works perfectly.

    – Arthur
    Nov 16 '18 at 13:53



















3














Check the Help for Rename-Item. The Parameter -NewName requires the name of the file only, not the full path.



Try out this:



Get-ChildItem "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf |  #create list of files

ForEach-Object{
$oldname = $_.FullName
$newname = $_.Name.Remove(0,17)

Rename-Item -Path $oldname -NewName $newname

$oldname
$newname #for testing
}





share|improve this answer
























  • Still throws an error - Rename-Item Cannot rename the specified target, because it represents a path or device name.

    – Arthur
    Nov 16 '18 at 9:53



















0














Please try this



Get-ChildItem -Path "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf | Rename-Item -NewName $newname





share|improve this answer





















  • 2





    and $newname would be the same for all files?

    – derloopkat
    Nov 13 '18 at 9:18











  • No, but the logic to renaming would be the same for all files.

    – Arthur
    Nov 13 '18 at 17:10











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53276843%2fpowershell-loop-through-files-and-rename%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Try this logic:



[string]$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'DesktopPowerShell Practice'
[string]$listOfFilesToRename = Get-ChildItem -Path $rootPathForFiles -Filter '*.PDF' | Select-Object -ExpandProperty FullName
$listOfFilesToRename | ForEach-Object {
#get the filename wihtout the directory
[string]$newName = Split-Path -Path $_ -Leaf
#use regex replace to apply the new format
$newName = $newName -replace '^Cumulative Update (d+) .*NAV 20(d+).*$', '$2CU$1.pdf' # Assumes a certain format; if the update doesn't match this expectation the original filename is maintained
#Perform the rename
Write-Verbose "Renaming '$_' to '$newName'" -Verbose #added the verbose switch here so you'll see the output without worrying about the verbose preference
Rename-Item -Path $_ -NewName $newName
}





share|improve this answer



















  • 1





    Thank you very much that works perfectly.

    – Arthur
    Nov 16 '18 at 13:53
















0














Try this logic:



[string]$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'DesktopPowerShell Practice'
[string]$listOfFilesToRename = Get-ChildItem -Path $rootPathForFiles -Filter '*.PDF' | Select-Object -ExpandProperty FullName
$listOfFilesToRename | ForEach-Object {
#get the filename wihtout the directory
[string]$newName = Split-Path -Path $_ -Leaf
#use regex replace to apply the new format
$newName = $newName -replace '^Cumulative Update (d+) .*NAV 20(d+).*$', '$2CU$1.pdf' # Assumes a certain format; if the update doesn't match this expectation the original filename is maintained
#Perform the rename
Write-Verbose "Renaming '$_' to '$newName'" -Verbose #added the verbose switch here so you'll see the output without worrying about the verbose preference
Rename-Item -Path $_ -NewName $newName
}





share|improve this answer



















  • 1





    Thank you very much that works perfectly.

    – Arthur
    Nov 16 '18 at 13:53














0












0








0







Try this logic:



[string]$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'DesktopPowerShell Practice'
[string]$listOfFilesToRename = Get-ChildItem -Path $rootPathForFiles -Filter '*.PDF' | Select-Object -ExpandProperty FullName
$listOfFilesToRename | ForEach-Object {
#get the filename wihtout the directory
[string]$newName = Split-Path -Path $_ -Leaf
#use regex replace to apply the new format
$newName = $newName -replace '^Cumulative Update (d+) .*NAV 20(d+).*$', '$2CU$1.pdf' # Assumes a certain format; if the update doesn't match this expectation the original filename is maintained
#Perform the rename
Write-Verbose "Renaming '$_' to '$newName'" -Verbose #added the verbose switch here so you'll see the output without worrying about the verbose preference
Rename-Item -Path $_ -NewName $newName
}





share|improve this answer













Try this logic:



[string]$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'DesktopPowerShell Practice'
[string]$listOfFilesToRename = Get-ChildItem -Path $rootPathForFiles -Filter '*.PDF' | Select-Object -ExpandProperty FullName
$listOfFilesToRename | ForEach-Object {
#get the filename wihtout the directory
[string]$newName = Split-Path -Path $_ -Leaf
#use regex replace to apply the new format
$newName = $newName -replace '^Cumulative Update (d+) .*NAV 20(d+).*$', '$2CU$1.pdf' # Assumes a certain format; if the update doesn't match this expectation the original filename is maintained
#Perform the rename
Write-Verbose "Renaming '$_' to '$newName'" -Verbose #added the verbose switch here so you'll see the output without worrying about the verbose preference
Rename-Item -Path $_ -NewName $newName
}






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 16 '18 at 12:57









JohnLBevanJohnLBevan

14.3k145105




14.3k145105








  • 1





    Thank you very much that works perfectly.

    – Arthur
    Nov 16 '18 at 13:53














  • 1





    Thank you very much that works perfectly.

    – Arthur
    Nov 16 '18 at 13:53








1




1





Thank you very much that works perfectly.

– Arthur
Nov 16 '18 at 13:53





Thank you very much that works perfectly.

– Arthur
Nov 16 '18 at 13:53













3














Check the Help for Rename-Item. The Parameter -NewName requires the name of the file only, not the full path.



Try out this:



Get-ChildItem "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf |  #create list of files

ForEach-Object{
$oldname = $_.FullName
$newname = $_.Name.Remove(0,17)

Rename-Item -Path $oldname -NewName $newname

$oldname
$newname #for testing
}





share|improve this answer
























  • Still throws an error - Rename-Item Cannot rename the specified target, because it represents a path or device name.

    – Arthur
    Nov 16 '18 at 9:53
















3














Check the Help for Rename-Item. The Parameter -NewName requires the name of the file only, not the full path.



Try out this:



Get-ChildItem "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf |  #create list of files

ForEach-Object{
$oldname = $_.FullName
$newname = $_.Name.Remove(0,17)

Rename-Item -Path $oldname -NewName $newname

$oldname
$newname #for testing
}





share|improve this answer
























  • Still throws an error - Rename-Item Cannot rename the specified target, because it represents a path or device name.

    – Arthur
    Nov 16 '18 at 9:53














3












3








3







Check the Help for Rename-Item. The Parameter -NewName requires the name of the file only, not the full path.



Try out this:



Get-ChildItem "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf |  #create list of files

ForEach-Object{
$oldname = $_.FullName
$newname = $_.Name.Remove(0,17)

Rename-Item -Path $oldname -NewName $newname

$oldname
$newname #for testing
}





share|improve this answer













Check the Help for Rename-Item. The Parameter -NewName requires the name of the file only, not the full path.



Try out this:



Get-ChildItem "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf |  #create list of files

ForEach-Object{
$oldname = $_.FullName
$newname = $_.Name.Remove(0,17)

Rename-Item -Path $oldname -NewName $newname

$oldname
$newname #for testing
}






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 13 '18 at 11:18









BuxmaniakBuxmaniak

1644




1644













  • Still throws an error - Rename-Item Cannot rename the specified target, because it represents a path or device name.

    – Arthur
    Nov 16 '18 at 9:53



















  • Still throws an error - Rename-Item Cannot rename the specified target, because it represents a path or device name.

    – Arthur
    Nov 16 '18 at 9:53

















Still throws an error - Rename-Item Cannot rename the specified target, because it represents a path or device name.

– Arthur
Nov 16 '18 at 9:53





Still throws an error - Rename-Item Cannot rename the specified target, because it represents a path or device name.

– Arthur
Nov 16 '18 at 9:53











0














Please try this



Get-ChildItem -Path "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf | Rename-Item -NewName $newname





share|improve this answer





















  • 2





    and $newname would be the same for all files?

    – derloopkat
    Nov 13 '18 at 9:18











  • No, but the logic to renaming would be the same for all files.

    – Arthur
    Nov 13 '18 at 17:10
















0














Please try this



Get-ChildItem -Path "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf | Rename-Item -NewName $newname





share|improve this answer





















  • 2





    and $newname would be the same for all files?

    – derloopkat
    Nov 13 '18 at 9:18











  • No, but the logic to renaming would be the same for all files.

    – Arthur
    Nov 13 '18 at 17:10














0












0








0







Please try this



Get-ChildItem -Path "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf | Rename-Item -NewName $newname





share|improve this answer















Please try this



Get-ChildItem -Path "C:Users******DesktopPowerShell Practice-Filter" -Filter *.pdf | Rename-Item -NewName $newname






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 13 '18 at 9:20









Mehmet Seckin

2,0392034




2,0392034










answered Nov 13 '18 at 9:13









thiyagu selvarajthiyagu selvaraj

413




413








  • 2





    and $newname would be the same for all files?

    – derloopkat
    Nov 13 '18 at 9:18











  • No, but the logic to renaming would be the same for all files.

    – Arthur
    Nov 13 '18 at 17:10














  • 2





    and $newname would be the same for all files?

    – derloopkat
    Nov 13 '18 at 9:18











  • No, but the logic to renaming would be the same for all files.

    – Arthur
    Nov 13 '18 at 17:10








2




2





and $newname would be the same for all files?

– derloopkat
Nov 13 '18 at 9:18





and $newname would be the same for all files?

– derloopkat
Nov 13 '18 at 9:18













No, but the logic to renaming would be the same for all files.

– Arthur
Nov 13 '18 at 17:10





No, but the logic to renaming would be the same for all files.

– Arthur
Nov 13 '18 at 17:10


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53276843%2fpowershell-loop-through-files-and-rename%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()