使用“3”个参数调用 "Replace" 的 powershell 异常:“值不能为空

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

调用此函数时,出现调用空错误的异常。

代码:


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.

您收到此错误是因为在您的“$Env:TEMP”文件夹中没有任何内容与字符串 "hsperfdata".

匹配

在尝试替换字符之前确保 $hsPrefDataDirectories 不为空。