/errors/powershell/cannot-bind-argument-to-parameter-because-it-is-null
PowerShell: Cannot bind argument to parameter 'Path' because it is null.
- tool
- PowerShell
- exit code
- 1
- versions
- Windows PowerShell 5.1, PowerShell 7.x
- os
- windows, linux, macos
Cannot bind argument to parameter 'Path' because it is null. means you passed a variable to a parameter that does not accept $null (most mandatory parameters), and the variable was $null at that moment. The variant ... because it is an empty string. means it held ''. The parameter name in quotes tells you which argument was empty; find out why the variable has no value, usually a typo in its name or a lookup that found nothing.
Reproduce it
$ErrorActionPreference = 'Stop'
$file = 'notes.txt'
'hello' | Set-Content $file
try { Get-Content -Path $fiel } catch { $_.Exception.Message; ' -> ' + $_.FullyQualifiedErrorId }
try { Get-Content -Path '' } catch { $_.Exception.Message }
$latest = Get-ChildItem -Filter *.log | Select-Object -First 1
try { Remove-Item -Path $latest.FullName } catch { $_.Exception.Message }
Get-Content -Path $fileOutput
Cannot bind argument to parameter 'Path' because it is null. -> ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand Cannot bind argument to parameter 'Path' because it is an empty string. Cannot bind argument to parameter 'Path' because it is null. hello
$fiel is a typo, so it is undefined and therefore $null. $latest is $null because no .log file exists, and so is $latest.FullName.
Catch it earlier
Strict mode turns the typo into an error on the line that uses it:
Set-StrictMode -Version Latest
try { Get-Content -Path $fiel } catch { $_.Exception.Message }Output
The variable '$fiel' cannot be retrieved because it has not been set.
In your own functions and scripts, declare what you need so the caller gets a clear error:
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $Path
)With Mandatory, an interactive caller is prompted for the value; in a non-interactive run (powershell -NonInteractive, CI, scheduled tasks) a missing mandatory parameter is an error instead of a prompt.
Common sources of $null
| Code | Why it is null |
|---|---|
| $item = Get-ChildItem *.log | Select -First 1 | no file matched |
| $user.Mail | the property does not exist or the object is $null |
| $env:APP_CONFIG | the environment variable is not set in this process |
| param($Path) without Mandatory | the caller did not pass -Path |
| $result = SomeFunction | the function wrote nothing to the output (only Write-Host) |
Sources
- learn.microsoft.comlearn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parameters
- learn.microsoft.comlearn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null
- learn.microsoft.comlearn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters