在 OSX 中,我打开一个 bash 终端并进入一个 PowerShell 控制台。在我的 PowerShell 脚本中,我想打开另一个 PowerShell 控制台并在那里执行一个 PowerShell 脚本。
在 Windows 下,我会做
Invoke-Expression ('cmd /c start powershell -Command test.ps1')
我怎么能在 OSX 中做同样的事情?
在 OSX 中,我打开一个 bash 终端并进入一个 PowerShell 控制台。在我的 PowerShell 脚本中,我想打开另一个 PowerShell 控制台并在那里执行一个 PowerShell 脚本。
在 Windows 下,我会做
Invoke-Expression ('cmd /c start powershell -Command test.ps1')
我怎么能在 OSX 中做同样的事情?
要在 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 }
我对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 或后台运行
子壳:
output=$(ls)
echo $output
背景:
./command &
具有重定向输出的背景,因此它不会渗入您当前的外壳:
./command 2>&1 > /dev/null