我已尝试搜索此问题但未发现任何有用的信息。
我正在尝试使用Powershell函数循环遍历字符串数组。我的想法是我正在尝试添加第二个数组。第一个数组有一周的日子。第二个数组是时间戳,例如2015-01-19
到目前为止我的工作如下。我知道使用Get-Date
然后将其格式化为可行的(通过添加和格式化结果)可能会更容易,我愿意接受建议。 - 谢谢,我真的非常感谢你的帮助!
Function My-Test{
param(
[string[]]$arr,
[string[]]$arr2
)
Foreach($day in $arr){
"$day is the best day to read something."
}
Foreach($var2 in $arr2){
echo $arr2
}
}
$days = @("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
$var2 = @("1","2","3","4","5","6","7")
My-Test -arr $days -arr2 $var2
$array = @(
("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"),
("2015-01-01","2015-01-02","2015-01-03","2015-01-04","2015-01-05","2015-01-06","2015-01-07")
)
$array[0][2]
$array
不返回两个属性,它返回Wednesday
答案 0 :(得分:1)
回答后续问题。
您可以在单个数组或包含两个数组的数组中返回两个值(我假设$ arr和$ arr2):
Function My-Test{
param(
[string[]]$arr,
[string[]]$arr2
)
Foreach($day in $arr){
write-host "$day is the best day to read something."
}
Foreach($var2 in $arr2){
write-host $var2
}
$ret = $arr+$arr2
return $ret
}
$days = @("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
$var2 = @("1","2","3","4","5","6","7")
$ret = My-Test -arr $days -arr2 $var2
然后$ret.Count
为14而$ ret包含合并的$ arr + $ arr2
其他可能性是创建数组数组或二维数组:
$ret = @()
$ret += ,$arr
$ret += ,$arr2
return $ret
在这种情况下,$ret[0]
包含工作日,$ret[0][0]
为星期一,$ret[0][1]
为星期二等,$ret[1]
包含第二个数组。
PS。你不需要写return
你可以简单地写$ret
,因为它暗示你正在返回那个值,但是在这个例子中解释这个例子更简单。我的看法。
事实上,您甚至不需要创建$ret
变量,您只需编写
@($arr,$arr2)
修改强>
您一次只能访问一个数组中的元素。
让我们看看你的新的多维数组
$array = @(
("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"),
("2015-01-01","2015-01-02","2015-01-03","2015-01-04","2015-01-05","2015-01-06","2015-01-07")
)
让我们看看$array[0]
包含的内容:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
所以$array[0][0]
是这个数组的第一个元素,星期一,$array[0][1]
是第二个,星期二等。
如果我们看第二个数组:
$array[1]
它包含:
2015-01-01
2015-01-02
2015-01-03
2015-01-04
2015-01-05
2015-01-06
2015-01-07
第二个数组的第一个元素是$array[1][0]
,2015-01-01,第二个是$array[1][1]
,2015-01-02等。