ExcellentSP
ExcellentSP

Reputation: 1619

How do we get a drive by its label in PowerShell 5.0?

I have an autorun.inf file with the following contents on my external hard drive:

[Autorun]
Label=MasterSword

This labels my external hard drive once it's plugged in as, MasterSword. I want to store a few scripts on it and include them in my $profile so they are loaded when PowerShell starts or when the profile is re-included (. $profile) at the interpreter.

As many know, using a hard-coded drive letter for external drives can lead to changing the reference to those external hard drive scripts every time the drive letter changes, resulting in the inclusion failing.

So I guess I have two questions:

  1. How do I get a hold of the drive label that was set in the autorun.inf?

  2. How do I translate that drive label into the drive letter so I can reference the scripts stored on it?

Upvotes: 8

Views: 15800

Answers (3)

ExcellentSP
ExcellentSP

Reputation: 1619

I did a little more research and came up with this little snippet:

To answer #1:

$scriptDrive = Get-Volume -FileSystemLabel MasterSword

To answer #2:

$scriptDriveLetter = $scriptDrive.DriveLetter

And together, they would be:

$scriptDrive = Get-Volume -FileSystemLabel MasterSword
$scriptDriveLetter = $scriptDrive.DriveLetter

Or for another interpretation:

$scriptDriveLetter = (Get-Volume -FileSystemLabel MasterSword).DriveLetter

Where the necessary drive letter is stored in $scriptDriveLetter.

Upvotes: 12

bkr009
bkr009

Reputation: 65

Here's a modification to ExcellentSP's answer that I used for my own use.

I have the script look for the plugged in usb by name and change the drive letter to a pre-determined drive letter:

$scriptDrive = Get-Volume -FileSystemLabel "mastersword"
Get-Partition -DriveLetter ($scriptDrive.DriveLetter) | Set-Partition -NewDriveLetter W

You can replace -DriveLetter with -DriveNumber as well dependent on your use.

But this was only because I was being lazy and didn't want to do much modifying my old script.

Most likely, the best way to do it is:

$scriptDrive = Get-Volume -FileSystemLabel "mastersword"
$drive = $scriptDrive.DriveLetter

You would then use $drive for any pathways or directories within this drive. ex: $drive:\folder\picture.jpg

Upvotes: 0

MisterSeajay
MisterSeajay

Reputation: 4689

You could try:

Get-PSDrive | Where-Object {$_.Description -eq "MasterSword"}

This will return an object such as:

Name            : E
Description     : MasterSword
Provider        : Microsoft.PowerShell.Core\FileSystem
Root            : E:\
CurrentLocation : Scripts

Thus, assuming your scripts are in the "Scripts" folder, you can find them with:

$Root = (Get-PSDrive | Where-Object {$_.Description -eq "MasterSword"}).Root
$Path = Join-Path $Root "Scripts"

Upvotes: 4

Related Questions