Home > database >  Powershell Profile to append parameters to a certain command
Powershell Profile to append parameters to a certain command

Time:09-16

I have a certain command that I want to be able to append a parameter to as a powershell profile function. Though I'm not quite sure the best way to be able to capture each time this command is run, any insight would be helpful.

Command: terraform plan

Each time a plan is run I want to be able to check the parameters and see if -lock=true is passed in and if not then append -lock=false to it. Is there a suitable way to capture when this command is run, without just creating a whole new function that builds that command? So far the only way I've seen to capture commands is with Start-Transcript but that doesn't quite get me to where I need.

CodePudding user response:

The simplest approach is to create a wrapper function that analyzes its arguments and adds -lock=false as needed before calling the terraform utility.

function terraform {
  $passThruArgs = $args
  if (-not ($passThruArgs -match '^-lock=')) { $passThruArgs  = '-lock=false'}
  & (Get-Command -Type Application terraform) $passThruArgs
}

The above uses the same name as the utility, effectively shadowing the latter, as is your intent.

However, I would caution against using the same name for the wrapper function, as it can make it hard to understand what's going on.

Also, if defined globally via $PROFILE or interactively, any unsuspecting code run in the same session will call the wrapper function, unless an explicit path or the shown Get-Command technique is used.

CodePudding user response:

Not to take away from the other answer posted, but to offer an alternative solution here's my take:

$Global:CMDLETCounter = 0
$ExecutionContext.InvokeCommand.PreCommandLookupAction = {
    Param($CommandName, $CommandLookupEvents)
    if ($CommandName -eq 'terraform' -and $Global:CMDLETCounter -eq 0)
    {
        $Global:CMDLETCounter  
        $CommandLookupEvents.CommandScriptBlock = {
            if ($Global:CMDLETCounter -eq 1) 
            { 
                if ($args -notmatch ($newArg = '-lock='))
                {
                    $args  = "${newArg}true"
                }
            }
            & "terraform" @args
            $Global:CMDLETCounter--
        }
    }
}

You can make use of the $ExecutionContext automatic variable to tap into PowerShells parser and insert your own logic for a specific expression. In your case, youd be using terraform which the command input will be parsed for each token and checked against -lock= in the existing arguments. If not found, append -lock=true to the current arguments and execute the command again.

The counter you see ($Global:CMDLETCounter) is to prevent an endless loop as it would just recursively call itself without there being something to halt it.

  • Related