5 powershell newline string-interpolation
我有一个在Powershell中运行的脚本,并且我希望能够在脚本名称和脚本内容本身之间的结果文本文件输出中添加一行。
当前,从下面开始,这$str_msg = $file,[System.IO.File]::ReadAllText($file.FullName)是我需要的行,但是我需要一行来分隔$file和下一个表达式的结果。我怎样才能做到这一点?
foreach ($file in [System.IO.Directory]::GetFiles($sqldir,"*.sql",
[System.IO.SearchOption]::AllDirectories))
{
$file = [System.IO.FileInfo]::new($file);
$Log.SetLogDir("");
$str_msg = $file,[System.IO.File]::ReadAllText($file.FullName);
$Log.AddMsg($str_msg);
Write-Output $str_msg;
# ...
}
Run Code Online (Sandbox Code Playgroud)
$str_msg = $file,[System.IO.File]::ReadAllText($file.FullName)不创建string,它创建一个 2 元素数组( [object[]]),由$file [System.IO.FileInfo]实例和包含该文件内容的字符串组成。
据推测,该.AddMsg()方法需要单个字符串,因此 PowerShell将数组字符串化以将其转换为单个字符串;默认情况下,PowerShell 通过使用单个空格作为分隔符连接元素来对数组进行字符串化;例如:
[string] (1, 2)产量'1 2'。
因此,这是最好的组合$str_msg为一个字符串,首先,有一个明确的换行符作为分隔符,如:
$strMsg = "$file`r`n$([System.IO.File]::ReadAllText($file.FullName))"
Run Code Online (Sandbox Code Playgroud)
请注意使用转义序列"`r`n"生成 CRLF,Windows 特定的换行序列;在类 Unix 平台上,您只需使用"`n"(LF)。
.NET 提供了一个跨平台抽象,[Environment]::NewLine,它返回适合平台的换行序列(您也可以将其嵌入到$([Environment]::NewLine)inside 中"...")。
字符串插值的替代方法是使用-f基于 .NETString.Format()方法的字符串格式化运算符:
$strMsg = '{0}{1}{2}' -f $file,
[Environment]::NewLine,
[System.IO.File]::ReadAllText($file.FullName)
Run Code Online (Sandbox Code Playgroud)
为第一个答案干杯
Backtick-r+backtick-n 将在 PS 中用新行进行回车。您可以将 $file 变量的 Get-Content 作为新的数组变量执行,并在特定索引处插入回车:
示例文件:test123.txt
如果文件内容是这样的:
line1
line2
line3
Run Code Online (Sandbox Code Playgroud)
将内容存储在数组变量中,以便您拥有索引
[Array]$fileContent = Get-Content C:\path\to\test123.txt
Run Code Online (Sandbox Code Playgroud)
在第 2 行和第 3 行之间添加回车:
$fileContent2 = $fileContent[0..1] + "`r`n" + $fileContent[2]
Run Code Online (Sandbox Code Playgroud)
然后输出一个新文件:
$fileContent2 | Out-File -FilePath C:\path\to\newfile.txt
Run Code Online (Sandbox Code Playgroud)
希望这种替代方法可以帮助未来的答案寻求者
小智 1
您需要使用回车符powershell特殊字符,即“`r”。
像这样使用它在您的行中添加回车符:
$str_msg = $file,"`r",[System.IO.File]::ReadAllText($file.FullName);
Run Code Online (Sandbox Code Playgroud)
查看此文档以了解有关 Poewershell 特殊字符的更多详细信息。
| 归档时间: |
|
| 查看次数: |
9619 次 |
| 最近记录: |