从哈希表中检索自定义对象

Retrieve Custom Object From Hashtable

我编写了一个 PowerShell 函数来创建自定义对象并将其存储到哈希中table。我面临的问题是检索该对象。我需要检索该对象,因为它包含一个数组,我需要遍历该数组并将其写入文本文件。

function removeItem {
    <#Madatory Parameters for function, it takes the path to the files/folders
    to clean up and path to the hashtable.#>
    Param([Parameter(Mandatory=$True)]
        [string]$path,
        [string]$writetoText,
        [hashtable] $hashWrite=@{}
    )

    <#Begin if statement: Test if Path Exists#>
    if (Test-Path ($path)) {
        <#Begin if statement: Check if file is Directory#>
        if ((Get-Item $path) -is [System.IO.DirectoryInfo]) {
            $pathObj = [pscustomobject]@{
                pathName = $path
                Wipe = (Get-ChildItem -Path  $path -Recurse)
                Count = (Get-ChildItem -Path $path -Recurse | Measure-Object).Count
            }

            # Write-Output $pathObj.Wipe

            #Add Data to Hashtable
            $hashWrite.Add($pathObj.pathName,$pathObj)

            foreach ($h in $hashWrite.GetEnumerator()) {
                Write-Host "$($h.Name): $($h.Value)"
            }

            <#
            [string[]]$view = $pathObj.Wipe
            for ($i=0; $i -le $view.Count; $i++){
                Write-Output $view[$i]
            }
            #>

            $pathObj.pathName = $pathObj.pathName + "*"
        }<#End if statement:Check if file is Directory #> 
    }       
}

我的函数有 3 个参数、一个路径、文本文件路径和一个散列table。现在,我创建一个自定义对象并存储路径、该路径中包含的 files/folders 和计数。现在,我的问题是,我想从我的 hashtable 中检索该自定义对象,以便我可以遍历 Wipe 变量,因为它是一个数组,并将其写入文本文件。如果我将散列 table 打印到屏幕上,它会将 Wipe 变量视为 System.Object[].

如何从散列 table 中检索我的自定义对象,以便循环遍历 Wipe 变量?

可能的解决方案:

$pathObj = [pscustomobject]@{
    pathName = $path
    Wipe = (Get-ChildItem -Path  $path -Recurse)
    Count = (Get-ChildItem -Path $path -Recurse | Measure-Object).Count
}

#Add Data to Hashtable
$hashWrite.Add($pathObj.pathName,$pathObj)

foreach ($h in $hashWrite.GetEnumerator()) {
    $read= $h.Value

    [string[]]$view = $read.Wipe
    for ($i=0; $i -le $view.Count; $i++) {
        Write-Output $view[$i]
    }
}

这是理想的实现方式吗?

GetEnumerator() 有一些用途,但在您的情况下,您最好只遍历哈希表的键:

$hashWrite.Keys | % {
  $hashWrite[$_].Wipe
} | select -Expand FullName