String parameter fetches null value in PowerShell

Viewed 25

I have this function that is supposed to take a file and remove any comments or blank lines from it, however, I can't test it because I can't get it to pass the argument into the function for some reason.

function Remove-Comments {
    [Parameter(Mandatory=$true)]
    [String]$filePath

    Write-Output $filePath
    (Get-Content $filePath) | ForEach-Object { #Remove any comments that start the line or are lead by whitespace
        if($_ -like ' *#*') {
            $_ -replace ''
        }else{
            $_
        }
    } | Set-Content $filePath

    (Get-Content $filePath) | Where-Object {$_.trim() -ne ""} | Set-Content $filePath #Remove any lines that only include spaces
}

This is how I am calling the function:

Remove-Comments "C:\Users\#########\Desktop\Encryption Checker Datapack\data\custom_namespace\functions\load.mcfunction"

This is the file contents:

#
# load function
#

# load:
tellraw @a {"text":"Load function works!","color":"green"}

# function call:
execute if entity @a run function custom_namespace:check/function_call

# advancement:
advancement revoke @a only custom_namespace:this_is_an_advancement




#



# hella lines for test lol


# random command that doesn't do anythjing:
execute if block ~ ~ ~ air



# more dev notez
# more dev notez



And this is the error I receive:

Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\########\Desktop\DatapackFileEncrypter.ps1:54 char:18
+     (Get-Content $filePath) | Where-Object {$_.trim() -ne ""} | Set-C ...
+                  ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-Content], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
1 Answers

Your function definition is missing the param(...) block:

function Remove-Comments {
  param(  # All parameter declaration must be inside this block.
    [Parameter(Mandatory=$true)]
    [String]$filePath
  )
  $filePath
  # ...
}

It is unfortunate that no syntax error is reported for your code, even though a [Parameter()] attribute clearly only makes sense in the context of a param(...) block.

As for what happened due to the missing param(...) block:

  • Due to lack of a proper parameter declaration, your path argument passed on invocation did not bind to a parameter variable in your function.

  • In effect, the [Parameter()] attribute was ignored and [string] $filePath became a cast from - undefined (in the context of the function) - variable $filePath. An undefined variable defaults to $null, and casting $null to [string] becomes the empty string, which your function implicitly outputs.

  • $filePath - still undefined and therefore defaulting to $null - then caused Get-Content to report an error, because passing $null to the -Path parameter isn't allowed.

Related