How to pass optional parameters in PowerShell? -


this wrapper function invoke-webrequest (i have removed lot of functionality keep noise down)

function invoke-serverapi($apifolder, $admincredentials, [validateset("get","post","put","delete")]  $httpmethod, $contenttype, $body, $verbose) {     $resp1httpcode= 'not set'     try     {         if ( ($httpmethod -eq 'get') -or ($httpmethod -eq 'delete'))         {             $resp1 = invoke-webrequest -uri $apifolder -method $httpmethod -credential $admincredentials -contenttype $contenttype -erroraction silentlycontinue -verbose:$verbose         }         else         {             $resp1 = invoke-webrequest -uri $apifolder -body $body -method $httpmethod -credential $admincredentials -contenttype $contenttype -erroraction silentlycontinue -verbose:$verbose         }         $resp1httpcode = $resp1.statuscode      }     catch [exception]     {         $resp1httpcode = $_.exception.response.statuscode.value__      }      return $resp1httpcode } 

i need pass -body parameter on verb post , put don't pass in , delete. managed if/else.

is there better way achieve in powershell did in switch parameter -verbose?

yes, involves forming hashtable parameters , using instead or in addition of parameter list, aka splatting. in case, this:

try {     $ifbody=@{}     if ( ($httpmethod -eq 'put') -or ($httpmethod -eq 'post'))     {         $ifbody."body"=$body     }     $resp1 = invoke-webrequest -uri $apifolder @ifbody -method $httpmethod -credential $admincredentials -contenttype $contenttype -erroraction silentlycontinue -verbose:$verbose      $resp1httpcode = $resp1.statuscode  } 

the @ifbody reverts hashtable -key=value -key2=value2... sequence of parameters cmdlet or function.


Comments