我有一个包含几个函数的PowerShell脚本。我如何从命令行调用特定的功能?从命令行调用特定的PowerShell功能
这不起作用:
powershell -File script.ps1 -Command My-Func
我有一个包含几个函数的PowerShell脚本。我如何从命令行调用特定的功能?从命令行调用特定的PowerShell功能
这不起作用:
powershell -File script.ps1 -Command My-Func
您通常会 “点” 的剧本到范围(全球,另一个剧本,一个脚本块内)。点一个脚本既会加载和执行该范围内的脚本,也不会创建新的嵌套范围。使用函数,这有利于在脚本执行后他们坚持。你可以做什么Tomer的建议,只是你需要点脚本如:
powershell -command "& { . <path>\script1.ps1; My-Func }"
如果你只是想从当前的PowerShell会话中执行的功能,那么这样做:
. .\script.ps1
My-Func
只是要意识到任何不在函数中的脚本都将被执行,任何脚本变量都将成为全局变量。
也许类似
powershell -command "& { script1.ps; My-Func }"
该指令在下面引发错误消息。正如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.
+1,第二代码片段是我需要的,做独立的功能简单的调试,从ISE – 2011-07-18 12:54:10
一个脚本文件,在第二个代码片段,您可以环绕代码'& {...}'在'&{。 \ script1.ps1; My-Func}'以避免范围污染。 – 2015-12-17 19:28:36
如果您有该功能的参数,请将它们放在功能名称后面,例如powershell -command“&{。”C:\ script.ps1“; MyMethod”arg1“”arg2“}” – HockeyJ 2017-08-18 14:36:59