Using PowerShell Scripts as Commands (Part 1)

by Jan 31, 2023

One very simple way of extending PowerShell commands are scripts. To turn a script into a command, pick a folder and store the PowerShell script in this folder. The name of your script will later turn into a command name.

For example, take the script below and save it with name “New-Password” in a folder:

$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 ''

The script produces a complex random password, and you can control the composition with the variables at top.

To use the script as a new command, make sure PowerShell includes the folder where you saved the script in its search for command. Let’s assume you store your scripts in a folder named “c:\myPsCommands”. Then running the code below will add the folder to the command search path:

$env:path += ";c:\myPsCommands"

Once you make this adjustment, you can now run your script simply by entering the “command” name New-Password. Essentially, the script name turns into an executable command name.

Tweet this Tip! Tweet this Tip!