On my local computer I created the network drive D:/
that points to \\MyComputerName\D
.
On my local disk C:/
I created a folder with the name D
and configured a network share with permission to everyone on that share.
Then I start Windows PowerShell ISE
. My working directory is C:\Users\username
After that I create a folder with Powershell within this network drive such as
[System.IO.Directory]::CreateDirectory("D:/Foo/Bar")
the directory Foo
with his subfolder Bar
will be created successfully.
Then I remove the Foo
folder within D:/
and start Visual Studio 2019 with Admin Permissions.
Then I create a simple C#.NET Console Application such as
class Program
{
static void Main(string[] args)
{
System.IO.Directory.CreateDirectory(@"D:/Foo/Bar");
}
}
If I run the Console Application the directory will not be created and I get System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'D:\Foo\Bar'.'
What should I do to create successfully the folder with my simple console application?
Fundamentally, if you run a process with elevation (as administrator), it will not see the drive mappings you've established while running non-elevated.
You can verify this as follows:
# Establish a (temporary) mapping; making it persistent makes no difference.
# Note: This assumes that the admin shares are turned on.
net use T: "\\$(hostname)\c$\Users"
# Start a new PowerShell process *elevated* (as admin)
# You'll see that it can't find drive T:
Start-Process -Verb Runas powershell '-noprofile -c Get-ChildItem T:; pause'
# Clean up
net use T: /del
The simplest workaround is to use the UNC path directly to create your folder.
If you don't want to hard-code that into your application or you don't want to re-create the mapping for your elevated incarnation beforehand, you'll have to find some other way to communicate the drive-mapping information from your non-elevated incarnation to your elevated one.
If all code that needs to see the mapped drive is run via PowerShell, a solution is to place net use
calls in the $PROFILE
file.