为什么下面的代码不起作用?根据这篇文章,全局的用法应该是正确的:http://technet.microsoft.com/en-us/library/ff730957.aspx http://technet.microsoft.com/en-us/library/ff730957.aspx
Function global:writeLog {
param($logType, $logString, $logFile)
$fileStream = New-Object IO.FileStream $logFile ,'Append','Write','Read'
$streamWriter = New-Object System.IO.StreamWriter $fileStream
$time = get-date -Format "hh:mm:ss"
$streamWriter.writeLine("[${time}][$logType] ${logString}")
$streamWriter.close()
}
$temp = {
writeLog -logType "INFO" -logString "Test" -logFile "d:\scripts\powershell\logtest.txt"
}
Start-Job -ScriptBlock $temp
get-job | receive-job -AutoRemoveJob -Wait
这是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
从文档Start-Job
:
Windows PowerShell 后台作业“在后台”运行命令,而不与当前会话交互。
因此,当前会话范围被忽略。
简单的解决方案:在脚本块内定义函数。
$JobScript = {
function write-log {
....
}
write-log <parameters>
}
或者,检查以下相关问题:
Powershell:将参数传递给作业 https://stackoverflow.com/questions/4472284/powershell-passing-parameters-to-a-job
开始作业中的变量 https://stackoverflow.com/questions/10196489/variables-in-start-job
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)