Reputation: 79
Using PowerShell, I'm struggling to locate a mechanism to determine if a path truely doesn't exist or if I don't have permissions to it. For instance, if I use the "Test-Path" commandlet on a path that is valid but I don't have permissions to, the result will be $false. I would prefer to use a try / catch block to try the command and catch an unathorizedAccessException exception or a ItemNotFoundException exception and handle the responses accordingly.
Any assistance would be appreciated.
Upvotes: 0
Views: 4913
Reputation: 43
Probably if you are using invoke command and Acces Denied is coming then you need to use Cred-SSP
.
For example:
$UserName='<username>'
$securekey= ConvertTo-SecureString '<secure-key>' -AsPlainText -Force;
$credentialdetail= New-Object System.Management.Automation.PSCredential -ArgumentList $UserName,$securekey;
Invoke-Command -Credentials $credentialdetail -ComputerName '<computername>' -Authentication CredSSP -ScriptBlock { '<...>' }
Upvotes: 1
Reputation: 60918
Personally I use this .net code to catch the exception accessing a share or local path:
add this type in powershell
add-type @"
using System;
using System.IO;
public class CheckFolderAccess {
public static string HasAccessToWrite(string path)
{
try
{
using (FileStream fs = File.Create(Path.Combine(path, "Testing.txt"), 1, FileOptions.DeleteOnClose))
{ }
return "Allowed";
}
catch (Exception e)
{
return e.Message;
}
}
}
"@
use it in this way:
> [checkfolderaccess]::HasAccessToWrite("\\server\c$\system volume information")
Access to path '\\server\c$\system volume information\Testing.txt' denied.
> [checkfolderaccess]::HasAccessToWrite("\\nonexistingserver\nonexistingpath")
Path not found.
Upvotes: 0