从命令行调用特定的PowerShell函数

rip*_*234 38 powershell

我有一个包含多个函数的PowerShell脚本.如何从命令行调用特定功能?

这不起作用:

powershell -File script.ps1 -Command My-Func
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 77

您通常会将脚本"点"到范围内(全局,另一个脚本,在scriptblock中).对脚本进行加点将在该范围内加载和执行脚本,而无需创建新的嵌套范围.使用函数,这样做的好处是它们在脚本执行后仍然存在.你可以做Tomer所建议的,除了你需要点脚本,例如:

powershell -command "& { . <path>\script1.ps1; My-Func }"
Run Code Online (Sandbox Code Playgroud)

如果您只想从当前的PowerShell会话中执行该功能,请执行以下操作:

. .\script.ps1
My-Func
Run Code Online (Sandbox Code Playgroud)

请注意,任何不在函数中的脚本都将被执行,任何脚本变量都将成为全局变量.

  • 如果您在函数上有参数,请将其放在函数名称之后,例如powershell -command“&{。” C:\ script.ps1“; MyMethod” arg1“” arg2“}” (2认同)

Abu*_*lal 6

该解决方案适用于 powershell 核心:

powershell -command "& { . .\validate.ps1; Validate-Parameters }" 
Run Code Online (Sandbox Code Playgroud)


Las*_*ter 5

该指令抛出以下错误消息。正如 Keith Hill 建议的那样,文件名前面需要有一个点才能将其加载到内存中。

MyFunction: The term 'MyFunction' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.