简体   繁体   English

如何在Powershell中和内部调用函数?

[英]How to call a function within & in powershell?

Suppose I have a function in test.ps1, its name is show the code is like below: 假设我在test.ps1中有一个函数,它的名称显示代码如下:

. "some_path\some_other_script.ps1"

function show {
    write-host "Hello World"
    #some other function call from some_other_script.ps1
    ...
}

How can I call show in follow format (in a & - call operator) 如何呼叫跟随格式的节目(在&-呼叫运算符中)

powershell.exe "& '%test_script_path%\test.ps1'\show"

I think I need to dot source test.ps1 first in order to get dependencies in show function from some_other_script.ps1 我想我需要先点源test.ps1以便从some_other_script.ps1中获得show函数的依赖关系

I know I can create a new script and put the code in show in the new script instead of in a function. 我知道我可以创建一个新脚本并将代码显示在新脚本中而不是函数中。 In that way, when do &... the script will be invoked. 这样,当do&...时,脚本将被调用。 But I don't want to create a new script just for a very simple function 但是我不想为一个非常简单的功能创建一个新脚本

Thanks for any suggestion 感谢您的任何建议

You could dot source it and then call it like this. 您可以点源它,然后这样称呼它。

powershell -Command ". '%test_script_path%\toolsql.ps1'; show"

The ; ; is used as a separator between commands. 用作命令之间的分隔符。

I am really appreciated for the help and time from @Patrick Meinecke, the following command works. 我真的很感谢@Patrick Meinecke的帮助和时间,以下命令有效。

powershell -command ". .\test.ps1;show"

Like he mentioned in the chat, "So to explain that the .\\ just indicates it's in the current directory it still needed the other . to tell powershell to load the script into the current context" 就像他在聊天中提到的那样,“因此,要说明。\\只是表明它位于当前目录中,它仍然需要另一个。来告诉powershell将脚本加载到当前上下文中”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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