[英]Powershell jump to another script
One of the lesser known features of DOS and DOS-like command files is that a line that starts with the name (path) of a batch file transfers control to the new file, with no return (as opposed to the "call" command which returns when execution is complete). DOS 和类似 DOS 的命令文件鲜为人知的特性之一是,以批处理文件的名称(路径)开头的行将控制权转移到新文件,而没有返回(与“调用”命令相反执行完成后返回)。
Can I do this with Powershell too?我也可以用 Powershell 做到这一点吗? It's a bit like "goto otherscript.ps1" but I know there is no goto in Powershell.
这有点像“转到 otherscript.ps1”,但我知道 Powershell 中没有转到。
The reason for asking is that I want to update the currently executing script from subversion if changes are available, and then execute the updated file from the top.问的原因是我想从subversion更新当前正在执行的脚本,如果有变化,然后从顶部执行更新后的文件。
You can use dot sourcing to run an external script - eg:您可以使用点源来运行外部脚本 - 例如:
main.ps1主.ps1
. ".\sub.ps1"
sub.ps1子.ps1
write-host "aaa"
It's more like an "include" than a goto as it runs in the current script's context and can access / modify variables in the main script:它更像是一个“包含”而不是一个 goto,因为它在当前脚本的上下文中运行并且可以访问/修改主脚本中的变量:
main.ps1主.ps1
. ".\sub.ps1"
write-host $x
# ^ outputs "bbb"
sub.ps1子.ps1
$x = "bbb"
write-host "aaa"
You can prevent the dot sourced script accessing the main script's context if you use the call operator - eg如果您使用调用运算符,您可以阻止点源脚本访问主脚本的上下文 - 例如
main.ps1主.ps1
& { . ".\sub.ps1" }
write-host $x
# ^ outputs a blank line
sub.ps1子.ps1
$x = "bbb"
write-host "aaa"
If you put an exit
after the dot sourced script it'll end the main script and kinda-sorta be like a goto...如果您在点源脚本之后放置
exit
,它将结束主脚本并且有点像 goto ......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.