powershell-3.0

powershell Exception calling "Replace" with "3" argument(s): "Value cannot be null


While calling this function, I get the exception calling null error.

Code:


if(Test-Path($Env:TEMP))  {

    $hsPrefDataDirectories = Get-ChildItem "$Env:TEMP" | where {$_.Name -match "hsperfdata"} | Format-Table name -hideTableHeaders | Out-String -stream    
    $hsPrefDataDirectories = [regex]::Replace($hsPrefDataDirectories, "^\s+", '')
    $hsPrefDataDirectories = [regex]::Replace($hsPrefDataDirectories, "\s+", ',')
    $hsPrefDataDirectories = [regex]::Replace($hsPrefDataDirectories, ",$", '')
    $hsPrefDataDirectories = $hsPrefDataDirectories.split(",")
    .....
    $hsPrefDataDirectories = $hsPrefDataDirectories.split(",")

Error: 

Exception calling "Replace" with "3" argument(s): "Value cannot be null.
Parameter name: input"

...

You cannot call a method on a null-valued expression.

Solution

  • You get this error because in your "$Env:TEMP" folder nothing matches the string "hsperfdata".

    Make sure the $hsPrefDataDirectories is not null before trying to replace characters.