How to test the shared location path from the remote computer in PowerShell?


Many times we need to test the NAS path or shared path location from the remote server. Meaning we need to check if the shared path is accessible from the remote location and we use the Test-Path that time but we get an error of PermissionDenied or UnauthorizedAccessExcept.

Our sample code is shown below and in this example, we are using the Invoke-Command to connect to another computer and from there we are checking if the shared path is accessible.

Example

Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock {
   Test-Path -Path "\ad\Shared\Temp"
}

This script throws an exception.

Output

Access is denied
    + CategoryInfo          : PermissionDenied: (\ad\Shared\Temp:String) [Test-Path], UnauthorizedAccessException
    + FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.TestPathCommand
    + PSComputerName        : LabMachine2k16
False

This is not the permission issue but this is a PowerShell remoting issue. By default PowerShell remoting supports one layer of remoting, here we are connecting to a remote machine and again checking the shared path from it so it becomes the 2 stages of remoting and PowerShell doesn't support it.

To get this issue solved, we can use the Map drive to test if we can connect to it successfully or not. If yes then the remote server has connectivity to that path. For example,

Example

Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
   if(New-PSDrive -Name X -PSProvider FileSystem `
      -Root "\Ad\Shared\Temp" -EA Ignore){
       Write-Output "Path is accessible"
   }
}

Output

Path is accessible

Updated on: 18-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements