2

I have written a powershell script to simple start or stop and array of services.

Here is my current script:

param([Switch] $Stop, [Switch] $Start) 

$services = @(
"Service1",
"Service2",
"Service3",
"etc"
)

if ($Start -eq $true) { 
    echo "Starting services..."
    get-service $services | start-Service
} 

if ($Stop -eq $true) { 
    echo "Stopping services..."
    get-service $services | stop-Service
} 

echo "Done."

The command is simply Services -stop or Services -start

The parameters -stop or -start are discoverable (when you hit tab) which I love.

Currently this will stop or start all the services in the array, what I would like to do is also have an option to stop or start a particular service.

This is easy enough if I modify the parameters and take in a service name.

BUT what I would really like to do, is have those services names to be fixed to the ones in my array, and to be discoverable in the same way so that hitting tab will go through the available default?

The result might be something like this:

Services -stop -service:Service1

Is this possible to do? To limit the -service to the ones in my array?

1 Answer 1

3

You can do this with the ValidateSet attribute e.g.:

param(
    [Parameter()]
    [Switch]
    $Stop,

    [Parameter()]
    [Switch]
    $Start,

    [Parameter()]
    [ValidateSet("Service1","Service2","Service3","etc")]
    [string[]]
    $Service
) 

...

You would invoke tab completion like so:

Services -stop -service <tab>
Sign up to request clarification or add additional context in comments.

2 Comments

I'll give it a try, can I use the same array or will I have to duplicate that portion? (within the validateset)
You can access the validateset, but it's a bit messy: $services = $MyInvocation.MyCommand.Parameters['Service'].Attributes | ? { $_.TypeId.Name -eq 'ValidateSetAttribute' } | select -ExpandProperty ValidValues

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.