Figo
Figo

Reputation: 1

PowerShell troubles - Using Functions with Parameters

I am developing a script which will be used to disable people's AD accounts in PowerShell as well as perform a lot of other functions.

I wanted the script to give the option of bulk mode or single mode. For example, as soon as you run the script, a parameter is enforced that asks if you want to run it in single mode or bulk mode. If bulk mode is selected, then it should load the function BULKmode which has already been defined and imports a csv.

If Single mode is selected, then it runs in single mode and selects the function Singlemode.

However the problem with PowerShell is that both parameters and functions go at the top of your script. I have tried both orders and the error I receive when I put the functions before the parameter is that there is

no such term as param

When i put the parameter first then it loads the parameter but then says

no such function

Below is a snippet

Param(
[Parameter (Mandatory=$true)]
[String]$PressYforBulkMode)

If ($PressYforBulkMode -eq "Y") {
Bulkmode
}

Else {
Singlemode
}

Upvotes: 0

Views: 49

Answers (2)

Dave
Dave

Reputation: 364

It seems you want to prompt for user input. I prefer using Parameters but if you want to prompt for input try this:

Function BulkMode
{
    "Running BulkMode"
}

Function SingleMode
{
    "Running SingleMode"
}


$Input = Read-Host "Press Y for BulkMode"

if ($Input -eq "Y")
{
    Bulkmode
}

else
{
    SingleMode
}

Upvotes: 0

Jason Snell
Jason Snell

Reputation: 1465

The best solution is to break apart your functions so that you can just use a loop to use the function that does the actual work.

The way to do this would be to pass your information into the main function as an array. If you have one entry or many entries it won't matter. Then use foreach to loop through the array and call the function that actually disables the AD account and any other actions required.

This would mean you wouldn't have to ever check for 'bulk' or 'single' mode. It would just work.

Example:

function MainFunction
{
param (pass in array here)

    foreach(entry in $myArray)
    {
        DoWork $entry
    }
}

function DoWork
{
    //do things here
}

Upvotes: 1

Related Questions