简体   繁体   中英

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).

Can I do this with Powershell too? It's a bit like "goto otherscript.ps1" but I know there is no goto in 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.

You can use dot sourcing to run an external script - eg:

main.ps1

. ".\sub.ps1"

sub.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:

main.ps1

. ".\sub.ps1"
write-host $x
# ^ outputs "bbb"

sub.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

& { . ".\sub.ps1" }
write-host $x
# ^ outputs a blank line

sub.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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM