首页 文章

使用PowerShell重命名文件会显示“拒绝访问路径”

提问于
浏览
0

再次,像任何其他“Square Bracket”相关的PowerShell,我已经阅读了许多其他类似的问题 . 但问题是,我得到的错误代码甚至与它们中的任何一个都不相似(“拒绝访问”) . 这可能是大多数这些解决方案无效的原因 .

基本上我想基于输入批量重命名文件夹中的文件 . 只有在带方括号( [] )的目录上放置并执行.ps1文件时,才会出现此问题 . 删除这些括号表示操作顺利 .

我的计划的重要部分:

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

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

同时,我得到了一堆错误代码,它们彼此相似,如下所示:

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

更多信息:Windows 10与PowerShell版本5 .

2 回答

  • 1

    如果要枚举带方括号的文件夹中的文件,则需要为 Get-ChildItem-LiteralPath 参数指定位置 .

    可以通过 $PSScriptRoot (PowerShell 3.0)或通过 $MyInvocation 自动变量找到脚本的位置:

    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)}
    
  • 0
    $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 }
    

相关问题