1

I use Test-Path to check existence and connectivity for a variety of files and folders in my scripts. If I get a return value of $false, I don't have any way of knowing if the file definitely doesn't exist, or if the user account doesn't have access or connectivity to the path.

How can I check and be certain that a file does not exist, while knowing the command had sufficient access and connectivity?

I was unable to attain this answer from the following posts:


I assembled the suggestion @Matt provided into a function as such:

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 data\myfile.txt'
msq
  • 146
  • 7
  • Possible duplicate of [Check if a file exists or not in Windows PowerShell?](https://stackoverflow.com/questions/31879814/check-if-a-file-exists-or-not-in-windows-powershell) – gravity May 28 '19 at 16:18
  • While the question is similar, I did not find the answer to this question on that post, or [A better way to check if a path exists or not in PowerShell](https://stackoverflow.com/questions/31888580/a-better-way-to-check-if-a-path-exists-or-not-in-powershell) – msq May 28 '19 at 16:23
  • 1
    You could attempt to read the file and check for access denied error? – Matt May 28 '19 at 16:45
  • Because you have an exception occurring ("Access Denied") that doesn't mean that it isn't the best way to do it. You would want to trap any exceptions (just as you would in any other situation) but still use `Test-Path` anyway. – gravity May 28 '19 at 16:58

1 Answers1

3

Why not attempt the get the item and examine the error message if it fails.

$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 in this case would contain a string of text with a message or the file/directory itself that you are testing against. You could also do the same thing with Test-Path ... -ErrorAction I guess it really depends what you want to do with the findings.

That code is not ideal but gives you the paths you needs. It differentiates between access denied, does not exist and does exist.

Matt
  • 45,022
  • 8
  • 78
  • 119