guini
guini

Reputation: 760

powershell script and subst command

I have the following powershell 2.0 script:

function getFreeDrive
{
    [char[]]$driveLetters = @([char]'E'..[char]'Z')
    foreach ($d in $driveLetters) {
        if(!(Test-Path -Path "$d`:" -IsValid)) {
            return $d
        }
    }
}

$drive = getFreeDrive

subst "$drive`:" T:\temp 
ls "$drive`:\"  # just a dummy command 
subst "$drive`:" /D

I want the script to

The script works fine, when I run it the first time. If I run the script a second time in the same shell, I get an error from the ls command saying that the drive can not be found. If I open a new shell and run the script, it runs fine again.

What is the problem with my script and how can I get the it to run multiple times in the same powershell instance?

Or maybe there is an alternative to the subst command? I tried using a powershell drive, but it doesn't work with other windows programs (e.g. devenv.exe).

Upvotes: 4

Views: 18028

Answers (3)

Tahir Hassan
Tahir Hassan

Reputation: 5817

I was having the exact same issue, and my workaround - note I am using version 3 - is to call Get-PSDrive before going into newly mapped drive:

$drive = getFreeDrive

subst "$drive`:" T:\temp 
Get-PSDrive | Out-Null
ls "$drive`:\"  # just a dummy command 
subst "$drive`:" /D

Upvotes: 2

HungryHippos
HungryHippos

Reputation: 1543

I can replicate the exact same behaviour as you, even to the point where in one Powershell window I can't even cd to the drive it's created, but if I open a brand new window I can cd to it just fine.

Behaviour seems like that outlined here:

http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/2e414f3c-98dd-4d8b-a3a3-88cfa0e7594c/

Workaround is probably to use PSDrives as mentioned above, or just don't map, then unmap, then try to remap the same drive in the same session.

Upvotes: 1

JPBlanc
JPBlanc

Reputation: 72610

An alternative is using PSProviders and more accuratly PSDrives (have a look to get-help about_providers) :

PS > New-PSDrive -Name "tr" -PSProvider filesystem -Root "c:\temp"

Name           Used (GB)     Free (GB) Provider      Root
----           ---------     --------- --------      ----
tr                               28,15 FileSystem    C:\temp

PS > ls tr:*.c

    Répertoire : C:\temp


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        01/08/2012     05:28        994 test.c


PS > Remove-PSDrive -Name "tr"

The trouble is that these drives can't be used with the shell explorer.exe.

Upvotes: 4

Related Questions