Sunday, January 30, 2011

Creating PSDrives for Modules

In my PowerShell training, I spend time examining modules and how you can use them to manage code and avoid profile bloat. In the (forgive the pun) modules on modules, I do lots of demos where being able to quickly set your location to the personal or system modules folder is useful. One simple way I demonstrate is to create PS drives pointing to the folders. I do this as follows:

# First, create variables pointing to each folder
$mod       = (ls env:psmodulepath).value.split(";")[0]
$sysmod    = (ls env:psmodulepath).value.split(";")[1]

# Now create PsDrives
New-PSDrive -name mod    -root $mod     –PsProvider FileSystem | out-null
New-PSdrive -name sysmod -root $sysmod  –PsProvider FileSystem | out-null

As you can see, I first create variables corresponding to the two built in Profile folders. The PsModulePath environment variable is set to a string holding the names of these folders, delimited by a semi-colon. Once I have the $mod and $sysmod variables, I can call New-PSDrive to create the drives. The last two PowerShell statements do return a value, so to to keep the output to a minimum, I just pipe the results to out-null (although I’ll quickly point out there are other ways to avoid the output!)

No comments: