How to rename files in Powershell with three digits and odd numbers? - windows

Pretty novice to using powershell.
Trying to rename several .wav files that need to be in an odd sequential order.
I've found from another post from here how to rename multiple files in odd increments but can't figure out how to format them as "001_title.wav", 003_title.wav, 005_title.wav etc.
Stumped with trying to implement '{0:d3}'.
Should I be using that?
Any help would be appreciated!
Thanks.
$path = "\path\to\files"
$oddNumbersArray = 0..500 | % {$_ *2 +1}
$i = 0
Get-ChildItem $path -Filter *.wav | % {Rename-Item $_ -NewName ("$($oddNumbersArray[$i])_title.wav") '{0:d3}' -f $($oddNumbersArray[$i]) ;$i++}

Your -NewName expression should look like this:
... |Rename-Item -NewName { '{0:d3}_title.wav' -f $oddNumbersArray[$script:i++] }
The {} brackets ensure the pipeline binder re-calculates the value for each input item, and the script: scope modifier is required because we're writing to a variable in a parent scope.
FWIW you don't have to "pre-calculate" your odd numbers - you can increment your counter variable by 2 instead:
$path = "\path\to\files"
$oddCounter = 1
Get-ChildItem $path -Filter *.wav |Rename-Item -NewName { '{0:d3}_title.wav' -f $oddNumbersArray[($script:i += 2)] }

Related

How to recursively truncate filenames in powershell?

I need to truncate filenames to 35 characters (including extension) so I run this script and it worked for the directory it self (PowerShell, Windows 10).
Get-ChildItem *.pdf | rename-item -NewName {$_.name.substring(0,31) + $_.Extension}
Then I wanted to apply the same script including subdirectories:
Get-ChildItem -Recurse -Include *.pdf | Rename-Item -NewName {$_.Name.substring(0,31) + $_.Extension}
This script gave me an error like this for each file:
Rename-Item : Error in input to script block for parameter 'NewName'. Exception when calling "Substring" with the arguments "2": "The index and length must reference a location in the string. Parameter name: length"
On line: 1 Character: 62
+ ... *.pdf | Rename-Item -NewName {$_.Name.substring(0,31) + $_.Extension}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (C:\User\prsn..._file_name_long.pdf:PSObject) [Rename-Item], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentInvocationFailed,Microsoft.PowerShell.Commands.RenameItemCommand
I tried this one but it doesn't go on subdirectories:
Command to truncate all filenames at 255 characters
I found this one but it doesn't have an answer:
https://superuser.com/questions/1188711/how-to-recursively-truncate-filenames-and-directory-names-in-powershell
I don't think you can use $_ that way. I think you have to wrap it in a ForEach loop in order to get the references to work that way. Once that's done, you'll have to specify the path of the file you want to rename as well:
Something like:
Get-ChildItem -Recurse -Include *.pdf -File |
ForEach-Object{
Rename-Item -Path $_.FullName -NewName ( $_.BaseName.SubString(0, 31) + $_.Extension )
}
Notice I used parenthesis instead of curly braces. If you use a script block it may not evaluate. There are other ways to make it happen, but I think using parens is the most obvious.
Notice I used $_.BaseName instead of name. Base name doesn't include the extension. though I don't know how your sub-string works out I left it in for you decide.
You can combine this with #Mathias's answer or some modification of it. That might give you a better or more reliable way to derive the new file name. I haven't tested it, but it might look something like:
Get-ChildItem -Recurse -Include *.pdf -File |
ForEach-Object{
Rename-Item -Path $_.FullName -NewName ( ($_.Name -replace '(?<=^.{35}).*$') + $_.Extension )
}
Use the -replace regex operator to remove anything after the first 35 chars - it will simply ignore any string that doesn't have at least 35 characters and return it as-is:
$_.Name -replace '(?<=^.{35}).*$'
The correct error message is
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
The reason is that the second argument is greater than the length of the file name. e.g. "abc".Substring(0,4) throws.
Answer
$renameTarget = dir -File -Recurse *.pdf | ? { $_.Name.Length -gt 35 }
$renameTarget | Rename-Item -NewName {
$_.name.substring(0, 31) + ".pdf"
}
or
dir *.pdf -File -Recurse | Rename-Item -NewName {
$_.name.substring(0, [Math]::Min($_.BaseName.length, 31)) + ".pdf"
}

Recursively Rename Files In All Subfolders Sequentially

I have a series of folders and subfolders, structured in this way:
001/Fabric/Blue/ (.jpg files, sequentially named)
001/Fabric/Green/ (.jpg files, sequentially named)
002/Fabric/Blue/ (.jpg files, sequentially named)
002/Fabric/Green/ (.jpg files, sequentially named)
etc.
The file names have excess string characters that I would like to remove, and I would like to convert their file names into an easier sequential format (0.jpg, 1.jpg, etc.).
I tried working with a few different PowerShell examples to get this to work. I have the recursive searching functionality working, however I receive an error about an InvalidOperationException when trying to rename the files in the ForEach-Object loop. Additionally, I am afraid my sequential numbering is not being 'reset' for each of the folders where it renames files.
$i = 0
Get-ChildItem -Filter "*.jpg" -Recurse | ForEach-Object {
Rename-Item $_ -NewName ('$i.jpg' -f $i++)
}
So, two questions:
How can I fix the error with Rename-Item?
How can I ensure my variable is reset for each subfolder the script starts renaming files in?
If you take a two step approach, first getting all the folders containing jpg's and then iterating through this list, you have no problem beginning with 1. But I'd always use leading zeroes for such a renumbering.
$BaseFld = "Q:\Test\"
$Ext = "*.jpg"
$jpgFolders = gci $($BaseFld+$Ext) -Recurse |
Select -ExpandProperty Directory -Unique |
select -ExpandProperty Fullname | Sort
ForEach ($Folder in $jpgFolders) {
Set-location $Folder
$i = 1
Get-ChildItem $Ext | %{Ren $_ -NewName ('{0:D4}.jpg' -f $i++) -whatif}
}
If the ouptut suits you, remove the -whatif in the second last line
other method
$rootdir="C:\temp"
gci $rootdir -Recurse -Directory | %{$i=1; gci $_.FullName -Recurse -File -Filter "*.jpg" | %{Ren $_.FullName -NewName ('{0}.jpg' -f $i++)} }

Add special prefix to all files in directory

I have a directory with a certain number of mp3 files, that are sorted by name, for example:
Artist.mp3
Another artist.mp3
Bartist.mp3
Cool.mp3
Day.mp3
How can I add a unique continuous 3-digit prefix to each file, but in a random order, so that when sorting by name it would look something like this:
001 Cool.mp3
002 Artist.mp3
003 Day.mp3
...
Try this:
$files = Get-ChildItem -File
$global:i = 0; Get-Random $files -Count $files.Count |
Rename-Item -NewName {"{0:000} $($_.Name)" -f ++$global:i} -WhatIf
Or in the unlikely event the filename contains curly braces :-):
$files = Get-ChildItem -File
$global:i = 0; Get-Random $files -Count $files.Count |
Rename-Item -NewName {("{0:000} " -f ++$global:i) + $_.Name} -WhatIf
Or as #PetSerAl suggests, using [ref]$i as a good way to avoid global vs script scoping issues altogether:
$files = Get-ChildItem -File
$i = 0; Get-Random $files -Count $files.Count |
Rename-Item -NewName {"{0:000} {1}" -f ++([ref]$i).Value, $_.Name} -WhatIf
If the output looks good remove the -WhatIf and run this again to actually rename the files.

How can I bulk rename files in PowerShell?

I'm trying to do the following:
Rename-Item c:\misc\*.xml *.tmp
I basically want to change the extension on every files within a directory to .tmp instead of .xml. I can't seem to find a straight forward way to do this in PowerShell.
From example 4 in the help documentation of Rename-Item retrieved with the command:
get-help Rename-Item -examples
Example:
Get-ChildItem *.txt| Rename-Item -NewName { $_.Name -replace '\.txt','.log' }
Note the explanation in the help documentation for the escaping backslash in the replace command due to it using regular expressions to find the text to replace.
To ensure the regex -replace operator matches only an extension at the end of the string, include the regex end-of-string character $.
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '\.txt$','.log' }
This takes care of the case mentioned by #OhadSchneider in the comments, where we might have a file named lorem.txt.txt and we want to end up with lorem.txt.log rather than lorem.log.log.
Now that the regex is sufficiently tightly targeted, and inspired by #etoxin's answer, we could make the command more usable as follows:
Get-ChildItem | Rename-Item -NewName { $_.Name -replace '\.txt$','.log' }
That is, there is no need to filter before the pipe if our regex sufficiently filters after the pipe. And altering the command string (e.g. if you copy the above command and now want to use it to change the extension of '.xml' files) is no longer required in two places.
This works well too when you're in the desired directory.
Dir | Rename-Item –NewName { $_.name –replace "old","new" }
The existing answers suggest the -replace operator, but what if the file is called a.xml.xml? Both .xml substrings will be replaced and the end result would be a.tmp.tmp. Fortunately, there's a .NET method for this:
Dir *.xml | rename-item -newname { [io.path]::ChangeExtension($_.name, ".tmp") }
(Manish Kumar was close with GetFileNameWithoutExtension but this is more elegant and probably a bit more efficient, not that it overly matters in this case)
Here's another variant that will work.
dir *.xml | Rename-Item -NewName {$_.BaseName + ".tmp"}
$_.BaseName will do the "base" name without the (last) extension.
a shortened version using the alias would be:
ls *.xml | ren -new {$_.BaseName + ".tmp"}
dir -Recurse | where-object -FilterScript {$_.Extension -eq ".xml"} | Rename-Item -NewName {[System.IO.Path]::GetFileNameWithoutExtension($_.fullname) + ".tmp"}
use -WhatIf to evaluate the result first
Even easier - remember that the replace search string is a regular expression,
dir *.xml | rename-item -newname {$_.name -replace "xml$","tmp"}
The "$" represents end-of-string, so the characters "xml" must be the last three chars of the filename.
This seems to work and is a pythonic i.e simple is better than complex (https://www.python.org/dev/peps/pep-0020/) way of doing it (once you are in the directory):
$files = Get-ChildItem -file -Filter *.xml;
ForEach ($file in $files)
{
$n = $file.Basename
Copy-Item -Path $file -Destination "$n.tmp"
Remove-Item "$n.xml"
}

script to find given string and replace in all files in given directory

How to write script in powershell which finds given string in all files in given directory and changes it to given second one ?
thanks for any help,
bye
Maybe something like this
$files = Get-ChildItem "DirectoryContainingFiles"
foreach ($file in $files)
{
$content = Get-Content -path $file.fullname
$content | foreach {$_ -replace "toreplace", "replacewith"} |
Set-Content $file.fullname
}
If the string to replace spans multiple lines then using Get-Content isn't going to cut it unless you stitch together the output of Get-Content into a single string. It's easier to use [io.file]::ReadAllText() in this case e.g.:
Get-ChildItem | Where {!$_.PSIsContainer} |
Foreach { $txt = [IO.File]::ReadAllText($_.fullname);
$txt -replace $old,$new; $txt | Out-File $_}
Note with with $old, you may need to use a regex directive like '(?s)' at the beginning to indicate that . matches newline characters also.
I believe that you can get the list of all files in a directory (simple?). Now comes the replacement part. Here is how you can do it with power shell:
type somefile.txt | %{$_ -replace "string_to_be_replaces","new_strings"}
Modify it as per your need. You can also redirect the output to a new file the same way you do other redirection (using: >).
To get the list of files, use:
Get-ChildItem <DIR_PATH> -name

Resources