Powershell script and subst command

I have the following permissions: 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 a script

  • find the first unused drive letter
  • create a new disk using subst
  • do something on this disc.
  • delete the disk with subst

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 message from the ls command saying that the drive was not found. If I open a new shell and run the script, it works fine again.

What is the problem with my script and how can I make it work several times in the same powershell instance?

Or maybe there is an alternative to subst ? I tried using the powershell drive, but it does not work with other Windows programs (for example, devenv.exe).

+4
source share
3 answers

I can replicate the same behavior as you, even until the moment when in one Powershell window I can’t even burn a CD to the created disc, but if I open a completely new window, I can handle it just fine.

The behavior is as shown here:

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

The workaround is probably to use PSDrive, as mentioned above, or just not display, then turn it off and then try to reassign the same drive in the same session.

+1
source

An alternative is to use PSProviders and more specifically PSDrives (see 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 problem is that these disks cannot be used with the explorer.exe shell.

+3
source

I had the same problem and my workaround - note that I am using version 3 - is calling Get-PSDrive before moving to a newly connected drive:

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

All Articles