【问题标题】:Powershell replace - how to avoid linebreaks at 80 charsPowershell 替换 - 如何避免 80 个字符的换行符
【发布时间】:2013-11-01 14:28:40
【问题描述】:

在一个批处理文件中,我需要在一个文件中使用脚本前面的变量值 (%tokenvar%) 更改 ##token## 的所有实例(只是我自己的占位符),并输出结果到一个文件。从这里的答案我想出了调用powershell:

type file.json|powershell -Command "$input|ForEach-Object{ $_ -replace \"##token##\", \"%tokenvar%\" }" > file.2.json

问题是生成的文件以 80 个字符包装,我不需要它!

我该怎么做?

【问题讨论】:

  • 您可以尝试通过管道连接到Out-String 并使用-Width <int> 参数吗?
  • 得到一个错误:Out-File : Cannot validate argument on parameter Encoding'。参数“filepath”不属于 ValidateSet 属性指定的集合“unicode,utf7,utf8,utf32,ascii,bigendianunicode,default,oem”。请提供集合中的参数,然后重试该命令。
  • 你会注意到,我尝试使用 Out-File,因为使用 Out-String 然后重定向输出会得到相同的 80 字符裁剪。
  • 您是否将-replace 的输出通过管道传输到Out-String?这对我有用"foo bar" -replace "bar", "baz" | out-string -width 120
  • ah - 发现重定向到文件 outside powershell 部分的问题。一旦我把它里面 一切都很好。类型 file.json|powershell -Command "$input|ForEach-Object{ $_ -replace \"##token##\", \"%tokenvar%\" } | Out-String -width 300 > file.2。 json"

标签: powershell batch-file command


【解决方案1】:

在这种情况下您不需要使用Out-String,因为Out-File 也有一个Width 参数:

... | Out-File File.2.json -Width 300"

只需确保 | Out-File ... 是 PowerShell 命令的一部分。

【讨论】:

    【解决方案2】:

    问题是PowerShell(>)中的重定向操作符会变成80个字符宽度的Out-File。您可以使用任意大宽度的 Out-File(我更喜欢 10k),或通过管道连接到 Set-Content(这会更慢)。您也可以将结果赋值给一个变量,然后使用 [IO.File]::WriteAllText 来执行更新。

    【讨论】:

      【解决方案3】:

      您可以直接在批处理文件中执行此操作,而无需 Powershell:

      @echo off
      setlocal DisableDelayedExpansion
      
      for /F "delims=" %%a in (file.json) do (
         set "line=%%a"
         setlocal EnableDelayedExpansion
         echo !line:##token##=%tokenvar%!
         endlocal
      )
      

      此批处理文件假定file.json 中没有空行,并且%tokenvar% 的值没有特殊的批处理字符。如果需要,这两点可以固定。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多