【问题标题】:Renaming files using PowerShell gives "Access to path is denied"使用 PowerShell 重命名文件会导致“拒绝访问路径”
【发布时间】:2017-07-14 11:39:48
【问题描述】:

再次,就像这里的任何其他“方括号”相关的 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:拒绝访问路径。 在 D:\[文件夹]\BatchReplaceWords.ps1:33 char:36 + ... ch-Object { 移动项目 -LiteralPath $_.Name $_.Name.Replace("$Replace" ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~ + CategoryInfo : PermissionDenied: (C:\Windows\Syst...y.format.ps1xml:FileInfo) [Move-Item], Unauthorized AccessException + FullyQualifiedErrorId : MoveFileInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.MoveItemCommand

更多信息:带有 PowerShell 版本 5 的 Windows 10。

【问题讨论】:

  • 使用-WhatIf 开关查看应该发生的情况:move-item -WhatIf -LiteralPath ...。这是查看文件名是否有意义的简单方法。
  • -LiteralPath $_.PSPath
  • @MathiasR.Jessen 同样的错误。虽然我要补充一点,我试图避免提供完整路径到“.Replace”,因为它可能会替换路径本身内部的某些内容(嗯,至少据我所知)。
  • @vonPryz 哇,不知何故,程序试图在 System32 文件夹上移动目标。 System32 目录中的许多消息之一:What if: Performing the operation "Move Directory" on target "Item: C:\Windows\System32\WindowsPowerShell\v1.0\en Destination: C:\Windows\System32\WindowsPowerShell\v1.0\en\en". 甚至没有一个针对当前文件夹(带有方括号的那个([ ])。
  • 你如何调用你的脚本?你打电话给Get-ChildItem 没有参数。

标签: powershell


【解决方案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)}

【讨论】:

  • 是的,这解决了它。虽然我仍然想知道为什么方括号突然把事情搞砸了。我使用的最后一行代码应该是我在浏览了很多之后发现的很多与方括号相关的问题的解决方案。然而我在这里。
【解决方案2】:
$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 }

【讨论】:

  • 嗯,这不是我理想的解决方案,因为它要求输入路径。虽然可以用一些代码行来修改。结果:它在带有方括号的目录中没有做任何事情。同时在普通目录上抛出Rename-Item : Cannot create a file when that file already exists. 错误。
猜你喜欢
  • 2021-10-04
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-12
  • 2012-03-06
  • 1970-01-01
相关资源
最近更新 更多