1

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.

4

2 回答 2

4

我认为您正在寻找的是splatting。您创建一个表示参数的名称/值对的哈希,并将其传递到 cmdlet。这为有条件地为 cmdlet 设置参数提供了一种非常简单的方法,而无需复制/粘贴如何在 switch 或嵌套 if/else 块中调用 cmdlet 的各种排列。

$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;
于 2013-10-09T20:15:24.520 回答
2

这是一个常见问题 - “我想调用一个 cmdlet,但根据各种编程条件存在/缺少一些参数。”

标准解决方案是将您的参数放在哈希表中,并使用splatting传递它们。

$array = @()
$array += "red"
$array += "blabla"

$params = @{}
if ($array[0]) { $params['foregroundcolor'] = $array[0] }
if ($array[1]) { $params['object'] = $array[1] }

write-host @params
于 2013-10-09T20:15:33.717 回答