Search code examples
powershellparametersparameter-passingcode-duplication

Powershell: Passing parameters to function


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.


Solution

  • 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
    })