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

时间:2017-09-04 18:13:14

标签: macos powershell terminal powershell-core

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

在Windows下,我会这样做

Invoke-Expression ('cmd /c start powershell -Command test.ps1')

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

2 个答案:

答案 0 :(得分:1)

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

无法向其传递参数

PS> open -a Terminal $PSHOME/powershell

如果您想运行指定的命令

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

注意:请确保至少运行 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

}

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

# Sample invocation
Start-InNewWindowMacOS -NoExit { Get-Date }

答案 1 :(得分:0)

我对mac上的powershell一无所知,如果它甚至存在,但是要在Mac OS X上打开像终端这样的gui应用程序,你可以使用open命令:

open -a /Applications/Utilities/Terminal.app ""将是一个新的空白窗口
open -a /Applications/Utilities/Terminal.app somescrip.sh将运行脚本

或者你可以制作一个苹果脚本并运行

将以下内容保存在文件中(〜/ OpenNewTerminal.scp):

tell application "Terminal"
    do script " "
    activate
end tell

然后你可以用osascript

运行它

osascript ~/OpenNewTerminal.scp

当然,更多bash习惯的方式是在子shell或后台运行

子shell:

output=$(ls)
echo $output

背景:

./command &

具有重定向输出的背景,因此它不会渗入当前的shell:

./command 2>&1 > /dev/null
相关问题