2

I'm creating a custom object in powershell. This object must raise an event, but there is no way to assign an event name with new-event CMDLET. I tired to add an event with add-member cmdlet, but powershell returns an issue that says "is not possible to assign an event to PSObject". Thereis an other way to perform this action? Thanks in advance. Germano

Germano Carella
  • 473
  • 6
  • 14

2 Answers2

1

The CmdLets Register-EngineEvent and New-Event may help you to register and fire your own events :

With New-Event you must specifie

  • -SourceIdentifier : Your own identifier

You should specifie

  • -Sender : the object that emit the event
  • -EventArguments : an array of arguments
  • -MessageData : a parameter object

Here is an example :

New-Event -SourceIdentifier "MyOwnEvent" -EventArguments "A Param"

Cmdlet Register-EngineEvent allow your code to subscribe to Windows PowerShell engine events, but also to the events fired by New-Event.

$evt1 = Register-EngineEvent -SourceIdentifier "MyOwnEvent" -Action {[console]::Beep(500,500)}

So now your object can have a note property called Event1 with the value "MyOwnEvent" a piece of code can register to this event with Register-EngineEvent and you object can fire this event with New-Event.

JPBlanc
  • 70,406
  • 17
  • 130
  • 175
0

-Edit, sorry misread the question. Did a quick search and turned up this answer

$o=New-Object PSObject -property @{"_val"=1}

Add-Member -MemberType ScriptMethod -Name "Sqrt" -Value {

 write-host "the square root of $($this._val) is $([Math]::Round([Math]::Sqrt($this._val),2))"
} -inputObject $o

Add-Member -MemberType ScriptProperty -Name 'val' -Value{ $this._val }  -SecondValue { $this._val=$args[0];$this.Sqrt() } -inputObject $o
Community
  • 1
  • 1
user4317867
  • 2,397
  • 4
  • 31
  • 57