Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function PowerShell和全局函数_Function_Powershell_Global - Fatal编程技术网

Function PowerShell和全局函数

Function PowerShell和全局函数,function,powershell,global,Function,Powershell,Global,为什么下面的代码不起作用?根据本文,global的用法应该是正确的: 这是powershell抛出的异常 The term 'writeLog' 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 correc

为什么下面的代码不起作用?根据本文,global的用法应该是正确的:

这是powershell抛出的异常

The term 'writeLog' 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.
    + CategoryInfo          : ObjectNotFound: (writeLog:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
    + PSComputerName        : localhost

启动作业的文档中

Windows PowerShell后台作业“在后台”运行命令,而不与当前会话交互

因此,将忽略当前会话范围

简单的解决方案:在scriptblock中定义函数

$JobScript = { 
    function write-log {
        ....
    }
    write-log <parameters>
}
$JobScript={
函数写入日志{
....
}
写日志
}
或者,检查以下相关问题:


PowerShell作业实际上在单独的PowerShell进程中运行。你可以这样看:

$pid
Start-Job {$pid} | Receive-Job -Wait
其中,
$pid
是当前PowerShell的进程id

需要从作业中运行的脚本中访问的任何内容,必须在传递到启动作业的脚本块中定义,即在脚本块中定义的函数,或使用启动作业上的
-ArgumentList
参数传递到脚本块中的参数,否则脚本可以点源另一个脚本(或导入模块)包含所需功能的。就我个人而言,我会将共享函数放在Utils.psm1这样的模块中,然后像这样导入:

Start-Job {param($scriptdir) Import-Module $scriptdir\Utils.psm1; ...} -Arg $PSScriptRoot

在脚本块中定义函数,然后使用

  • 使用NoNewScope调用命令以在当前范围内获取该命令
  • 用于将其放入作业的InitializationScript参数
  • #创建共享函数脚本块
    [scriptblock]$func={function getPID(){write output“函数在进程id:$pid!”中运行}
    #在普通脚本范围内设置函数,以便可以在此处访问
    调用命令-NoNewScope-ScriptBlock$func
    写入输出“主脚本已启动”
    #从父脚本运行函数
    格特皮德
    #创建后台作业脚本
    $jobScript={getPID}
    #运行后台作业
    写入输出“启动后台作业”
    启动作业$jobScript-名称“Job1”-初始化脚本$func
    得到工作|得到工作
    得到工作|停止工作
    获取作业|删除作业
    
    除了传递参数之外,您的
    $temp{writeLog…}
    是否存在其他功能?相反,使用
    ArgumentList
    参数将参数直接从
    Start Job
    传递到函数,跳过中间人。写一个更精确的问题!
    Start-Job {param($scriptdir) Import-Module $scriptdir\Utils.psm1; ...} -Arg $PSScriptRoot