Secret Messenger
Secret Messenger

Reputation: 21

Renaming files using PowerShell gives "Access to path is denied"

Again, like any other "Square Bracket" related PowerShell here, I've read many others similar problems. But the thing is, the error codes I get aren't even similar to any of them ("Access Denied"). Which might be why most of those solutions are ineffective.

Basically I want to batch rename files in a folder based on inputs. The problem only arise when you put and execute the .ps1 file on a dir with square brackets ([]). Removing those brackets shows smooth operation.

The important bits of my program:

$Replace = Read-Host -Prompt 'To Replace'
$New = Read-Host -Prompt 'With'

Get-ChildItem | ForEach-Object { Move-Item -LiteralPath $_.Name $_.Name.Replace("$Replace", "$New") }

Meanwhile, I get a bunch of error codes which are similar to one another like this:

Move-Item : Access to the path is denied.
At D:\[Folder]\BatchReplaceWords.ps1:33 char:36
+ ... ch-Object { Move-Item -LiteralPath $_.Name $_.Name.Replace("$Replace" ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\Windows\Syst...y.format.ps1xml:FileInfo) [Move-Item], Unauthorized AccessException
    + FullyQualifiedErrorId : MoveFileInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.MoveItemCommand

More info: Windows 10 with PowerShell version 5.

Upvotes: 1

Views: 4037

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

You need to specify a location to Get-ChildItem's -LiteralPath parameter if you want to enumerate files in a folder with square brackets.

The location of the script can be found through $PSScriptRoot (PowerShell 3.0+) or through the $MyInvocation automatic variable:

if(-not(Get-Variable PSScriptRoot -Scope Script)){
    $PSScriptRoot = Split-Path $script:MyInvocation.MyCommand.Path
}

$Replace = Read-Host -Prompt 'To Replace'
$New = Read-Host -Prompt 'With'

Get-ChildItem -LiteralPath $PSScriptRoot |Rename-Item -NewName {$_.Name.Replace($Replace,$New)}

Upvotes: 1

Maximilian Burszley
Maximilian Burszley

Reputation: 19654

$TextToReplace = Read-Host -Prompt 'Enter the filename text to replace:'
$ReplacementText = Read-Host -Prompt 'What are you replacing this text with?'
$Path = Read-Host -Prompt 'Which path do these files exist?'

GCI -Path $Path |
  ? { $_.FullName -like "*$TextToReplace*" } |
  % { Rename-Item -Path $_.FullName -NewName $ReplacementText }

Upvotes: 0

Related Questions