bash的exec()在PowerShell中的等效项是什么?

Jam*_* Ko 5 windows powershell scripting exec

PowerShell的新手在这里。从当前进程中运行新脚本而不创建子shell的最佳方法是什么?在Bash中,您可以通过以下方式进行操作:

source script # Executes the commands in script within the current shell
Run Code Online (Sandbox Code Playgroud)

要么

exec script # Same as source, except it completely replaces the current process with script
Run Code Online (Sandbox Code Playgroud)

在PowerShell中有与此等效的功能吗?

use*_*867 1

您还可以使用.\Script.ps1

或者开始输入名称并使用TAB来完成脚本名称。

点源脚本允许函数在命令行上可用。

例如:

Function Get-LocalTime { 

$CurTime = Get-Date

"The Date and time currently is $CurTime"

}
Run Code Online (Sandbox Code Playgroud)

现在我们点源(将上面的脚本命名为Example.ps1)PS C:\>. .\Example.ps1

允许我们简单地键入并按 Tab 完成Get-LocalTime

https://i.stack.imgur.com/QAHmS.png

-编辑注释,您可以定义一个函数并在同一脚本中立即使用该函数。所以Example.ps1在最后一行只需输入Get-LocalTime

  • 这回答了问题的前半部分(powershell相当于源代码),但没有回答标题。有相当于“exec”的吗?这对于创建一个运行 bash 的别名非常有用,这样你就不必“退出”两次。 (8认同)
  • 对于不熟悉 Unix exec() 的 Windows 管理员来说,它将执行上下文完全传递给子进程,父进程不再作为进程占用内存。如果我们执行 ps,原来的 powershell 进程应该会消失。这非常有用,因为有时我们想在启动服务之前做一些事情,但不希望父 shell 闲置。 (6认同)