Changing directory based on creation of network mapped drive

Hi guys,

I am trying to map a network drive with a randomly generated letter.

$drive = Get-ChildItem function:[f-z]: -n | Where { !(Test-Path $_) } | select -First 1
$env = New-PSDrive -Name ($drive)[0] -PSProvider "FileSystem" -Path

After that I want to change the directory to be the newly created drive. What I am doing:

cd $drive:
$someEnv = $drive + ":\include"

Changing the directory is not working. And I guess the second line too.

Can you please help me how I can change the directory successfully based on the network drive name and then in$someEnv store for example if the network drive is X:



Thanks in advance.


Don’t you get errors? New-PSDrive does not have a parameter -Path. You have to provide a value for the parameter -Root. Please read the complete help to learn how to use it. And you sould not use ENV as a variable name as it is a reserved Powershell variable - About Environment Variables. And as you already have only one drive in your variable $drive you should not use ($drive)[0] as this cuts off the colon from your drive name. :wink:

Thanks Olaf,

Sorry my mistake with -Path. I was removing some things from the command because of privacy. This is the correct command:

$envPath = New-PSDrive -Name ($drive)[0] -PSProvider "FileSystem" -Root SomeNetworkPath

You are suggesting that I should structure it like this(without [0])?

$envPath = New-PSDrive -Name $drive -PSProvider "FileSystem" -Root SomeNetworkPath

What do you think about changing the directory like this:

cd $drive:
$someEnv = $drive + ":\include"

The thing is I am using Powershell and Jenkins and can’t test everything locally, but checking the output directly in Jenkins log.

P.S I am not using $ENV in my code, its just here for demonstration purposes. :slight_smile:

Sorry, my mistake. That’s actually right like you did it. But because your variable $drive already includes the colon your following commands should cause errors actually.

You are correct. I fixed that. Thank you.

One last question, how I should remove the created $drive at the end. What I am trying:

$someEnv = Remove-PSDrive -Name $drive

Here I think removing of the drive will fail because it will be for example “X:” instead of “X”.

Am I correct?


Why don’t you use the same syntax you used to create the mapped drive? :wink:

When you crosspost the same question at the same time to different forums you should at least post links to the other forums along with your question to avoid people willing to you help making their work twice or more.


I agree, even though the context of the two posts is different. The original post here is about the changing the directory and you helped a lot. I didn’t had much time that’s why I didn’t referenced this one on the stackoverwflow.

Thanks for your help and will do that in future.

Regards and keep up the good work. :slight_smile: