Remove-Item: Cannot Bind Argument to Parameter 'Path' Because It Is Null

Remove-Item: Cannot Bind Argument to Parameter 'Path' Because It Is Null

Good Afternoon

I have created the following powershell

function script{
    param (
        [string]$path = {"C:\PowerShellTest\Med Rec\1\", "C:\PowerShellTest\Med Rec\2\", "C:\PowerShellTest\Med Rec\3\"}
        )
    }

Get-ChildItem $path -Recurse | Select-Object Directory,Name,CreationTime | Export-Csv "C:\PowerShellTest\Med Rec\text.csv" -Force -NoTypeInformation

Remove-Item -Recurse -Path $path 

when I run it I receive the following error

Remove-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\PowerShellTest\New folder\Content Deleted Daily at 1AM.ps1:9 char:28
+ Remove-Item -Recurse -Path $path
+                            ~~~~~
    + CategoryInfo          : InvalidData: (:) [Remove-Item], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand

I'm unable to figure out why its not working.

2 Answers

Your $path variable is outside of the scope of where Remove-Item is called.

Have a look at this example:

function script{
    $path = "hello";
    echo $path;
}
echo $path;

When echo $path is called on the last line, nothing is outputted because there has been no value placed in $path. However if I call script then hello is outputted, but as soon as that script function is done running the $path variable inside of the function will not be accessible any more.

To fix, define your $path variable where the Remove-Item has access to it, for example before the script function.

To see more on scope in Powershell here is Microsoft's full documentation.

I fixed it up by just creating an alias (I hope its the correct term).

$path = "C:\PowerShellTest\MedRec\1\", "C:\PowerShellTest\MedRec\2\", "C:\PowerShellTest\MedRec\3\"

Get-ChildItem $path -Recurse | Select-Object Name,CreationTime | Export-Csv "C:\PowerShellTest\MedRec\text.csv" -Force -NoTypeInformation

Get-ChildItem $path -Recurse | Remove-Item -Recurse -Force

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.