繁体   English   中英

将新行从命令行传递到 PowerShell

[英]Passing new line from command line to PowerShell

如何从命令行向 PowerShell 传递换行符?

// MyScript.ps1:
[CmdletBinding()]
Param(
    [Parameter()] $Param
)

Write-Host $Param

// Command line (not PowerShell - cmd.exe!)
powershell.exe -File MyScript.ps1 -Param "First`nSecond"

不起作用。 同样使用命令行的换行符\n也不起作用。 那么如何向命令行传递一个新行呢?

解决方法是使用任何其他字符,例如命令行中的\\n ,并在PowerShell中替换它:

$x = $param.Replace("\n", "`n")

然而,这是有效的,它当然是一个黑客,而不是我的首选解决方案。

First Line◙Second Line有一个特殊字符。

当使用变量从 CMD 调用时,我必须将参数作为文字传递(使用'而不是" )。

样本pstest.ps1

Write-Host "Without Replace:"
Write-Host $args[0]

Write-Host #Blank Space for Readability
Write-Host "With Replace:"
Write-Host $args[0].Replace("\n", "`n")

从 CMD 拨打,结果:

> set "tmpvar=blar1 de \nblar2"
> powershell.exe .\pstest.ps1 '%tmpvar%'

Without Replace:
blar1 de \nblar2

With Replace:
blar1 de
blar2

您需要回车和换行:

`r`n

所以这应该工作:

powershell.exe -File MyScript.ps1 -Param "First`r`nSecond"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM