Home > Net >  Renaming files inside a folder in powershell
Renaming files inside a folder in powershell

Time:10-12

I'm running this code from a folder at the same path I have a 'testfolder' with some files to try to rename them. When it runs for some reason it comes with an error because the file doesn't exist.

param(
    [string]$foldername = 'unknown'
)

if (Test-Path $foldername){
    $amount = Get-ChildItem $foldername | Measure-Object
    $confirmation = Read-Host "All", $amount.Count, "files will be renamed with the name", $newname " Yes/No?" 
    if ($confirmation -eq "Yes"){
        Get-ChildItem  $foldername| ForEach-Object {
            $newname = Read-Host "Pick a new name for a file."
            Rename-Item -Path $_ -NewName $newname
    }
        else {Write-Host "Sorry,",$foldername, "does not exist."}
    
    }
}

Error

Folders and files

I think its trying to rename them and put them at the same path where the script file is running, but it should be inside the folder 'testfolder'

CodePudding user response:

The issue is likely to be caused by the FileInfo instance, returned by Get-ChildItem, being coerced into a string and resolved into the file's Name (in Windows PowerShell) instead of the file's FullName. See this answer for details, similar issue and a more in depth explanation.

As for your code, it looks like you could leverage Cmdlet.ShouldProcess to ask for confirmation, delay-bind Script Block to rename your files and ValidateScript attribute declaration to validate that the input folder exists:

[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
    [Parameter(Mandatory)]
    [ValidateScript({
        if(Test-Path $_ -PathType Container) { return $true }
        throw [System.ArgumentException] "'$_' could not be found."
    })]
    [string] $FolderName = 'unknown'
)

$target = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($FolderName)
$files  = Get-ChildItem $foldername -File

if($PSCmdlet.ShouldProcess($target, "Renaming $($files.Count) files")) {
    $files | Rename-Item -NewName {
        Read-Host "Pick a new name for $($_.Name)"
    }
}

Now when calling your script you would get a prompt like the following:

PS ..\pwsh> .\test.ps1 myTestFolder
    
Confirm
Are you sure you want to perform this action?
Performing the operation "Renaming 1 files" on target "C:\path\to\myTestFolder".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
  • Related