powershellprefixbasename

Powershell - How to prefix filename into folder for any path containing that file type


Powershell script needed to pull the file basename from a file type within time and date stamped folders on a directory and append those folders with that base name.

The script below works to replace the path name below but I need to prefix the folder. Is it possible to join-path in this way?

Original link for script below

cd C:\Directory
Get-ChildItem *.lsa -File -Recurse | ForEach-Object {
  Rename-Item (Split-Path $_ -Parent) ($_.BaseName)  -WhatIf 
}

Result:

What if: Performing the operation "Rename Directory" on target "Item: C:\Directory\originalpath 
Destination: C:\Directory\basename".

What I want is "C:\Directory\basename_originalpath"
Or even better would be "C:\Directory\basename\originalpath"

I think Join-path is the solution but I'm first time scripting and can't link the two commands. I also have to specify the starting directory as the first attempt ran my entire c:\ drive without it.


Solution

  • Its not pretty but I think this would work:

    Get-ChildItem *.lsa -File -Recurse | ForEach-Object {
        if(-Not (Test-Path -Path "$outputDirectory\$($_.BaseName)")){
            New-Item -WhatIf -ItemType Directory -Path "$outputDirectory\$($_.BaseName)"
        }
    
        Move-Item (Split-Path $_ -Parent) "$outputDirectory\$($_.BaseName)\$($_.Directory.BaseName)" -WhatIf
    }
    

    Updated code.