'Checking if a UNC Path/Server Folder Exists
I am working on a project that utilizes a PowerShell script that creates a new login on a remote SQL Server (SSMS) and then checks to see if a particular folder exists on the server. If the folder does not already exist, the script will create that folder.
The issue I am having is that I cannot verify whether or not the folder exists since the path I am testing is a UNC path of the form "\\server\Files\Log". I have tried many different solutions that I have found through a couple hours of searching online, and all solutions return FALSE even though I am testing a server and folder I know already exist.
I am using PowerGUI to write my script and my system is using PowerShell v5. What I have tried so far:
Test-Path $path
(where$path
has been set to \\server)Test-Path "filesystem::\\Srv"
[System.IO.Directory]::Exists($path)
I even tried
[System.IO.Directory]::Exists('G:\')
using all of the letters I have network servers mapped to to see if I needed to map to the drives to make it work (all returned FALSE)
What am I missing here? Any thoughts on this topic would be greatly appreciated as I have been grinding on this for a while with no progress being made.
EDIT: For anyone who might stumble upon this later, please read the comments, which I found to be super helpful. My main issue was that I was running PowerShell as an administrator which does not have the same permissions as my normal user account. Also note that Test-Path \\server
alone does not work, a folder must also be referenced.
Solution 1:[1]
You already have the correct answer:
Test-Path $path
or
Test-Path \\server.domain.tld\ShareName
If Test-Path
is returning false, I can think of three things that could be wrong:
- The share does not exist on that server, or at least with the name you expect
- Your user does not have permission to read that share
- You are specifying the short name of the server, and you need the FQDN to resolve it. This is common in multidomain environments.
After re-reading your question, it looks like you might be running Test-Path \\server
. You cannot check for the existence of a server this way, you have to specify both the server and the share name at a minimum. If you want to know that a server exists and is online, use Test-Connection
(assuming you are able to ping
this server in the first place). Here is an example of using Test-Connection
:
$serverName = 'server.domain.tld'
$sharePath = 'ShareName' # you can append more paths here
if( Test-Connection $serverName 2> $null ){
Test-Path "\\${serverName}\${sharePath}"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |