Skipping files with a given prefix when renaming - powershell

I have the following script for renaming a bunch of files in a directory, adding the name of the directory to the start of them:
$s = "Y:\Teknisk Arkiv\Likeretter 111-Å1\E2_Kretsskjema\02_Likeretter styring\3AJJ000302-222"
Get-ChildItem -Path $s -Exclude $_.Directory.Name* | rename-item -NewName { $_.Directory.Name + '_' + $_.Name }
Before running the script the files in the folder looks something like this
after like this
As you can see it does more or less what I want, except that -exclude $_.DirectoryName* doesn't prevent files which already have the foldername as a prefix from being renamed. What am I doing wrong here?

$_ in a pipeline is only defined inside a script block used in a non-initial pipeline segment, where it refers to the input object at hand, so in your Get-ChildItem command it is effectively undefined.
Even if $_.Directory.Name did have a value, $_.Directory.Name* wouldn't work as expected, because it would be passed as 2 arguments (you'd have to use "$($_.Directory.Name)*" or ($_.Directory.Name + '*').
You instead want to extract the directory name from the $s input path, which you can do with Split-Path -Leaf, and then append '*'.
In order for -Exclude to be effective, the input path must end in \*, because -Include and -Exclude filters - perhaps surprisingly - operate on the leaf component of the -Path argument, not on the child paths (unless -Recurse is also specified).
To put it all together:
Get-Item -Path $s\* -Exclude ((Split-Path -Leaf $s) + '*') |
Rename-Item -NewName { $_.Directory.Name + '_' + $_.Name }
I've switched to Get-Item, since \* is now being used to enumerate the children, but Get-ChildItem would work too.

The $_ is only valid when it is used on the right-side of a pipeline meaning when you have a collection of items and "pipe" them through the "$_" would represent the current item.
Since the directory name you want excluded is static you can just hardcode it and use as your exclude filter.
$s = "Y:\Teknisk Arkiv\Likeretter 111-Å1\E2_Kretsskjema\02_Likeretter styring\3AJJ000302-222"
$exclude_filter = "3AJJ000302-222*"
Get-ChildItem -Path $s -Exclude $exclude_filter | rename-item -NewName { $_.Directory.Name + '_' + $_.Name }
Also try to use "-whatif" with rename-item so you know what will happen before it happens.

$_ represents the currently processed item, what requires a ForEach-Object or a scriptblock inside a pipe, not present at the begin of your command.
Solution make the path a FileInfoObject and use -Exclude
$s = Get-Item "Y:\Teknisk Arkiv\Likeretter 111-Å1\E2_Kretsskjema\02_Likeretter styring\3AJJ000302-222"
Get-ChildItem -Path $s -Exclude "$($s.Name)*"|Rename-Item -NewName {$_.Directory.Name+'_'+$_.Name}
solution use a Where-Object to filter files already starting with the directory name
Get-ChildItem -Path $s | Where-Object {$_.Directory.Name -notlike "$($_.Name)*"} |
Rename-Item -NewName { $_.Directory.Name + '_' + $_.Name }
Solution use the RegEx based -replace operator to prepend the directory name and use a negative lookahead assertion to exclude files which already have it.
Get-ChildItem -Path $s |
Rename-Item -NewName {$x=$_.Directory.Name;$_.Name -replace "^(?!$x)",$x}

Related

Find Files in Subdirectories with Specific Text and Rename

From root folder, I am trying to search all files in subdirectories with "-poster" and rename those files to only poster without changing the file extension. All these files have other text in front of the "-poster" that I want to remove, and all the files are .jpgs.
Would a command such as this work:
Get-ChildItem -filter *-poster* -recurse | ForEach {Rename-Item $_ -NewName "poster.jpg"}
I haven't tried it, as don't want to risk changing other files.
Use the -WhatIf common parameter to preview an operation without actually performing it:
Get-ChildItem -Filter *-poster* -Recurse |
Rename-Item -NewName poster.jpg -WhatIf
Note:
-WhatIf does not test actual runtime conditions.
That is, if a poster.jpg file already exists in the target directory, the Rename-Item call will fail once -WhatIf is removed.
To handle this case, you have the following options, depending on your use case:
Allow the failure, if you don't expect a preexisting file.
Ignore the failure, if a preexisting file implies that no action is needed: add -ErrorAction Ignore to the Rename-Item call.
Blindly overwrite the existing file, by adding -Force to the Rename-Item call.
Create a file with a different name, such as by appending a sequence number, using a delay-bind script block - see below.
Get-ChildItem -Filter *-poster* -Recurse |
Rename-Item -NewName {
$newBaseName = 'poster.jpg'
$newBaseName = [IO.Path]::GetFileNameWithoutExtension($newName)
$newExtension = [IO.Path]::GetExtension($newName)
$suffix = ''
if ([array] $preexisting = Get-ChildItem -File -LiteralPath $_.DirectoryName -Filter "$newBaseName*$newExtension")) {
$highestNumSoFar = [int[]] ($preexisting.BaseName -replace '^.*\D') | Sort-Object -Descending | Select-Object -First 1
$suffix = $highestNumSoFar + 1
}
$newBaseName + $suffix + $newExtension
} -WhatIf

How do I recursively rename files in a directory with Powershell?

I have a powershell script which appends " - Confidential" to the end of files that don't already match the string "Confidential" within the filename. When running this script in the directory, it works. However, I need it to rename all the items within the subfolder too. How could I achieve this?
Get-ChildItem * -Exclude *Confidential* -Recurse |
ForEach {Rename-Item -NewName { $_.BaseName + " - Confidential" + $_.Extension }}
Thanks all for reading.
You're close, but there's a few problems:
Rename-Item is missing the original file, so let's add $_ to it. We could have also given it $_.FullName but I'm just passing the entire object to it.
Rename-Item is being given a script block with no input for -NewName because you've used curly braces ({}), so we change it to regular brackets (()).
Subfolders are also being renamed, which also results in files in them not being recursed (because they contain Confidential), so we specify the -File switch on Get-ChildItem to only return files.
So that brings us to this:
Get-ChildItem * -File -Exclude *Confidential* -Recurse |
ForEach {Rename-Item $_ -NewName ( $_.BaseName + " - Confidential" + $_.Extension )}
And just some cleanup/optimisation:
Remove wildcard (*) from Get-ChildItem. It already assumes all items in the folder you're in.
Enclose string in quote marks.
Add some spaces inside script block and change ForEach alias to shorter % alias (both just my personal preference).
And the final result looks like this:
Get-ChildItem -File -Exclude "*Confidential*" -Recurse |
% { Rename-Item $_ -NewName ( $_.BaseName + " - Confidential" + $_.Extension ) }
As always, you can do a dry run by specifying -WhatIf on Rename-Item, just in case there's some unexpected behaviour.
Edit: You could actually just pipe the output of Get-ChildItem into Rename-Item like so without the need for ForEach-Object:
Get-ChildItem -File -Exclude "*Confidential*" -Recurse |
Rename-Item -NewName { $_.BaseName + " - Confidential" + $_.Extension }

Remove recursively "_v1" from files in multipe sub folders

I have multiple files stored in folders and subfolders. Almost all of them contain _v1 at the end of the BaseName. I tried the following but I'm getting an error.
Get-ChildItem -Recurse * -Filter "/(_v1)/" |
Rename-Item -NewName { $_.Name -replace '/(_v1)/','' } -WhatIf
Error:
Get-ChildItem : Second path fragment must not be a drive or UNC name.
Try this :
Get-ChildItem "C:\test\ " -recurse -Filter "*_V1*" | % { Rename-Item $_ -NewName $($_.Name -replace "_V1","" ) }
PowerShell isn't Perl. Forward slashes don't indicate a regular expression, they're just literal forward slashes, so neither your filter expression nor your search string will match the intended files. Also, the parentheses (i.e. the capturing group) serve no purpose, so you should remove them.
Use a wildcard pattern as the filter string for Get-ChildItem and apply the regular expression replacement to the basename to avoid unintentional replacements of _v1 elsewhere in the file names.
Get-ChildItem -Filter '*_v1.*' -Recurse |
Rename-Item -NewName { ($_.BaseName -replace '_v1$') + $_.Extension }
If you're running at least PowerShell v3 you can add the parameter -File to Get-ChildItem so that it won't return directories.

Grandparent Folder Name To File Name

I have a script that runs when I specify the exact directory of c:\script\19\ the problem is, have other folders in the c:\script such as 18, 17, 16. The script I have is appending the 19 in front of all of the files. How do I get this to look at the grandparent of the file it's renaming and append it? An example of how it's working is files like this:
c:\script\18\00000001\Plans.txt
c:\script\19\00001234\Plans.txt
c:\script\17\00005678\App.txt
But my script is renaming the files like this
c:\script\18\00000001\19-0001 Plans.txt
c:\script\19\00001234\19-1234 Plans.txt
c:\script\17\00005678\19-5678 App.txt
My script is this:
$filepath = Get-ChildItem "C:script\" -Recurse |
ForEach-Object {
$parent = $_.Parent
$grandparent = $_.fullname | Split-Path -Parent | Split-Path -Parent | Split-Path -Leaf
}
Get-ChildItem "C:\Script\" –recurse –file |
Where-Object {$_.Name –notmatch ‘[0-9][0-9]-[0-9]’} |
rename-item -NewName {$grandparent + '-' + $_.Directory.Name.SubString($_.Directory.Name.length -4, 4) + ' ' + $_.Name}
The simplest solution is to combine string-splitting with the -split operator with a delay-bind script block (which you've tried to use):
Get-ChildItem C:\Script –Recurse –File -Exclude [0-9][0-9]-[0-9]* |
Rename-Item -NewName {
# Split the full path into its components.
$names = $_.FullName -split '\\'
# Compose the new file name from the relevant components and output it.
'{0}-{1} {2}' -f $names[-3], $names[-2].Substring($names[-2].Length-4), $_.Name
} -WhatIf
-WhatIf previews the renaming operation; remove it to perform actual renaming.
Note how -Exclude is used with a wildcard expression directly with Get-ChildItem to exclude files that already have the target name format.
The main reason your original didn't work is that you calculated single, static
$parent and $grandparent values, instead of deriving the input path-specific values from each input path.
Additionally, your $grandparent calculation was needlessly complicated; Gert Jan Kraaijeveld's helpful answer shows a simpler way.
To get the grandparent of a $file object:
$file.Directory.Parent
The parent directory of a file is the 'Directory' member of the file object.
The parent directory of a directory is the 'Parent' member of the directory object.
It is not hard, but confusing it sure is...
Edit
You asked for my solution:
Get-ChildItem C:\script -Recurse -File | ForEach-Object {
$parent = $_.Directory.Name
$grandparent = $_.Directory.Parent.Name
Rename-Item $_.FullName -NewName "$grandparent-$($parent.Substring($parent.length-4,4)) $($_.name)"
}
I used the -file parameter of Get-ChildItem to get only files from the folder structure. I'm not sure that suits in your situation

error from Powershell when try to rename with sequential prefix *recursively*

I have no problem adding sequential prefixes to filenames. The following works great on the top directory in question.
$path="E:\path\newtest1"
$count=4000
Get-ChildItem $path -recurse | Where-Object {!$_.PSIsContainer -and $_.Name -NotMatch '^\d{4}\s+'} | ForEach -Process {Rename-Item $_ -NewName ("$count " + $_.name -f $count++) -whatif}
BUT if there are files in subfolders within the top directory, these are all completely missed. Whatif reports that for any deeper file it "does not exist".
I have tried the following, based on looking at some pages on other recursion problems, but as you can probably guess I have no clue what it is doing. Whatif shows that it does at least pickup and rename all the files. But the following does it too much and makes multiple copies of each file with each number:
$path="E:\path\newtest1"
$count=4000
Get-ChildItem -recurse | ForEach-Object { Get-ChildItem $path | Rename-item -NewName ("$count " + $_.Basename -f $count++) -whatif}
Really keen to get some guidance on how to get the first of these two snippets to work to find all files in all subdirectories and rename them with sequential number prepended.
Try it like so:
Get-ChildItem $path -recurse -file | Where Name -NotMatch '^\d{4}\s+' |
Rename-Item -NewName {"{0} $($_.name)" -f $count++} -whatif
When you supply $_ as an argument (not a pipeline object), that gets assigned to the Path parameter which is of type string. PowerShell tries to convert that FileInfo object to a string but unfortunately the "ToString()" representation of files in nested folders is just the filename and not the full path. You can see this by executing:
Get-ChildItem $path -recurse -file | Where Name -NotMatch '^\d{4}\s+' | ForEach {"$_"}
The solution is either to A) pipe the object into Rename-Item or B) use the FullName property e.g. Rename-Item -LiteralPath $_.FullName ....