【问题标题】:Insert newline in html format using Powershell使用 Powershell 以 html 格式插入换行符
【发布时间】:2015-06-30 22:54:32
【问题描述】:

我有具有
 的字符串值。我想用\n 替换它。当我在每一行到达另一行后将其转换为 html 格式时。但这不起作用。

$StdOut = 'total 40
drwxr-xr-x 3 root root 4096 Jun 16 14:55 .
drwxr-xr-x 5 root root 4096 Jun 16 14:54 ..
-rw------- 1 root root    0 Jun 16 14:55 cimserver_start.lock
srwxrwxrwx 1 root root    0 

6 月 16 日 14:55 cim.socket drwxr-xr-x 2 root root 4096 Jun 16 17:58 localauth -rw------- 1 根根 6 Jun 16 14:55 scx-cimd.pid '

$CResult = $StdOut -replace "
", "\n"

使用Convert-html后,我有这样的文字:

'total 40\ndrwxr-xr-x 3 root root 4096 Jun 16 14:55 .\ndrwxr-xr-x 5 root root 4096 Jun 16 14:54 ..\n-rw------- 1 root root    0 Jun 16 14:55 cimserver_start.lock\nsrwxrwxrwx 1 root root    0 Jun 16 14:55
 cim.socket\ndrwxr-xr-x 2 root root 4096 Jun 16 17:58 localauth\n-rw------- 1 root root    6 Jun 16 14:55 scx-cimd.pid\n

'

我该怎么做?

【问题讨论】:

  • \ 不是 PowerShell 中的字符转义序列,您应该使用反引号:"`n"

标签: powershell powershell-3.0


【解决方案1】:

Mathias 提到的方法适用于换行符。但是如果你有(或可能有)其他实体引用,那么我会使用 HtmlDecode 方法,例如

Add-Assembly System.Web
[System.Web.HttpUtility]::HtmlDecode($StdOut)

输出:

total 40
drwxr-xr-x 3 root root 4096 Jun 16 14:55 .
drwxr-xr-x 5 root root 4096 Jun 16 14:54 ..
-rw------- 1 root root    0 Jun 16 14:55 cimserver_start.lock
srwxrwxrwx 1 root root    0

【讨论】:

    【解决方案2】:
    PS C:\WINDOWS\system32> Add-Assembly System.Web
    Add-Assembly : The term 'Add-Assembly' is not recognized as the name of a   
    cmdlet, function, script file, or operable program. Check the spelling of 
    the name, or if 
    
    a path was included, verify that the path is correct and try again.
    At line:1 char:1
    + Add-Assembly System.Web
    + ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Add-Assembly:String) [],   
    CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
    

    【讨论】:

      【解决方案3】:

      试试这个

      $null = [Reflection.Assembly]::LoadWithPartialName('System.Web')
      [System.Web.HttpUtility]::HtmlDecode($StdOut)
      

      给我

      total 40
      drwxr-xr-x 3 root root 4096 Jun 16 14:55 .
      drwxr-xr-x 5 root root 4096 Jun 16 14:54 ..
      -rw------- 1 root root    0 Jun 16 14:55 cimserver_start.lock
      srwxrwxrwx 1 root root    0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-22
        • 2016-11-29
        • 1970-01-01
        • 1970-01-01
        • 2022-09-27
        • 1970-01-01
        相关资源
        最近更新 更多