数组/列表选择

问题描述 投票:0回答:2

描述:尝试将值放入哈希表时遇到问题。下面的代码应该获取一堆组件(该部分有效)的文件路径,并将它们放入一个数组中并对其进行排序。然后创建一个哈希表,其中文件路径作为名称,组件 ID 作为值。该值是通过文件路径名上的 -split 收集的。这部分正在测试和工作,但是当我尝试下面的操作时,我得到一个无法索引到空数组的信息。我已经使用 .Add(filepath[1],RandomValue) 进行了测试,并且该方法有效,但是当我尝试 .Add(filepath[1],-split) 时,它因空数组而失败。我打算将其放入一个循环中,但现在只需让一个值起作用就足够了。

代码:

$fullPathU3 = (Get-ChildItem -Path "P:\Example\Component\Place\Ready" -Recurse -Depth 1| Where-Object {($_.Name -like "*thing") -and ($_.Name -Notlike "*unlinke*") -and ($_.Name -Notlike "*old*")}).fullName
$fullPathU3 = $fullPathU3 | sort


$fileCompTable = New-Object System.Collections.Hashtable 
$fileCompTable = @{}

$fileCompTable.Add($fullPathU3[1] , ($fullPathU3[1] -split "\\")[5])

c# .net powershell
2个回答
0
投票

您的脚本存在一些问题,我已对其进行了如下修改:

$path = "P:\Example\Component\Place\Ready"

$fileCompTable = New-Object System.Collections.Hashtable 
$fileCompTable = @{}

$fullPathU3 = Get-ChildItem -Path $path -Recurse -Depth 1 | Where-Object {($_.Name -like "*thing") -and ($_.Name -Notlike "*unlinke*") -and ($_.Name -Notlike "*old*")}
Write-Output "Items:"
$fullPathU3
$fullPathU3 | ForEach-Object -Process {
    $fileCompTable.Add($_.FullName , ($_.FullName -split "\\")[-1])
}

Write-Output "Hashtable:"
$fileCompTable
  1. ().fullName
    用于集合,如果你想将其应用到 每个元素都可以使用管道,类似于 C# LINQ Select
  2. [5]
    不是获取数组最后一个元素的最佳方法,我建议使用
    [-1]
    索引器
  3. 我修改了你的代码,执行了 foreach 并添加了所有 元素

0
投票

无需显式索引到收集的路径数组中 - 只需使用

ForEach-Object
:

迭代数组即可
$fileSystemItems = Get-ChildItem -Path "P:\Example\Component\Place\Ready" -Recurse -Depth 1 |Where-Object {($_.Name -like "*thing") -and ($_.Name -Notlike "*unlinke*") -and ($_.Name -Notlike "*old*")}

$fileCompTable = @{}
$fileSystemItems |ForEach-Object {
  $compID = ($_.FullName -split '\\')[5]
  $fileCompTable[$_.FullName] = $compID
}
© www.soinside.com 2019 - 2024. All rights reserved.