Calling Code ?

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
User avatar
Posts: 196
Joined: Tue Feb 25, 2014 1:01 pm

Calling Code ?

Post by mqh777 » Fri Jan 12, 2018 3:10 pm

Product, version and build: 5.4.145
32 or 64 bit version of product: 64
Operating system: Windows 10, Windows 7
32 or 64 bit OS: Both

I have a PowerShell Studio tool that has a field for "computer name" once you enter a computer name you can then press many different buttons on different forms that will execute code against that computer name. I have this code that works as expected but I have to copy/paste it into many many different parts of my overall script as part of any button that runs code against the computer.

if ($PC -eq "" -OR $PC -like " ")
$Error1 = "You did not enter a machine in the computer field."
$richtextbox_Output.SelectionColor = 'Red'


Is there a way to use this code over and over when you want? Can I declare it in some way within PowerShell studio? Or.....can it only work if it is a Function?

I was trying to envision something like this:

$ERRORCODE = "my code from above"

Then I can just call $ERRORCODE when I want and it will execute.

User avatar
Posts: 5279
Joined: Thu Aug 18, 2011 4:56 am

Re: Calling Code ?

Post by davidc » Fri Jan 12, 2018 3:22 pm


A function is probably the best bet. You can also share the same event over multiple button controls. You can use the $this variable to determine what control triggered the event.
SAPIEN Technologies, Inc.

User avatar
Posts: 12399
Joined: Tue May 22, 2007 9:57 am

Re: Calling Code ?

Post by jvierra » Fri Jan 12, 2018 4:01 pm

Use the "Validating" event to enforce the rules for the input control. All controls can be ted tot the same event. When you define a button event use the "events" tab of the properties panel and just select an existing event.