gpt4 book ai didi

arrays - PSObject 数组返回 Powershell 读取单个项目/行

转载 作者:行者123 更新时间:2023-12-04 16:35:50 25 4
gpt4 key购买 nike

我正在使用一个函数来调用另一个函数并返回一个 PSObject 数组或多个数组(我认为)。每个循环对象后的返回值是一组值。 Function Test2 中 $a 中的数据在下面,但它的计数是 3,这意味着三个对象或数组,每个文件夹一个。这似乎很正常,如果我将其写入 CSV 以用于报告,我会很好,但我希望操作每个数组中的数据。当我尝试操作数据时,它正在尝试操作数组,但我无法搜索或使用每一行中的项目。我也不知道我有多少个文件夹,因此解决方案需要通用且可扩展。我不知道如何轻松访问所有数组中的每一行。

Function Test1 {
[cmdletbinding()]
param(
[Parameter(Position = 0, Mandatory = $true)]
[string]$Folder
)

$array1 = @("Folder1_Test1","Folder1_Test2","Folder1_Test3","Folder1_Test4","Folder1_Test5 ","Folder2_Test6","Folder2_Test7","Folder2_Test8","Folder2_Test9","Folder3_Test1 0")
$array2 = @("Folder1_Test1","Folder1_Test4","Folder1_Test5","Folder2_Test9")


$data = @()
Foreach ($item in $array1) {
If ($item -match $Folder -and $array2 -notcontains $item) {
$Obj = New-Object PSObject -Property @{
Folder = $Folder;
SubFolder = $item;
Message = "$item not found.";
}
$data += $Obj
}
}
Return ,$data
}

Function Test2 {
$Folders = @("Folder1", "Folder2", "Folder3")
$a = $Folders | ForEach-Object {Test1 $_}
$a.Count

foreach ($item in $a)
{
$item.Folder
$item.SubFolder
$item.Message
}
}

然而,$a 的输出计数为 3。
SubFolder      Message                   Folder 
--------- ------- ------
Folder1_Test2 Folder1_Test2 not found. Folder1
Folder1_Test3 Folder1_Test3 not found. Folder1
Folder2_Test6 Folder2_Test6 not found. Folder2
Folder2_Test7 Folder2_Test7 not found. Folder2
Folder2_Test8 Folder2_Test8 not found. Folder2
Folder3_Test10 Folder3_Test10 not found. Folder3

如何访问每个对象内的每一行?我希望能够搜索子文件夹,然后识别它所在的文件夹并编写消息,如下所示:
$a | ForEach-Object | Write-Host {"Subfolder $($_.Subfolder) is in $($_.Folder) and error message is $($_.Message)"}

提前致谢。

最佳答案

您正在创建的是一个包含三个元素的数组。数组中的每个元素都显示信息。当您将它写到控制台时,您会看到所有元素都挤在一起:

SubFolder          Message                       Folder 
--------- ------- ------
Folder1_Test2 Folder1_Test2 not found. Folder1
Folder1_Test3 Folder1_Test3 not found. Folder1
Folder1_Test5 Folder1_Test5 not found. Folder1
Folder2_Test6 Folder2_Test6 not found. Folder2
Folder2_Test7 Folder2_Test7 not found. Folder2
Folder2_Test8 Folder2_Test8 not found. Folder2
Folder3_Test1 0 Folder3_Test1 0 not found. Folder3

如果你查看 $a[0] 你会看到:
PS C:\WINDOWS\system32> $a[0]

SubFolder Message Folder
--------- ------- ------
Folder1_Test2 Folder1_Test2 not found. Folder1
Folder1_Test3 Folder1_Test3 not found. Folder1
Folder1_Test5 Folder1_Test5 not found. Folder1

这就是计数返回 3 的原因。
如果您使用 $a[0][0]您将看到一行,因为它正在访问 $a 的第一个元素,它是一个数组,然后访问该数组的第一个元素。您必须使用嵌套循环来访问嵌套数组中的每个元素。

关于arrays - PSObject 数组返回 Powershell 读取单个项目/行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46285443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com