gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:04:29 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com