Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I customise the 'not recognized as the name of a cmdlet' error in Powershell?

Say I make a typo on the command line:

whih foo

Powershell returns:

whih : The term 'whih' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ whih mocha
+ ~~~~
+ CategoryInfo          : ObjectNotFound: (whih:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

The long message is useful for scripts, but for interactive shell use, I'd like to wrap it with something shorter, like:

'whih' isn't a cmdlet, function, script file, or operable program.

Can I wrap the error and change it to something shorter?

like image 861
mikemaccana Avatar asked Aug 02 '18 14:08

mikemaccana


People also ask

How do you fix the term is not recognized as the name of a cmdlet?

By default, you have to install modules in the exact order to use them. If that module is missing, corrupt, or got moved, it throws up the error, “the term is not recognized as the name of a cmdlet.” You can use “get-module” in PowerShell to see if the module is present and correct.

Can you create your own aliases for cmdlets in PowerShell?

You can create an alias for a cmdlet, such as Set-Location . You cannot create an alias for a command with parameters and values, such as Set-Location -Path C:\Windows\System32 . To create an alias for a command, create a function that includes the command, and then create an alias to the function.

Which the term which is not recognized as the name of a cmdlet function script file?

The term 'Select-Object-Property' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.


1 Answers

Yes, you can intercept the CommandNotFoundException with a CommandNotFoundAction!

$ExecutionContext.InvokeCommand.CommandNotFoundAction = {
  param($Name,[System.Management.Automation.CommandLookupEventArgs]$CommandLookupArgs)  

  # Check if command was directly invoked by user
  # For a command invoked by a running script, CommandOrigin would be `Internal`
  if($CommandLookupArgs.CommandOrigin -eq 'Runspace'){
    # Assign a new action scriptblock, close over $Name from this scope 
    $CommandLookupArgs.CommandScriptBlock = {
      Write-Warning "'$Name' isn't a cmdlet, function, script file, or operable program."
    }.GetNewClosure()
  }
}
like image 103
Mathias R. Jessen Avatar answered Oct 24 '22 01:10

Mathias R. Jessen