执行Powershell脚本时缺少权限

时间:2020-11-03 20:11:22

标签: powershell

在上一篇文章Delete Files in subfolders after encode中,我得到了一个有效的脚本,我确认该脚本删除了我创建的测试文件夹中的一个文件,但在我的普通文件夹中,该脚本(既独立又在我的主文件中实现脚本)无法删除文件,同时给出如下错误消息: “缺少权限...;您没有权限,依此类推” 当以管理员身份运行脚本时,出现相同的错误。 我该怎么做才能解决此问题?

我得到的脚本:

Get-ChildItem *.mkv | where BaseName -notlike '*`[HEVC]' | foreach {
    # Convert the input file and send ffmpeg's output to the display,
    # by piping to Write-Host, rather than trough the pipeline.
    ffmpeg -i $_ -c:v libx265 -c:a copy -x265-params crf=25 "$($_.BaseName) [HEVC].mkv" -n |
       Write-Host

    # Conversion OK? Output the file-info object, which pipes it to Remove-Item.
    if ($LASTEXITCODE -eq 0) { $_ } 
 } | Remove-Item 

我所有文件夹的脚本:

$current_path = Get-Location
$directories = get-childitem -path $current_path -Recurse -Directory
Foreach ($dir in $directories) {
    Set-Location $dir.fullname
    & "G:\Folder1\Compressing ps1 and bat\ffmpeg powershell HEVC.ps1"   
}

1 个答案:

答案 0 :(得分:0)

注意:

  • OP的问题原来是由于特定于环境的权限问题而无法删除文件

    • 在脚本中将-Force开关添加到Remove-Item文件删除调用中,此问题已解决,这表明文件已设置了ReadOnly文件属性(例如,attrib +R $file)-这是-Force可以解决的唯一与权限相关的问题。
  • 如果要处理与目录有关的权限错误,而您想忽略,则下面的答案可能仍然很有趣。


有些目录甚至不允许管理员访问:

  • 每个用户配置文件中都有隐藏的系统联结,用于向后兼容,如this answer中所述;但是,这不适用于您,因为这些内容被隐藏,并且您的Get-ChildItem不包含-Force以便包含隐藏项。

  • 在Windows目录(通常为C:\Windows)中,存在无法访问的子目录,这些子目录没有被隐藏,例如C:\WINDOWS\CSC\v2.0.6C:\WINDOWS\System32\LogFiles\WMI\RtBackup

  • 通常可以设置权限以排除甚至管理员。

由于在所有这些情况下,都可以假设没有找到感兴趣的文件,因此您可以选择(初始)忽略这些错误:

$current_path = Get-Location
$directories = Get-Childitem -ErrorAction SilentlyContinue -ErrorVariable errs -Path $current_path -Recurse -Directory
foreach ($dir in $directories) {
  Set-Location -ErrorAction SilentlyContinue -ErrorVariable +errs $dir.fullname
  if (-not $?) { continue }
  & "G:\Folder1\Compressing ps1 and bat\ffmpeg powershell HEVC.ps1"   
}

这将使错误(-ErrorAction SilentlyContinue)保持沉默,但会将它们收集在(自选)$errs变量({{1} )。
通过消息显示这些错误且没有太多“噪音”的快速方法是运行
-ErrorVariable errs

如果您确信所有错误均来自于将被忽略的权限错误,则可以省略
-ErrorVariable +errs个参数,然后将$errs | ForEach-Object ToString替换为
-ErrorVariable,它只是悄悄地丢弃所有错误。