Friday, August 14, 2015

Reorganize My Profile

As you may have guessed, I am testing a new PowerShell profile.  My old one had been around for a few years and was based in my knowledge and PowerShell's features at the time.  Here are the principles I am using for my new profile:
  • I'm organizing the functions I most often use into modules and leaving out special-purpose scripts. I'm putting all organization-related items in one module and trying to generalize all the other modules for sharing/publishing purposes. This includes using environment variables like $env:USERDNSDOMAIN
  • Instead of import statements or complicated ways to check for modules or elevated prompt, I am using Requires statements on each file (only one per file is allowed).  For more info, use  Get-Help about_requires
  • Since PowerShell 3, modules are loaded on-demand.  Any modules that show up in Get-Module -ListAvailable are included in this.  If a script or module requires a module that is available, then that module is imported automatically. 
  • To add a module to -ListAvailable, create a .PSM1 file and put it in Documents\WindowsPowerShell\Modules\modname, and the folder and PSM1 file names have to match.  I'm moving my modules here in this format.
  • Instead of typing the long path to my WindowsPowerShell folder, I created a PSDrive (map) called my:
    $null = New-PSDrive -Name my -Root (Split-Path -Path $PROFILE -Parent) -PSProvider FileSystem

So how do you organize your scripts? Leave a comment below!

Thursday, August 6, 2015

Test Profile

Want to test your new profile script without loading your existing one(s)?  Run this from the Run command:
powershell.exe /noexit /noprofile /file myfile.ps1

Here are some other parameters for powershell.exe
Find out more about profiles here.

Parameter Validation

To summarize Glenn Sizemore from the Scripting Guys blog, here is how you can validate your PowerShell parameters when you write your own script (requires V2):
Param(
[ValidateSet("Department", "AppData")][string]$type,
[ValidateRange(10, 25)][int]$size,
[ValidateScript({Test-connection $_ -count 2 -quiet})][string]$computername
)

And since version 3, the PowerShell ISE is smart enough (via Intellisense) to show you your choices in a drop-down for a ValidateSet parameter.