2

I am attempting to build a script that will import data from a CSV and process commands based on the data that is filled in. Small Example:

CSV formatted with following headers

Name TargetOU Description ManagingGroup Permission

Some of these are required and some are optional.

This would be easy to accomplish using Parameters, but this is attempting to run without user interaction. The below code would solve the problem if I just had Name and a optional Description:

If ($_.Description -ne $null) {
    New-GPO -Name $_.Name -Description $_.Description }
ElseIF ($_.Description -eq $null) {
    New-GPO -Name $_.Name }

If I want to make it more complex I end up having to write an If statement for every possible combination of required and optional parameters:

If ($_.Description -ne $null -and $_.TargetOU -ne $null) {
    New-GPO -Name $_.Name -Description $_.Description | New-GPLink -Target $_.TargetOU }
ElseIf ($_.Description -eq $null -and $_.TargetOU -ne $null) {
    New-GPO -Name $_.Name | New-GPLink -Target $_.Target }

etc... for every possible combination.

Is there any simpler way to build this command without 100's of If statements? The CSV will potentially contain 10 options to fill in based on what users want completed.

2 Answers 2

2

you just need to separate mandatories parameters and optional parameters. You initialize optional parameters with default values and If a mandatory parameter is missing you just cancel the operation for the line.

1

You could use splatting. In splatting, you pass a hashtable to a function, which is interpreted as arguments.

for example:

$params=@{Name='Fred'}

my-func @params

By using splatting, you don't have to have a bunch of nested if-then constructs, just build the list of parameters and send it.

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.