Thursday, July 2, 2020

Stupid Citrix Trick #2: Mapping Drives With Powershell

Problem: Many systems need network drives mapped dynamically depending on group memberships, location, etc.  Powershell options are limited.

Solution: Me and mapped drives have a lot in common: we've both been around a long time, we both can be mighty useful, and we both can sometimes be a little awkward to deal with. Powershell, on the other hand, is a lot newer, is extremely useful, but unfortunately it ain't perfect, and when you're using it as a logon script you'll quickly discover its flaws.

There are two common ways to use this, which I'll refer to as "One Night Stand" and "Love You Forever".

One Night Stand

The usual method of mapping drives in Powershll is New-PSDrive.  A call to this function looks like this:

New-PSDrive -Name "F" -Root "\\Server\Share\Folder"

Very straightforward, you just provide the drive letter and the path that you want to assign to it.  However, this drive mapping only as long as the Powershell session is open.  If you're running Citrix virtual apps, the Powershell session will end around the time your app is opening.  So won't get us where we want to go. We need a long term commitment. We need...

Love You Forever

So you're tired of love that doesn't last, of fleeting kisses that feel like rain, of summer days that turn to autumn rains.  You're looking for a truly everlasting love.  Here you go:

New-PSDrive -Name "F" -Root "\\Server\Share\Folder" -Persist

But like the Gothic romance of a cursed vampire, this love will last forever.  Powershell sticks that mapped drive in your user profile, if you need to reuse it you'll need to explicitly delete it.  Why would you need to reuse it?  There are 26 letters after all!

Well, you may not believe this, but large organizations have an insatiable thirst for mapped drives, and since A through E are used for local drives, you're really only got 21.  If only there were some middle ground!

I don't guess it's a spoiler to say that there is.  Powershell is useful partly because you can use so many functions from other environments.  In this case we're going to use COM to create a VBScript Network object to do what we want.  Here's the code to get the object:

$VBSnet = New-Object -ComObject "WScript.Network"

Once this has been created you can call the MapNetworkDrive function like so:

$VBSnet.MapNetworkDrive("F:", "\\Otherserver\Thatshare\Thispath")

Et voila!

No comments:

Post a Comment