powershell - 写输出-文本引号之间的nonewline变量

标签 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的信息,但无法弄清楚如何正确使用它。

最佳答案

不要依赖隐式字符串连接。使用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

关于powershell - 写输出-文本引号之间的nonewline变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39830743/

相关文章:

variables - 无法编译::I don't understand my errors. MoSTLy the “declared as void” errors and “StudentType was not declared in this scope” .

javascript - 是否可以将 id 名称分配给变量并在 javascript 的函数中使用它

powershell - Windows 7/PS2.0 New-Object System.Drawing.Text.PrivateFontCollection不起作用,但在Windows 10中确实起作用

sql-server-2008 - Powershell 静默/无人值守安装 sql server 2008

Powershell [System.Windows.Forms.SendKeys],发送shift+windowsKey+rightArrow组合

javascript - 如何将变量值分配为哈希中的变量名?

swift - 如何从字符串创建变量?

powershell - 使用每行的第一个单词作为变量

powershell - 查找并运行文件

linux - 找不到 ssh 环境变量 bash 命令