gpt4 book ai didi

function - PowerShell 和全局函数

转载 作者:行者123 更新时间:2023-12-02 22:41:05 24 4
gpt4 key购买 nike

为什么下面的代码不起作用?根据本文,global 的用法应该是正确的: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 的文档:

A Windows PowerShell background job runs a command "in the background" without interacting with the current session.

因此,当前 session 范围被忽略。

简单的解决方案:在脚本 block 中定义函数。

$JobScript = { 
function write-log {
....
}
write-log <parameters>
}

或者,检查这些相关问题:

Powershell: passing parameters to a job

Variables in Start-Job

关于function - PowerShell 和全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19277313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com