是否可以将PowerShell命令行拆分为多行?

在Visual Basic中,我可以在下一行中使用下划线(_)来继续命令。


当前回答

只要在这里加上一个极端情况。这可能会帮你节省5分钟。如果你使用一连串的动作,你需要在行末加上“。”,然后在“'”后面留下一个空格(反勾号)。这是我很不容易才发现的。

$yourString = "HELLO world! POWERSHELL!". `
                  Replace("HELLO", "Hello"). `
                  Replace("POWERSHELL", "Powershell")

其他回答

我刚刚发现,在后勾号和换行符之间一定没有任何字符。即使是空格也会导致命令不起作用。

在powershell中有很多方法来继续一行,用管道,括号,圆括号,操作符,点,甚至用逗号。这里有一个关于它的博客:https://get-powershellblog.blogspot.com/2017/07/bye-bye-backtick-natural-line.html

你也可以在foreach和if语句之后继续。

在windows终端(powershell配置文件),我可以简单地单击Shift-Enter对我来说很好。

PS C:\xxx2021> Get-ChildItem -Include *remote* -Recurse |
>> Sort-Object -Property LastWriteTime -Descending  |
>> Select-Object LastWriteTime, Name -First 25

LastWriteTime        Name
-------------        ----
12/5/2021 5:04:02 PM remote-control-car-BatteryPack-Number-2021-12-03.pdf

PS C:\xxx2021>enter code here
$scriptBlock = [Scriptblock]::Create(@'
  echo 'before'
  ipconfig /all
  echo 'after'
'@)

Invoke-Command -ComputerName AD01 -ScriptBlock $scriptBlock

源 不要使用反引号

我开始的时候

if ($true) {
"you can write multiple lines here, and the command doesn't run untill you close the bracket"

"like this"
}

最近我发现我可以

&{
get-date
"more stuff"
}