使用 Powershell 和 Test-Path,如何区分 "folder doesn't exist" 和 "access denied"
Using Powershell and Test-Path, how can I tell the difference between a "folder doesn't exist" and "access denied"
在 powershell 中使用 Test-Path 命令,如何区分 "folder doesn't exist" 和 "access denied"?
试试
Test-Path $PathToFolder -ErrorAction SilentlyContinue
然后测试看是否未授权
$Error[0].Exception.GetType()
TL;DR:好消息是 Test-Path
通常不会 return false 即使你没有权限(如果没有,你会得到一个异常而不是简单 $false
)
更深入地说,这取决于您所说的拒绝访问是什么意思。根据您要检查的权限,将取决于适合您的 PowerShell 命令。
例如C:\System Volume Information是非管理员无权访问的文件夹。 Test-Path
return对于此文件夹是正确的 - 它存在 - 即使您无法访问它。另一方面,运行ning 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
Resolve-Path
会完成这项工作,如果找不到路径,则会抛出错误。
在 powershell 中使用 Test-Path 命令,如何区分 "folder doesn't exist" 和 "access denied"?
试试
Test-Path $PathToFolder -ErrorAction SilentlyContinue
然后测试看是否未授权
$Error[0].Exception.GetType()
TL;DR:好消息是 Test-Path
通常不会 return false 即使你没有权限(如果没有,你会得到一个异常而不是简单 $false
)
更深入地说,这取决于您所说的拒绝访问是什么意思。根据您要检查的权限,将取决于适合您的 PowerShell 命令。
例如C:\System Volume Information是非管理员无权访问的文件夹。 Test-Path
return对于此文件夹是正确的 - 它存在 - 即使您无法访问它。另一方面,运行ning 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
Resolve-Path
会完成这项工作,如果找不到路径,则会抛出错误。