powershell - 使用 Powershell 和测试路径,我如何区分 "folder doesn' t 存在”和 "access denied"

标签 powershell

在 powershell 中使用 Test-Path 命令,如何区分“文件夹不存在”和“拒绝访问”?

最佳答案

TL;DR:好消息是 Test-Path即使您没有权限,通常也不会返回 false (如果没有权限,您将得到一个异常而不是简单的 $false )

更深入地说,这取决于您所说的拒绝访问是什么意思。根据您要检查的权限,将取决于哪些 PowerShell 命令适合您。

例如,C:\System Volume Information 是一个非管理员无权访问的文件夹。 Test-Path此文件夹返回 true - 它存在 - 即使您无法访问它。另一方面,运行 Get-Child-Item失败。所以在这种情况下,你需要运行

$path = 'C:\System Volume Information'
if ((Test-Path $path) -eq $true)
{
    gci $path -ErrorAction SilentlyContinue
    if ($Error[0].Exception -is [System.UnauthorizedAccessException])
    {
        # your code here
        Write-Host "unable to access $path"
    }
}

但是,如果您有读取权限但没有写入权限,那么您必须实际尝试写入文件,或查看其安全权限并尝试找出适用于脚本运行的当前用户的内容:
(get-acl C:\windows\system32\drivers\etc\hosts).Access

关于powershell - 使用 Powershell 和测试路径,我如何区分 "folder doesn' t 存在”和 "access denied",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28588181/

相关文章:

json - 如何在 powershell 中替换 json 文件中的属性

powershell - 如何从给定的 powershell 数组中获取第一列?

powershell - Powershell:Get-Item与Get-ChildItem

powershell - 在 Oneliner 中的 ConvertFrom-StringData 之后删除重复项

powershell - 在PowerShell中 “$myvariable =”和Set-Variable有什么区别?

visual-studio - 第二次运行脚本后,Powershell 无法覆盖持续错误?

powershell - 抛出了 'Microsoft.Rest.Azure.CloudException' 类型的异常

postgresql - 连接到 docker postgres 实例 : "The server encountered an internal error and was unable to complete your request." 时出现 pgadmin 错误

powershell - 术语 'AzCopy' 未被识别为 cmdlet、函数、脚本文件的名称

c# - ASP.NET 托管 Active Directory RSAT powershell 脚本--DC 挂断