I have a Powershell function that wraps Invoke-WebRequest. Depending on the value of parameter $verbose I want to use -Verbose or not.
The code I have wrote using an API does the work... but I feel there should be a better way with less lines of code. It feels wrong to have twice the line with the Invoke-WebRequest
So my question is: Is there a best way in Powershell to deal with switch parameters?
Here is the function:
function Invoke-MarkLogicManagementAPI($server, $apiFolder, $adminCredentials, $HTTPmethod, $body, $verbose)
{
$resp1HTTPCode= "Not set"
try
{
$uri = "http://$($server):8002/manage/v2/$apiFolder"
if ($verbose -eq $true)
{
$resp1 = Invoke-WebRequest -Uri $uri -Body $body -Method "$HTTPmethod" -Credential $adminCredentials -ContentType "application/json" -ErrorAction SilentlyContinue -Verbose
}
else
{
$resp1 = Invoke-WebRequest -Uri $uri -Body $body -Method "$HTTPmethod" -Credential $adminCredentials -ContentType "application/json" -ErrorAction SilentlyContinue
}
$resp1HTTPCode = $resp1.StatusCode
}
catch [Exception]
{
$resp1HTTPCode = $_.Exception.Response.StatusCode.Value__
}
return $resp1HTTPCode
}
Yes, you can pass a boolean to a switch parameter. In your case:
example: