Tuesday, August 21, 2018

Using Powershell as a command / alias runner

I've been using powershell as a command runner for quite awhile.  Any time I want to automate something, I can write a powershell function (or a group of functions in a separate script file), add it to my profile, and it'll be available in any powershell command window.  I even get added benefits such as function completion.  I've named several functions beginning with "csm" and when I type csm + ctrl enter I get this:



To get this working, you must first create a profile:
  • At the powershell command prompt, run Test-Path $Profile.  If the result is true, then you have created a profile.  To see the path to your profile, just type $Profile.
  • If the result is false, run this command to create a profile:
    • New-Item -Path $Profile -Type File -Force.
  • I've no idea how to create it an a location you desire (I back mine up in place), but this will create a file like: C:\Users\[you]\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
  • Open your profile in the Powershell ISE.  Create functions to your heart's desire.  Of course you have access to all of powershell's built in commands as well.
  • If you get an error saying you can't run scripts, run this command: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned  More info here.
You will need to keep the concept of "dot raising" in mind.  This is a security measure, I believe.  So to launch an executable, you will need to write your function like this:

function start-git
{
    Set-Location C:\Dev
    . "C:\Program Files\Git\bin\bash.exe" #note the dot
}

If you want to pass parameters into your function, you can do that like:

function compare-files([string]$s1, [string]$s2)
{
    . "C:\Program Files (x86)\WinMerge\WinMergeU.exe" $s1 $s2
}

If you want to group related functions in a separate script, you reference it like this:
#########  WhateverFunctions.psm1
function whatever {}
Export-ModuleMember -function whatever
########## profile
Import-Module C:\WhateverFunctions.psm1

No comments: