PowerShell - Why is this not renaming my files? - powershell

I have been looking around for a way to quickly and easily rename hundreds os files in one go.
something where I only have to change smalle parts for it to be reused somewhere else.
So i ended up starting to make this script. shown below...
the output should come out like this:
Show Title - SXX.EXXX - Episode title - [release year]
the raw files all looks like this:
XXX Episode title [release year]
It does not work right now. and i haven't been able to see why yet.
Whenever i run it, it does nothing. but i do not get any error message.
$ShowTitle = "My Title -"
$SeasonNumber = "02"
# Getting all child files (In ALL subfolders)
$files = Get-Childitem –Path Get-Location -Recurse |
Where-Object { $_.Name -match $_.Name } |
# Insert a ' - ' between the episode number and the episode text.
Rename-Item -NewName {$_.BaseName.insert(5,'-') + $_.Extension} |
# Append title and season number to the beginning of the file.
Rename-Item -NewName { $ShowTitle + "S" + $SeasonNumber + ".E" + $_.Name} |
# Makes a "-" between episode title and year of release.
Rename-Item -NewName { $_.Name -replace '\[', '- [' }
it worked on a smaller scale before. like this:
$files = Get-Childitem –Path "C:\Users\user\Videos\Series\show\Season x" -Recurse |
Where-Object { $_.Name -match 'show title' } |
Rename-Item -NewName { $_.Name -replace '\[', '- [' }
But i would like to do all the steps above in one go.
Can someone give me a hint so I can find the right answer to my little problem?
Thank you in advance.

You've got a lot of bugs here.
Get-Childitem –Path Get-Location -Recurse
This doesn't make sense. You're looking for a file or folder in the current directory with the literal name Get-Location. Like C:\Get-Location\. If you want to get the files in the current directory, you just don't specify the -Path parameter: Get-ChildItem -Recurse.
Where-Object { $_.Name -match $_.Name } is kind of nonsense code? The right hand side of the -match operator is going to be treated as a regular expression. That means . means "any character", square brackets and parentheses have special meaning, and so on. It's often going to always be true, but I can't imagine that you actually want to do what that says. It's very possible to construct a valid filename that doesn't match a regular expression with the same string value. For example '[01] File.avi' -match '[01] File.avi' is false.
Second, the -NewName parameter takes a string, while {$_.BaseName.insert(5,'-') + $_.Extension} is a ScriptBlock. That may work because some parts of Powershell allow that, but idiomatically I would say that it's wrong because it will not work consistently. A better option would be to use a string with embedded subexpressions like -NewName "$($_.BaseName.Insert(5,'-'))$($_.Extension)"
Finally, Rename-Item doesn't pass any output to the pipeline without the -PassThru parameter. You'd only process the first item and then I imagine the system would complain of an empty pipeline or only the first Rename-Item would do anything.
Try something like this:
$ShowTitle = "My Title -"
$SeasonNumber = "02"
# Getting all child files (In ALL subfolders)
$files = Get-Childitem -Recurse |
Where-Object { $_.Name -match 'some value or delete this command if you want all files' } |
# Insert a ' - ' between the episode number and the episode text.
Rename-Item -NewName "$($_.BaseName.Insert(5,'-'))$($_.Extension)" -PassThru |
# Append title and season number to the beginning of the file.
Rename-Item -NewName "$($ShowTitle)S$($SeasonNumber).E$($_.Name)" -PassThru |
# Makes a "-" between episode title and year of release.
Rename-Item -NewName "$($_.Name -replace '\[', '- [')" -PassThru

Related

how to change file names to their default with powershell

I just wanted to re-number my music files based on their date creation on windows 10 and I found this PowerShell script on the internet.
[ref]$i = 1; gci -file | Rename-Item -NewName {'{0:D} - {1}' -f $i.Value++, $_}
but this code didn't do that.
After that, I used the below code but unfortunately, my file names were broken and converted to numbers! see the code and image below
$count = 1; Get-ChildItem -File | Sort-Object LastWriteTime | Rename-Item -NewName { '{0:D {1}' -f $script:count++, $_.Extension }
So now I want to first rename my files to their default name and after that, I would like to re-number them by their date of creation. For example, if assuming my latest song is "song1.mp3" it should turn to "1 - song1.mp3".
Tnx a lot.

Script lists all files that don't contain needed content

I'm trying to find all files in a dir, modified within the last 4 hours, that contain a string. I can't have the output show files that don't contain needed content. How do I change this so it only lists the filename and content found that matches the string, but not files that don't have that string? This is run as a windows shell command. The dir has a growing list of hundreds of files, and currently output looks like this:
File1.txt
File2.txt
File3.txt
... long long list, with none containing the needed string
(powershell "Set-Location -Path "E:\SDKLogs\Logs"; Get-Item *.* | Foreach { $lastupdatetime=$_.LastWriteTime; $nowtime = get-date; if (($nowtime - $lastupdatetime).totalhours -le 4) {Select-String -Path $_.Name -Pattern "'Found = 60.'"| Write-Host "$_.Name Found = 60"; }}")
I tried changing the location of the Write-Host but it's still printing all files.
Update:
I'm currently working on this fix. Hopefully it's what people were alluding to in comments.
$updateTimeRange=(get-date).addhours(-4)
$fileNames = Get-ChildItem -Path "K:\NotFound" -Recurse -Include *.*
foreach ($file in $filenames)
{
#$content = Get-Content $_.FullName
Write-host "$($file.LastWriteTime)"
if($file.LastWriteTime -ge $($updateTimeRange))
{
#Write-Host $file.FullName
if(Select-String -Path $file.FullName -Pattern 'Thread = 60')
{
Write-Host $file.FullName
}
}
}
If I understood you correctly, you just want to display the file name and the matched content? If so, the following will work for you:
$date = (Get-Date).AddHours(-4)
Get-ChildItem -Path 'E:\SDKLogs\Logs' | Where-Object -FilterScript { $date -lt $_.LastWriteTime } |
Select-String -Pattern 'Found = 60.' |
ForEach-Object -Process {
'{0} {1}' -f $_.FileName, $_.Matches.Value
}
Get-Date doesn't need to be in a variable before your call but, it can become computationally expensive running a call to it again and again. Rather, just place it in a variable before your expression and call on the already created value of $date.
Typically, and for best practice, you always want to filter as far left as possible in your command. In this case we swap your if statement for a Where-Object to filter as the objects are passed down the pipeline. Luckily for us, Select-String returns the file name of a match found, and the matched content so we just reference it in our Foreach-Object loop; could also use a calculated property instead.
As for your quoting issues, you may have to double quote or escape the quotes within the PowerShell.exe call for it to run properly.
Edit: swapped the double quotes for single quotes so you can wrap the entire expression in just PowerShell.exe -Command "expression here" without the need of escaping; this works if you're pattern to find doesn't contain single quotes.

Powershell add suffix to filenames, based on prefix

I have a directory that consists of a number of text files that have been named:
1Customer.txt
2Customer.txt
...
99Customer.txt
I am trying to create powershell script that will rename the files to a more logical:
Customer1.txt
Customer2.txt
...
Customer99.txt
The prefix can be anything from 1 digit to 3 digits.
As I am new to powershell, I really don't know how I can achieve this. Any help much appreciated.
The most straigth forward way is a gci/ls/dir
with a where matching only BaseNames starting with a number with a
RegEx and piping to
Rename-Item and building the new name from submatches.
ls |? BaseName -match '^(\d+)([^0-9].*)$' |ren -new {"{0}{1}{2}" -f $matches[2],$matches[1],$_.extension}
The same code without aliases
Get-ChildItem |Where-Obect {$_.BaseName -match '^(\d+)([^0-9].*)$'} |
Rename-Item -NewName {"{0}{1}{2}" -f $matches[2],$matches[1],$_.extension}
Here is one way to do it:
Get-ChildItem .\Docs -File |
ForEach-Object {
if($_.Name -match "^(?<Number>\d+)(?<Type>\w+)\.\w+$")
{
Rename-Item -Path $_.FullName -NewName "$($matches.Type)$($matches.Number)$($_.Extension)"
}
}
The line:
$_.Name -match "^(?<Number>\d+)(?<Type>\w+)\.\w+$")
takes the file name (e.g. '23Suppliers.txt') and perform a pattern match on it, pulling out the number part (23) and the 'type' part ('Suppliers'), naming them 'Number' and 'Type' respectively. These are stored by PowerShell in its automatic variable $matches, which is used when working with regular expressions.
We then reconstruct the new file using details from the original file, such as the file's extension ($_.Extension) and the matched type ($matches.Type) and number ($matches.Number):
"$($matches.Type)$($matches.Number)$($_.Extension)"
I'm sure there's a nicer way to do this with regex, but the following is a quick first go at it:
$prefix = "Customer"
Get-ChildItem C:\folder\*$prefix.txt | Rename-Item -NewName {$prefix + ($_.Name -replace $prefix,'')}

Rename multiple folders containing special characters

I'm trying to process a folder of a few hundred folders that all have parenthesis and square brackets in the name, but also have an unwanted space before the square bracket that I would like removed.
example: c:/Documents/MainFolder/Subfolder1Title (Attribute1) (Attribute2) [UniqueNumber ] - []
(Where the space after "UniqueNumber is the unwanted space"
I would like to write a script that looks for all folders that have " ] - []" and replace it with "] - []" without changing the rest of the folder name, so that it ends up as: c:/Documents/MainFolder/Subfolder1Title (Attribute1) (Attribute2) [UniqueNumber] - []
I've tried several solutions from other questions, but most deal with just files instead of folders, and for some reason there's an issue with the square brackets that just seemingly can't be resolved. ( with use of `` before the [ )
Example:
$dir = "c:/Documents/MainFolder/"
CD $dir
Get-ChildItem | `
Where-Object {$_.Name -match ' ] - []'} | `
Rename-Item -LiteralPath $_fullname -NewName $_.fullname.replace ( " ] - []" , "] - []")
Please help.
Avoid asking multiple distinct questions at once. I will just answer the first question which is related to your question title.
The -match takes a regex, therefore you have to escape the [.
$_fullname is missing a dot.
Since you are using powershell-v2, you probably have to use curly brackets.
This should work:
Get-ChildItem | Where-Object {$_.Name -match '\s+]\s+-\s+\[]'} |
Rename-Item -NewName ({$_.fullname -replace "\s+]\s+-\s+\[]" , "] - []"})
Note: You should not change the directory, instead specify the path within the Get-ChildItem cmdlet.
Here the script I used that works:
$dir = "c:/" # changed this to C:/
# Create a Sample folder
$sampleFolderPath = Join-Path $dir 'Subfolder1Title (Attribute1) (Attribute2) [UniqueNumber ] - []'
New-Item $sampleFolderPath -ItemType Directory -Force
# Now lets rename it
Get-ChildItem -Path $dir |
Where-Object {$_.Name -match '\s+]\s+-\s+\[]'} |
Rename-Item -NewName ({$_.fullname -replace "\s+]\s+-\s+\[]" , "] - []"})

Powershell renaming a specific Character

I've been batch renaming .las files in powershell with a simple script:
cd "C:\Users\User\desktop\Folder"
Dir | Rename-Item -NewName {$_.name-replace "-", "" }
Dir | Rename-Item -NewName {$_.name-replace "_", "" }
Dir | Rename-Item -NewName {$_.BaseName+ "0.las"}
This has been working great, but I need to modify it to account for a different naming convention.
The files start out in this format: 123_45-67-890-12W_0
and get converted to 123456789012W00.las
Occasionally the number after the W will be non zero, and I need to carry that on as the last digit, eg. 123_45-67-890-12W_2 needs to go to 123456789012W02
I'm not sure how to use if statements and to select a specific digit in powershell format, which is how I would approach this problem. Does anyone have some ideas on how to go about this?
Thanks
You can use a regular expression to achieve this:
Get-ChildItem "C:\Users\User\desktop\Folder" | ForEach-Object {
#capture everything we need with regex
$newName = $_.Name -replace "(\d{3})_(\d{2})-(\d{2})-(\d{3})-(\d{2})(\w)_(\d)",'$1$2$3$4$5$6$7'
#insert 0 before last digit and append file extension
$newName = $newName.Insert(($newName.Length - 1), "0") + ".las"
#rename file
Rename-Item $_.FullName -NewName $newName
}
You can use the substring method to get all but the last character in the basename, then concatenate the zero, then use substring again to get the basename's last character, then finish off with the .las extension:
Dir | Rename-Item -NewName {($_.BaseName).substring(0,$_.BaseName.length - 1) + "0" + ($_.BaseName).substring($_.BaseName.length -1,1) + ".las"}
# ^^^^This gets everything but the last charcter^^^ ^^^^^^^^^^This gets the last character^^^^^^^^^^