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'