[System.Object[]] doesn't contain a methodnamed 'replace'

后端 未结 3 1692
轻奢々
轻奢々 2021-01-15 01:51

The following is part of the file edit07.html:
From $array I\'m able to access the $empid = $user.employeeid and $seat = $user.Position<

相关标签:
3条回答
  • 2021-01-15 02:19

    Get-Content returns not a single string, but array of strings (split on new lines) and array itself doesn't have a replace method. You can turn it into a single string with -Raw parameter or call replace method on each string in the array.

    0 讨论(0)
  • 2021-01-15 02:22

    PowerShell v2 doesn't unroll arrays to call a method on each element of an array if the array object itself doesn't have that method. That feature was introduced with PowerShell v3. There are basically three ways to avoid this problem:

    • Upgrade to PowerShell v3 or newer. This is the preferred solution.

    • Read the file into a single string (as you have found out yourself). There are several ways to do this:

      $fileContent = Get-Content 'C:\path\to\your.html' | Out-String
      $fileContent = (Get-Content 'C:\path\to\your.html') -join "`r`n"
      $fileContent = [IO.File]::ReadAllText('C:\path\to\your.html')
      
    • Do the replacement for each line of the array Get-Content produces, e.g. like this:

      $search  = '...'
      $replace = '...'
      
      $fileContent = Get-Content 'C:\path\to\your.html'
      
      $fileContent -replace [regex]::Escape($search), $replace | Set-Content ...
      

      or like this:

      $search  = '...'
      $replace = '...'
      
      $fileContent = Get-Content 'C:\path\to\your.html'
      
      $fileContent | ForEach-Object { $_.Replace($search, $replace) } |
        Set-Content ...
      

      Note that the -replace operator does a regular expression match, so you need to escape special characters (like ?) in the search term (that's what [regex]::Escape() does). The .Replace() method does a simple string replacement, and thus doesn't require escaping.

    0 讨论(0)
  • 2021-01-15 02:33

    Changed

    $fileContent = Get-Content 'c:\temp\edit07.html'
    

    to

    $fileContent = [IO.file]::ReadAllText('c:\mgmt\schart\edit07.html')
    
    0 讨论(0)
提交回复
热议问题