write-output - 文本引号之间的非线性变量

时间:2016-10-03 11:40:33

标签: powershell variables

我正在编写一个PowerShell文件,该文件创建一个批处理文件,其中包含带引号的文本之间的变量。

请参阅下面的脚本,以便了解我的意思。

$addnewcomputerhere = Read-Host -Prompt 'Input new computername'
$addnewusernamehere = Read-Host -Prompt 'Input new username'
Write-Output 'powershell -Command "(gc sourcechangeme.txt) -replace ''newcomputername'', '''$addnewcomputerhere'''| Out-File source1changeme.txt"' | Add-Content edittextdone.bat
Write-Output 'powershell -Command "(gc sourcechangeme.txt) -replace ''newusername'', '''$addnewusernamehere'''| Out-File source1changeme.txt"' | Add-Content edittextdone.bat

运行脚本edittextdone.bat应如下所示:

powershell -Command "(gc sourcechangeme.txt) -replace 'newcomputername', 'thecomputernamethathasbeengivenonprompt'| Out-File source1changeme.txt"
powershell -Command "(gc sourcechangeme.txt) -replace 'newusername', 'theusernamethathasbeengivenonprompt'| Out-File source1changeme.txt"

而不是它看起来像这样:

powershell -Command "(gc sourcechangeme.txt) -replace 'newcomputername', '
thecomputernamethathasbeengivenonprompt'| Out-File source1changeme.txt"
powershell -Command "(gc sourcechangeme.txt) -replace 'newusername', '
theusernamethathasbeengivenonprompt'| Out-File source1changeme.txt"

我的问题是变量开始换行。

我正在寻找任何建议并且没有运气this

我还阅读了-NoNewline,但无法弄清楚如何正确使用它。

1 个答案:

答案 0 :(得分:1)

不要依赖隐式字符串连接。使用format operator-f)将值插入输出字符串:

'powershell -Command "(gc sourcechangeme.txt) -replace ''newcomputername'', ''{0}''| Out-File source1changeme.txt"' -f $addnewcomputerhere | Add-Content edittextdone.bat
'powershell -Command "(gc sourcechangeme.txt) -replace ''newusername'', ''{0}''| Out-File source1changeme.txt"' -f $addnewusernamehere | Add-Content edittextdone.bat