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

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


当前回答

使用分号;分开命令 在任何反斜杠上替换双反斜杠\\。 使用“'传递安全地址到交换机命令,如“'PATH'”。

这个ps1命令安装地区pfx证书。

powershell -Command "$pfxPassword = ConvertTo-SecureString -String "12345678" -Force -AsPlainText ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\My -Password $pfxPassword ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\Root -Password $pfxPassword"

其他回答

这是一个老帖子,所以这是现代的方法。

如果您不使用遗留的powershell,那么延续行最干净的方法是在行开始处使用管道。

注意:该命令不会将某些行注释掉。这在命令行中非常有用。

> Get-ChildItem -path 'c:\' -Depth 1                 
    | Sort-Object LastWriteTime                       
    # | Sort-Object Length -Descending                   
    | Select-Object -First 3 -Skip 3                   
    | Foreach-Object {                                 
      $_.Name, $_.Length | Join-String -Separator ' = '                                                       
    }                                                  

输出:

explorer.exe = 4826160                                 
procexp.old.exe = 2925760                              
RtlExUpd.dll = 2839488                                 

Windows Powershell(版本< 6)

不幸的是,windows powershell不支持它。上面链接了一堆替代方案。你可以完全删除反勾号:2017/07/ byye - byye -backtick-natural-line

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

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

我开始的时候

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"
}

使用分号;分开命令 在任何反斜杠上替换双反斜杠\\。 使用“'传递安全地址到交换机命令,如“'PATH'”。

这个ps1命令安装地区pfx证书。

powershell -Command "$pfxPassword = ConvertTo-SecureString -String "12345678" -Force -AsPlainText ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\My -Password $pfxPassword ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\Root -Password $pfxPassword"

如果你想把字符串分成多行,你可以使用“+”。例如:

$header =    "Make," +

             "ComputerName," +

             "Model," +

             "Windows Version"

看起来就像:

$header = "Make,ComputerName,Model,Windows Version"