remove file's end and the begigng using powershell - powershell

i have a folder contains pdf files starting with paracel_ and end with _manifest
for example :
paracel_123_manifest
i use this command to remove the "manifest" from the file but i dont konw how to remove the "paracel" from the satart of the file
$dir = "C:\temp"
$phrase = "_manifest"
$length=$phrase.Length
Get-ChildItem $dir -Recurse| Where-Object { $.Name -like "$phrase" } | Rename-Item -NewName { $.name.substring(0,$.BaseName.length-$length)+$.Extension}# -WhatIf -verbose
thanks in advance!!
hope someone can assist
A

$dir = "C:\temp"
$phrase = "_manifest"
Get-ChildItem $dir -Filter "paracel_*$phrase*.pdf" -Recurse | ForEach-Object {
Rename-Item $_.FullName -NewName ($_.Name.Replace("_manifest","")).Replace("paracel_","") -WhatIf -verbose
}
You were on the right path. I just changed the filter and put parsed the items in a foreach loop.

Related

How to include folders in Powershell -include string

I am doing some batch file name updates and am having trouble including folders. I have it currently set to target only specific file types, but I also want to include folders. Since folders don't have an extension I am unsure how to specify folders in the "-include" string. Any help would be greatly appreciated.
Here is what I am currently working with, but it ignores folders when I would like them included.
Get-ChildItem k:/toolbox/powershell -Include *.gif, *.jpg, *.png, *.xls,
*.xlsx, *.ppt, *.pptx, *.doc, *.docx, *.pdf -recurse | where {$_.name -match
"_"} | foreach {
$New=$_.name.Replace("_","-")
Rename-Item -path $_.Fullname -newname $New -passthru
}
(Get-Item '~\Desktop\*') | foreach { $FolderName = $_.name.Replace("_","-"); Rename-Item -path $_.fullname -newname $FolderName -passthru }
I would just add 2nd statement:
Get-ChildItem "k:/toolbox/powershell" -Recurse |where mode -eq d----- | where {$_.name -match "_"} | foreach {$New=$_.name.Replace("_","-")
Rename-Item -path $_.Fullname -newname $New -passthru }
If you run Get-ChildItem "k:/toolbox/powershell" you will receive a list of items where the "Mode" is "d-----" for directories, hence you can use that filter criteria for directories

UpperCase only first two letters of all filenames in a folder?

I know I can convert all filenames in a given folder to uppercase with the following:
Get-ChildItem -Path your_path -Recurse | Rename-item -NewName {$_.name.ToUpper()}
However, how can I capitalize only the first two letters of all filenames in a folder?
i.e.
ls123456_This_is_a_Test.pdf --> LS123456_This_is_a_Test.pdf
re98765_Another_Test.pdf --> RE98765_Another_Test.pdf
Thanks
Dan
Use the .SubString() method to separate the first two characters
## Q:\Test\2018\07\21\SO_51451148.ps1
$Folder = (Get-Item '.').FullName
Get-ChildItem -Path $Folder -File -Recurse |
Where-Object Name -match '^[a-z]{2}.' |
Rename-item -NewName {"{0}{1}" -f $_.Name.SubString(0,2).ToUpper(),
$_.Name.Substring(2)} -WhatIf
If the output looks OK, remove the -WhatIf parameter
try it :
Get-ChildItem "c:\temp" -file | %{
if ($_.Name.Length -gt 1)
{
$NewName="{0}{1}" -f $_.Name.SubString(0, 2).ToUpper(), $_.Name.Substring(2)
}
else
{
$NewName=$_.Name.ToUpper()
}
Rename-item $_.FullName $NewName -WhatIf
}

Recursively removing/renaming files using powershell

I have to go through many levels of child folders and remove special characters that are invalid in SharePoint, mainly '#&'
I have scoured the internet trying different commands; rename-item/move-item, variations of the two, all to no avail. The closest i've gotten is using:
Get-ChildItem -Recurse | Rename-Item -NewName {$_.Name -replace'[!##&]','_'}
but i keep getting this error: Rename-item: Source and destination path must be different.
Could someone point me in the right direction?
Regards
That error only happens when you attempt to rename a directory to the same NewName as the current name, you can safely ignore it.
Add -ErrorAction SilentlyContinue to silently suppress the error message:
Get-ChildItem -Recurse | Rename-Item -NewName {$_.Name -replace'[!##&]','_'} -ErrorAction SilentlyContinue
You need to filter out the files that you're not planning to rename:
Get-ChildItem -Recurse |
Where-Object { $_.Name -match '[!##&]' } |
Rename-Item -NewName {$_.Name -replace '[!##&]','_'}
something like this may work
dir -Recurse -File | ? basename -Match '[!##&]' | % {
# if the file.txt already exists, rename it to file-1.txt and so on
$num = 1
$base = $_.basename -replace'[!##&]', '_'
$ext = $_.extension
$destdir = Split-Path $_.FullName
$newname = Join-Path $destdir "$base$ext"
while (Test-Path $newname) {
$newname = Join-Path $destdir "$base-$num$ext"
$num++
}
ren $_.fullname $newname
}

how to convert function to work recursively

I have this awesome powershell script that will remove special characters from filenames:
Function Rename-Files($path)
{
Get-ChildItem -path $path |
Foreach-Object {
$newName = $_.name -replace '[^A-Za-z0-9-_ ]', ''
if (-not ($_.name -eq $newname)){
Rename-Item -Path $_.fullname -newname ($newName)
}
}
} #end function
Rename-Files -path "C:\somepath"
i would like to know whether it is possible to get this working not just on the top directory but recursively through the entire directory structure?
Just add the -Recurse Get-ChildItem parameter. e.g.
Get-ChildItem -Recurse -path $path

Renaming a file that has a bracket in the file name using power shell

I am trying to rename a file that has a bracket in the file name. This does not seem to work because powershell sees [] as special characters and does not know what to do.
I have a folder on my computer c:\test. I want to be able to look through that folder and rename all files or portions of the file. The following code seems to work but if the file has any special characters in it the code fails:
Function RenameFiles($FilesToRename,$OldName,$NewName){
$FileListArray = #()
Foreach($file in Get-ChildItem $FilesToRename -Force -Recurse | Where-Object {$_.attributes -notlike "Directory"})
{
$FileListArray += ,#($file)
}
Foreach($File in $FileListArray)
{
IF ($File -match $OldName )
{
$File | rename-item -newName {$_ -replace "$OldName", "$NewName" }
}
}
}
renamefiles -FilesToRename "c:\test" -OldName "testt2bt" -NewName "test"
I did find a similar question: Replace square bracket using Powershell, but I can't understand how to use the answer cause it's just a link explaining the bug:
For multiple files this can be done with one line.
To remove the bracket you should try:
get-childitem | ForEach-Object { Move-Item -LiteralPath $_.name $_.name.Replace("[","")}
Move-Item -literalpath "D:\[Copy].log" -destination "D:\WithoutBracket.txt"
Use the literalpath switch with the Move-Item cmdlet [instead of using the rename-item cmdlet]
As far as bracket are concerned, you've got Microsoft official answer in an old Technet Windows PowerShell Tip of the Week.
You can use :
Get-ChildItem 'c:\test\``[*``].*'
Thanks for help guys you all helped a lot this is the solution I came up with in the end after reading your reply’s .
I have a folder on my pc called c:\test and it has a file in it called "[abc] testfile [xas].txt" and i want it to be called testfile2.txt
Function RenameFiles($FilesToRename,$OldName,$NewName){
$FileListArray = #()
Foreach($file in Get-ChildItem $FilesToRename -Force -Recurse | Where-Object {$_.attributes -notlike "Directory"})
{
$FileListArray += ,#($file.name,$file.fullname)
}
Foreach($File in $FileListArray)
{
IF ($File -match $OldName )
{
$FileName = $File[0]
$FilePath = $File[1]
$SName = $File[0] -replace "[^\w\.#-]", " "
$SName = $SName -creplace '(?m)(?:[ \t]*(\.)|^[ \t]+)[ \t]*', '$1'
$NewDestination = $FilePath.Substring(0,$FilePath.Length -$FileName.Length)
$NewNameDestination = "$NewDestination$SName"
$NewNameDestination | Write-Host
Move-Item -LiteralPath $file[1] -Destination $NewNameDestination
$NewNameDestination | rename-item -newName {$_ -replace "$OldName", "$NewName" }
}
}
}
renamefiles -FilesToRename "c:\test" -OldName "testfile" -NewName "testfile2"