Reputation: 323
need some help!
I have a rather difficult problem, I would like to solve. I have an array:
@array = string, string, string
In my example:
yellow, red, blabla
I would like to use these string from the array and put them in a commandlet with extra if-clauses (difficult to explain, I will better show it) and check if they exist before adding them to the commandlet.
$array = @()
$array += "red"
$array += "blabla"
$command = write-host
if ($array[0]) {$command = $command + " -foregroundcolor $array[0]"}
if ($array[1]) {$command = $command + " -object $array[1]"}
&$command
This obviously doesn't work. The question is, how can I have some sort of puzzling together certain parameters of a single commandlet with strings?
Error tells me more or less, that this no commandlet or executable script.
another idea I had, but I would like to avoid, because it won't stay simple:
If (!$array[0]) {
(if (!$array[1]) {write-host "nodata"} else {write-host -object $array[1]})
else
(if (!$array[1]) {write-host -foregroundcolor $array[0]}
else {write-host -forgroundcolor $array[0] -object $array[1]})
}
Got an error in there already.
Upvotes: 1
Views: 58
Reputation: 16792
This is a common issue - "I want to call a cmdlet, but with some parameters present/missing depending on various programmatic conditions."
The standard solution is to put your arguments in a hashtable, and pass them using splatting.
$array = @()
$array += "red"
$array += "blabla"
$params = @{}
if ($array[0]) { $params['foregroundcolor'] = $array[0] }
if ($array[1]) { $params['object'] = $array[1] }
write-host @params
Upvotes: 2
Reputation: 28174
I think what you're looking for is splatting. You create a hash which represents the name/value pairs of your parameters, and pass that into the cmdlet. This makes for a very easy way to conditionally set parameters for a cmdlet without having to copy/paste the various permutations of how the cmdlet is called within switch or nested if/else blocks.
$MyParms = @{};
$array = @()
$array += "red"
$array += "blabla"
if ($array[0]) {$MyParms.Add("foregroundcolor",$array[0])};
if ($array[1]) {$MyParms.Add("object",$array[1])};
Write-Host @MyParms;
Upvotes: 4