Troubleshooting PowerShell Functions

Part 1
Problem scenario:
  You have a PowerShell function that should add two parameter numbers and display their sum.  It is displaying the input when it should not.  No sum is being displayed.  There are no error messages. What should you do?
Solution:  Your code may look like this:

function contint ($a, $b) {
    $c = $a + $b
    return $c}

$d = contint (5, 2)
echo $d

The solution is to change the "$d = contint" line to be like this:
$d = contint 5 2
#With just spaces between the function name and its positional parameters, the PowerShell function will be invoked properly.

Part 2
Problem scenario:  You have a PowerShell function that is not working.  When you run the script that invokes it, you get an error like this:

"Select-String : Cannot bind argument to parameter 'Pattern' because it is null.
At C:\temp\contint1.ps1:2 char:34
+     $ca = cat $a | select-string $b
+                                  ~~
    + CategoryInfo          : InvalidData: (:) [Select-String], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SelectStr
   ingCommand"

Here is the function in the script:
function contint ($a, $b) {
    $ca = cat $a | select-string $b
    return $c}

$d = contint ('C:\temp\foo.txt', 'alphaString')
echo $d

Solution:  The solution is to call the function without parentheses and without the comma like this:
function contint ($a, $b) {
    $ca = cat $a | select-string $b
    return $ca}

$d = contint 'C:\temp\foo.txt' 'alphaString'
echo $d
#  The single quotes on the string arguments are optional. 
# There can be no commas between the arguments when calling the function.

Leave a comment

Your email address will not be published. Required fields are marked *