gpt4 book ai didi

在 Register-ObjectEvent 的操作中执行函数的 Powershell 控制台问题

转载 作者:行者123 更新时间:2023-12-02 23:23:45 33 4
gpt4 key购买 nike

在 powershell ISE 中工作正常,但在控制台中我得到:

The term 'MainAction' 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.

如何修复?

function MainAction () {
$test = "123"
Write-Host $test
}

MainAction

$action = {
try {
Write-Host in action
MainAction
} catch {
Write-Host $Error
$timer.Stop()
Unregister-Event thetimer
}
}

$timer = New-Object Timers.Timer
Register-ObjectEvent -InputObject $timer -EventName elapsed `
-SourceIdentifier thetimer -Action $action -OutVariable out
$timer.Interval = 5000
$timer.AutoReset = $true
$timer.Start()

编辑:

我发现我可以使用配置文件来存储函数定义。至create profile使用:

New-Item -path $profile -itemType file -force

但我仍然很感兴趣,为什么 powershell ISE 不需要配置文件来存储和使用 Register-ObjectEvent 操作中的函数。

最佳答案

当您使用 Register-ObjectEvent 注册 -Action 时,PowerShell 将创建新的动态模块来承载该操作。因此,作为结果,只有全局范围在事件处理程序和其余代码之间共享。因此,您应该将所有需要的函数放在全局范围内:

function global:MainAction {
Write-Host 'Do something'
}

$Action = { MainAction }

$Timer = New-Object Timers.Timer
$EventJob = Register-ObjectEvent -InputObject $Timer -EventName Elapsed -Action $Action

$Timer.Interval = 5000
$Timer.AutoReset = $true
$Timer.Start()

或者将它们显式添加到由 PowerShell 创建的动态模块的范围内:

$Action = { MainAction }

$Timer = New-Object Timers.Timer
$EventJob = Register-ObjectEvent -InputObject $Timer -EventName Elapsed -Action $Action

. $EventJob.Module {
function MainAction {
Write-Host 'Do something'
}
}

$Timer.Interval = 5000
$Timer.AutoReset = $true
$Timer.Start()

关于在 Register-ObjectEvent 的操作中执行函数的 Powershell 控制台问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42174731/

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