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

后端 未结 3 1699
轻奢々
轻奢々 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: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.

提交回复
热议问题