如何确认文件不存在,而不是拒绝访问?

时间:2019-05-28 16:15:26

标签: powershell file

我使用NoMethodError in Employees#destroy Showing /Desktop/bad/current/app/views/employees/destroy.js.erb where line #1 raised: undefined method `id' for nil:NilClass Rails.root: /Desktop/bad/current Application Trace app/views/employees/destroy.js.erb:1:in `_app_views_employees_destroy_js_erb__4462192751889852231_70177039108760' 检查脚本中各种文件和文件夹的存在和连接。如果我得到的返回值为Test-Path,那么我将无法确定绝对文件是否不存在,或者用户帐户是否没有访问权限或连接性到路径。

在知道命令具有足够的访问权限和连接性的情况下,如何检查并确定文件不存在?

我无法通过以下帖子获得此答案:


我将提供的建议@Matt组装成这样的函数:

$false

1 个答案:

答案 0 :(得分:3)

为什么不尝试获取项目并检查错误消息(如果失败)。

$path = "\\sqlskylinevm\path\file.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做同样的事情,我想这实际上取决于您要对发现进行什么处理。

该代码并不理想,但可以为您提供所需的路径。它区分拒绝访问,不存在和确实存在。