我使用 Test-Path
来检查脚本中各种文件和文件夹的存在和连接性。 如果我得到的返回值为 $false
,我无法知道该文件是否绝对不存在,或者用户帐户是否无法访问或连接到路径。
如何在知道命令具有足够访问权限和连接性的同时检查并确定文件不存在?
我无法从以下帖子中获得此答案:
-
检查Windows PowerShell中是否存在文件?
-
检查路径在PowerShell中是否存在的更好方法
我将@Matt提供的建议组装成一个函数:
function Get-FileType([string]$Path)
{
try
{
get-item -LiteralPath $Path -ErrorAction Stop
$exists = 'Exists'
}
catch [System.UnauthorizedAccessException] {$exists = 'Access Denied'} #Inaccessible
catch [System.Management.Automation.ItemNotFoundException]{$exists = 'Not Found'} #Doesn't Exist
catch [System.Management.Automation.DriveNotFoundException]{$exists = 'Not Found'} #Doesn't Exist
catch {$exists='Unknown'} #Unknown
return $exists
}
Get-FileType 'C:test datamyfile.txt'
为什么不尝试获取项目并在失败时检查错误消息。
$path = "\sqlskylinevmpathfile.txt"
$file = try{
Get-Item $path -ErrorAction Stop
} catch [System.UnauthorizedAccessException] {
"can't get to it"
} catch [System.Management.Automation.ItemNotFoundException]{
"does not exist"
}
if($file -eq "can't get to it"){
Write-Warning "File exists but access is denied"
} elseif($file -eq "does not exist"){
Write-Warning "Could not find file"
} else {
Write-Host "Oh Happy Days!" -ForegroundColor Green
}
在这种情况下,$file
将包含一个文本字符串,其中包含您正在测试的消息或文件/目录本身。你也可以对Test-Path ... -ErrorAction
做同样的事情,我想这真的取决于你想用这些发现做什么。
该代码并不理想,但为您提供了所需的路径。它区分访问被拒绝、不存在和确实存在。