Rajiv Ahmed
Rajiv Ahmed

Reputation: 29

Powershell - Append text to end of filenames in sub-directories recursively

Overview

Hi StackOverflow!

I'm hoping someone on here could help me.

I have built the following code to append text to the end of filename on a network drive. The files in question are primarily ".zip" files and usually range from 6 - 8 sub-directories in the parent folder with 8 - 10 ".zip" files per sub-directoy.

What I am hoping to achieve is to append text to the end of each filename recursively.

Code:

#Current Directory of creatives
$fileLocation = read-host "Type/Paste location of creatives"

if (Test-Path \\serverPath\name\* -PathType Leaf) {
    $serverPathName = "\\serverPath\name\"
    $driveLetter = "D:\"
    $fileLocation = ($fileLocation -replace [regex]::Escape($serverPathName),$driveLetter)
}
$fileLocation = Resolve-Path $fileLocation
Write-Output $fileLocation

$newText = read-host "Please enter text to append"
$newText = $newText -replace '\s','-'

$addMarket = read-host "Are folders split by market? [Y/N]"

$ZipFiles = Get-ChildItem -Path "$currentDirectory" -Recurse -Filter "*.zip"

if ($addMarket -eq "N") {
    foreach  ($Zipfile in $ZipFiles) {
        Get-ChildItem | %{$_|rename-item -NewName ((($_.BaseName -replace '\s','-') + "-" + $newText + $_.Extension))}
    }
}
elseif($addMarket -eq "Y") {
    foreach  ($Zipfile in $ZipFiles) {
        Get-ChildItem -File -Recurse | Rename-Item -NewName {(($_.BaseName -replace '\s','-')  + "-" + (($_.Directory.Name -replace '\s','-')) + "-" + $newText + $_.Extension).ToLower()}
    }
}
else {
    write-host "ERROR! Incorrect Input!"
    Write-Host "Exiting Script..."
    Exit
}

#Clear Console
clear
#Read-Host -Prompt “Press Enter to exit”

Current Situation:

When I run the above (without the loop function), it works fine but I have to into each sub-directory and run the script directly there - which is obviously time-consuming and monotonous.

When I run it within the loop, it works but loops for a long time until the total count of ".zip" files have been reached. e.g. 8 sub-dirs, 9 ".zip" = loops 72 times - each time appending the same text.

Expected Situation:

I wish to run the script from the parent folder of the sub-dirs and the script will only append the text once per sub-dir to all ".zip" and then exit the script.

Problem(?)

I believe the issue lies in the following variable:

$ZipFiles

But I am unable to figure out how to rectify this. I've set it to find all ".zip" files in the parent folder. I've also set it to count he number of files per sub-dir:

Get-ChildItem -Directory | ForEach-Object { Write-Host $_.FullName $(Get-ChildItem $_ | Measure-Object).Count}

But neither has worked for me.

Summary:

I'm hoping someone can point out to me the error I am making and where the fix needs to be. I am open to all suggestions. If there is a better approach, please also let me know. I don't mind changing how the code works, if it means the same end result.

Thanks for reading!

Rajiv Ahmed

Upvotes: 1

Views: 523

Answers (1)

Olaf
Olaf

Reputation: 5232

You have some errors/mistakes in your code:
- You ask to provide a $fileLocation but you don't use it in your code.
- Instead you use a variable $currentDirectory but that's not defined.
- Then you collect all zip files in a variable $ZipFiles, you iterate over this array where you already have zip files but you use Get-ChildItem to get them again. ;-)

Something like this should work actually:

$fileLocation = read-host "Type/Paste location of creatives"

if (Test-Path \\serverPath\name\* -PathType Leaf) {
    $serverPathName = "\\serverPath\name\"
    $driveLetter = "D:\"
    $fileLocation = ($fileLocation -replace [regex]::Escape($serverPathName), $driveLetter)
}
$fileLocation = Resolve-Path $fileLocation
Write-Output $fileLocation

$newText = read-host "Please enter text to append"
$newText = $newText -replace '\s', '-'

$addMarket = read-host "Are folders split by market? [Y/N]"

if ($addMarket -eq "N") {
    Get-ChildItem -Path $fileLocation -Recurse -Filter "*.zip" -File |  
    ForEach-Object { 
        Rename-Item -Path $_.FullName -NewName ((($_.BaseName -replace '\s', '-') + "-" + $newText + $_.Extension)) 
    }
}
elseif ($addMarket -eq "Y") {
    Get-ChildItem -Path $fileLocation -Recurse -Filter "*.zip" -File |  
    ForEach-Object { 
        Rename-Item -Path $_.FullName -NewName ((($_.BaseName -replace '\s', '-') + "-" + (($_.Directory.Name -replace '\s', '-')) + "-" + $newText + $_.Extension).ToLower())
    }
}
else {
    write-host "ERROR! Incorrect Input!"
    Write-Host "Exiting Script..."
    Exit
}

Clear-Host

Upvotes: 2

Related Questions