Using PowerShell Scripts as Commands (Part 2)

by Jan 31, 2023

Publishing on Feruary 2, 2023

In our previous tip we discussed a simple way to extend the PowerShell command set. By saving scripts in a folder that you add to the environment variable $env:path, PowerShell recognizes all scripts in this folder as new commands.

PowerShell scripts support the same mechanism for user parameters that you’d use for functions. Let’s take a look how you can add a new script-based command to your PowerShell that uses parameters.

Save the script below as “New-Password.ps1” to a folder named c:\myPsCommands. You may have to create the folder.

[CmdletBinding()]
param
(
    $CapitalLetter = 4,
    $Numeric = 1,
    $LowerLetter = 3,
    $Special = 2
)
   
$characters = & { 
    'ABCDEFGHKLMNPRSTUVWXYZ' -as [char[]] | 
    Get-Random -Count $CapitalLetter

    '23456789'.ToCharArray() | 
    Get-Random -Count $Numeric

    'abcdefghkmnprstuvwxyz'.ToCharArray() | 
    Get-Random -Count $LowerLetter

    '§$%&?=#*+-'.ToCharArray() | 
    Get-Random -Count $Special
    
} | Sort-Object -Property { Get-Random } 
$characters -join ''

Next, add the folder path to PowerShell’s command search path, for example by running this:

 
PS> $env:path += ";c:\myPSCommands" 
 

Now you can run any of the scripts that you stored in the folder just like regular commands. If the script features a param() block at its start, you can supply parameters, too. When you followed the example, you now have a command called New-Password that can generate complex passwords, and parameters help you compose the passwords:

 
PS> New-Password -CapitalLetter 2 -Numeric 1 -LowerLetter 8 -Special 2
yx+nKfph?M8rw
 


Tweet this Tip! Tweet this Tip!