PowerShell / PowerShell/PSScriptAnalyzer
PSPossibleIncorrectComparisonWithNull fails to work with typecasted variables
Nobody has claimed this yet.
- Dominant language
- C#
- Stars
- 2.2k
- Forks
- 414
- Avg merge
- 13h 1m
- Merged PRs (30d)
- 2
Description
Steps to reproduce
If you validate this script, it complains about PSPossibleIncorrectComparisonWithNull even though it is pretty clear $value must be a string.
Function Get-FooBar() {
return "foobar"
}
[string]$value = (Get-FooBar)
if ($value -eq $null) {
Write-Output 'value is $null'
} else {
Write-Output 'value is not $null'
}
Expected behavior
It works perfectly fine if the value is type-casted like this:
Function Get-FooBar() {
return "foobar"
}
$value = (Get-FooBar) -as [string]
if ($value -eq $null) {
Write-Output 'value is $null'
} else {
Write-Output 'value is not $null'
}
Actual behavior
So we get this error needlessly.
ERROR: test.ps1:9:5: PSPossibleIncorrectComparisonWithNull $null should be on the left side of equality comparisons.
Environment data
> $PSVersionTable
Name Value
---- -----
PSVersion 6.0.2
PSEdition Core
GitCommitId v6.0.2
OS Linux 4.15.10-1.el7.elrepo.x86_64 #1 SMP Thu Mar 15 10:05:52 EDT 2018
Platform Unix
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
> (Get-Module -ListAvailable PSScriptAnalyzer).Version | ForEach-Object { $_.ToString() }
1.16.1
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the PSPossibleIncorrectComparisonWithNull rule and reproduce the warning using the first PowerShell script, then compare it with the -as [string] example. Trace the rule's handling of explicitly typecast variables and add or update coverage so the warning is not emitted for the demonstrated safe comparison while existing cases remain covered.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- powershell
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 48/100