0

So I'm doing a bit of 'House Keepying' on my script and I've found one area than can be reduced/tidied. Take this GUI I've created:

enter image description here

Both menu bar add_click events to Restart HostnameA and HostnameB call seperate functions even though the code in both of the functions is pratically the same, the only difference is this variable for the hostname (see below).

Code for button events.

$Restart_current_machine.Add_Click(
{
restart_current_machines
})

$Restart_target_machine.Add_Click(
{
restart_target_machines
})

# Function Blocks

function restart_target_machines
{
restart-computer -computer $combobox1.text -force
}

function restart_current_machines
{
restart-computer -computer $combobox2.text -force
}

My question is this: is there a way I can use Param() (or something like that) to get rid of function restart_current_machinesthereby only having one function to restart either of the machines?

Something like?

$Restart_current_machine.Add_Click(
{
param($input = combobox1.text)
$input | restart_current_machines
})

$Restart_target_machine.Add_Click(
{
param($input = combobox2.text)
$input | restart_current_machines
})

# Only needing one function

function restart_target_machines
{
restart-computer -computer $input -force
}

I know that is in all probability wrong, but just to give you a better idea of what I'm trying to do.

1 Answer 1

2

Create a generic function that defines a ComputerName parameter and pass that parameter to the underlying cmdlet:

function restart-machine ([string[]]$ComputerName)
{
    Restart-Computer -ComputerName $ComputerName -Force
}

The Rastart-Compter cmdlet ComputerName parameter accepts a collection of names so the parameter is defained as a string array.

Now, from anywhere in your code just call restart-machine and pass the computer names to restart to the ComputerName parameter. To restart multiple machines, delimit each name with a comma (i.e restart-machine -computerName $combobox1.text,$combobox2.text)

$Restart_target_machine.Add_Click(
{
   restart-machine -computerName $combobox1.text
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thank Shay, you're a star and you've come to my assistance again. Would you mind explaning ([string[]]$ComputerName) - I get that the variable is called '$computename' but what does '[string[]]' mean/do?
when a parameter type is set to '[string]' the parameter accepts ONE string only. If you set it to '[string[]]' it can accept ONE OR MORE (array) of strings. When you pass multiple values to a parameter of this kind, you delimit each string with a comma.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.