如何从PowerShell脚本打开另一个PowerShell控制台
在OSX中,我打开一个bash终端并输入一个PowerShell控制台。 在我的PowerShell脚本中,我想打开另一个PowerShell控制台并在那里执行PowerShell脚本。如何从PowerShell脚本打开另一个PowerShell控制台
在Windows下,我会做
Invoke-Expression ('cmd /c start powershell -Command test.ps1')
我怎么能这样做在OSX的samething?
要在MacOS在一个新的终端窗口启动PowerShell的实例:
无能够传递参数:
PS> open -a Terminal $PSHOME/powershell
如果你想运行一个给定的命令:
不幸的是,如果你想通过一个命令在新的PowerShell实例运行需要相当多的工作:
从本质上讲,你需要将您的命令在一个临时的,自我删除,可执行的shell脚本,通过认领行调用:
注:一定要运行至少PowerShell核心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 }
很高兴听到它,Jim(感谢您确认,@LotPings)是的,通过shebang行的调用在之前的beta版中被打破;我添加了一个说明最低版本要求的注释。一旦有新版本发布,就值得更新。 – mklement0
我不知道在Mac PowerShell的东西,如果存在的话,但打开像Mac OS X上的终端就可以使用命令打开一个GUI应用程序:
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
我尝试了一些与'open -a Terminal.app'不同的东西,但没有运气。我没有尝试第二种解决方案。我想打开另一个powershell控制台并从powershell脚本执行powershell脚本,我是不知道如何实现2nd。 – Jim
'开始powershell'? –
没有帮助:( – Jim
您是否在OS/X上使用PowerShell 6从https://github.com/PowerShell/PowerShell – lit