Home > OS >  PowerShell missing parameter hook
PowerShell missing parameter hook

Time:09-20

I have a mandatory InterfaceIndex parameter in my script.

When the parameter is not provided in command line PowerShell prompts for it but I would like to run Get-NetAdapter and display available interfaces before the prompt so that the user will know which value to select.

Is there a way to hook to missing parameter event or, at least, always run a command before parameters are parsed?

CodePudding user response:

This should do the trick:

Param (
  [Parameter(Mandatory=$False)]
    [Int] $NetIF
)
    If (0 -eq $NetIF) {
      Get-NetAdapter | 
        Select InterfaceIndex, InterfaceName |
        Format-Table
      $NetIF = Read-Host "Enter an InterfaceIndex"
    }

Note: If your parameter is other than Int, i.e. String adjust accordingly!

Output:

InterfaceIndex InterfaceName 
-------------- ------------- 
            19 ethernet_32777
            15 wireless_32768
            14 ethernet_32778
             6 ethernet_32768


Enter an InterfaceIndex: 
  • Related