2

I have a lot of powershell scripts so I created a custom logging Powershell module with a couple of cmdlets. The problem is that we have had trouble getting all of the users to download and put the custom module in their PSModulePath.

Ideally I'd like the script to continue silently and not show any errors if the cmdlet cannot be found, but I haven't found a good way to do it. Right now we get messages like this:

C:> foo-bar
foo-bar : The term 'foo-bar' is not recognized as the name of a cmdlet, function, script file, or operable program...

Setting ErrorActionPreference will suppress the message, but it also suppresses all other error messages which isn't desirable.

I could write a custom function in every script that checks to see if the module is loading before calling the custom cmdlets, but it seems like there should be a better way to do it.

StaticMethod
  • 593
  • 1
  • 7
  • 20
  • Even though there can be points in handling scenarios like this, I can't help but feel that this is being approached from the wrong angle, especially if this is in an enterprise environment. You can adjust the original scripts to include this new logging feature and have the users successfully update these but not get the logging related cmdlets distributed? Maybe I'm missing something here. – notjustme Jun 07 '17 at 06:13
  • Why do you want the script to continue if it cannot successfully run some commands? – henrycarteruk Jun 07 '17 at 09:19
  • This question confirms [my thoughts](https://stackoverflow.com/questions/41860911/powershell-with-exchange-how-do-i-append-all-verbose-output-to-a-file/44265303#44265303) that there is a desire to have a (better) native logging in scripting languages like PowerShell – iRon Jun 07 '17 at 10:08

2 Answers2

5

For a given cmdlet foo-bar, you can do the following, once, at the beginning of the script:

if (-not (Get-Command foo-bar -ErrorAction Ignore)) {
  # Define a dummy function that will be a no-op when invoked.
  function foo-bar { }
}

All subsequent calls to foo-bar then either call the actual cmdlet, if available, or the dummy function, resulting in a quiet no-op.

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

You can use try/catch in a different way to suppress that. Since it is not a cmdlet, -erroraction won't work directly. So you can try like this:

try
{
    foo-bar
}
catch [Management.Automation.RuntimeException]
{

}
Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45