asgerhallas
asgerhallas

Reputation: 17724

Set location to newly mounted disk image fails in PowerShell

I'm trying to run the following code in a function in my script:

$result = Mount-DiskImage -ImagePath $imagepath -PassThru
$driveLetter = ($result | Get-Volume).DriveLetter
Set-Location "$($driveLetter):"

But it constantly fails with this error:

  Set-Location : Cannot find drive. A drive with the name 'G' does not exist.
  At C:\Users\Agent\BuildAgent\scripts\helpers.psm1:35 char:3
  +   Set-Location "$($driveLetter):"
  +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (G:String) [Set-Location], DriveNotFoundException
      + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

But after the script has terminated I can change the drive, no problem.

It might be timing related, but injecting a sleep (even a large one) before setting location, does not help.

Does anyone know about this issue?

Upvotes: 1

Views: 1574

Answers (2)

Vimes
Vimes

Reputation: 11947

Let's all up-vote the bug report.

Then, I think I have a workaround by manually adding the drive as a new PSDrive. I guess the New-PSDrive cmdlet can access the mounted drive even though others can't.

$mount = Mount-DiskImage $isoPath -PassThru
$driveLetter = ($mount | Get-Volume).DriveLetter

# Have to use New-PSDrive so other cmdlets in this session can see the new drive
New-PSDrive -Name $driveLetter -PSProvider FileSystem -Root "$($driveLetter):\"

// ...do things...

Dismount-DiskImage $mount.ImagePath

Upvotes: 3

Sean Rhone
Sean Rhone

Reputation: 268

I can't try this but your command looks odd to me Set-Location "$($driveLetter):"

have you tried Set-Location "$driveLetter:"

without the parens

Upvotes: 0

Related Questions