如何从 PowerShell 脚本打开另一个 PowerShell 控制台

Jim*_*Jim 5 macos terminal powershell powershell-core

在 OSX 中,我打开 bash 终端并进入 PowerShell 控制台。在我的 PowerShell 脚本中,我想打开另一个 PowerShell 控制台并在那里执行 PowerShell 脚本。

在Windows下,我会做

Invoke-Expression ('cmd /c start powershell -Command test.ps1')
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 OSX 中做同样的事情?

mkl*_*nt0 1

在 macOS 上的新终端窗口中启动 PowerShell 实例


无法向其传递参数

PS> open -a Terminal $PSHOME/powershell
Run Code Online (Sandbox Code Playgroud)

如果你想运行给定的命令

不幸的是,如果您想传递一个命令在新的 PowerShell 实例中运行,则需要做更多的工作:
本质上,您需要将命令放置在通过 shebang 调用的临时、自删除、可执行 shell 脚本中线:

注意:请确保至少运行PowerShell Core v6.0.0-beta.6才能正常工作。

Function Start-InNewWindowMacOS {
  param(
     [Parameter(Mandatory)] [ScriptBlock] $ScriptBlock,
     [Switch] $NoProfile,
     [Switch] $NoExit
  )

  # Construct the shebang line 
  $shebangLine = '#!/usr/bin/env powershell'
  # Add options, if specified:
  # As an aside: Fundamentally, this wouldn't work on Linux, where
  # the shebang line only supports *1* argument, which is `powershell` in this case.
  if ($NoExit) { $shebangLine += ' -NoExit' }
  if ($NoProfile) { $shebangLine += ' -NoProfile' }

  # Create a temporary script file
  $tmpScript = New-TemporaryFile

  # Add the shebang line, the self-deletion code, and the script-block code.
  # Note: 
  #      * The self-deletion code assumes that the script was read *as a whole*
  #        on execution, which assumes that it is reasonably small.
  #        Ideally, the self-deletion code would use 
  #        'Remove-Item -LiteralPath $PSCommandPath`, but, 
  #        as of PowerShell Core v6.0.0-beta.6, this doesn't work due to a bug 
  #        - see https://github.com/PowerShell/PowerShell/issues/4217
  #      * UTF8 encoding is desired, but -Encoding utf8, regrettably, creates
  #        a file with BOM. For now, use ASCII.
  #        Once v6 is released, BOM-less UTF8 will be the *default*, in which
  #        case you'll be able to use `> $tmpScript` instead.
  $shebangLine, "Remove-Item -LiteralPath '$tmpScript'", $ScriptBlock.ToString() | 
    Set-Content -Encoding Ascii -LiteralPath $tmpScript

  # Make the script file executable.
  chmod +x $tmpScript

  # Invoke it in a new terminal window via `open -a Terminal`
  # Note that `open` is a macOS-specific utility.
  open -a Terminal -- $tmpScript

}
Run Code Online (Sandbox Code Playgroud)

定义此函数后,您可以使用给定命令(指定为脚本块)调用 PowerShell,如下所示:

# Sample invocation
Start-InNewWindowMacOS -NoExit { Get-Date }
Run Code Online (Sandbox Code Playgroud)