PowerShell 向自定义对象添加值 属性

PowerShell adding value to a custom object property

我是 PowerShell 的新手,我有点迷茫,我创建了一个新的 PSobject 来存储日期和文件的哈希值,并且该数据存储在 .csv 文件中。我的问题在于尝试在文件的哈希更改时更新信息。我不想覆盖文件,而是添加新信息。以下是我到目前为止所做的以及我得到的错误。我希望有人能澄清我遇到的问题。提前致谢

function GetFileHash {
    $wc = [System.Net.WebClient]::new()
    $settingsObject = Get-Content -Path $PSScriptRoot\config.json | ConvertFrom-Json
    try {
        Get-FileHash -InputStream($wc.OpenRead($settingsObject.pdfUrl))
    }
    catch {
        return $null
    }
}

function CheckforUpdate {
    $fileHash = GetFileHash
    if ($null -eq $fileHash) {
        "Some error occured. The error was: " + $Error[0]
        return
    }
    $csvPath = Join-Path -Path $PSScriptRoot -ChildPath "hashInfo.csv"
    $checkDate = Get-Date
    if ((Test-Path $csvPath) -eq $false) {
        $CSVObject = New-Object PSobject
        $CSVObject | Add-Member -MemberType NoteProperty -Name "CheckDate" -Value $checkDate.DateTime
        $CSVObject | Add-Member -MemberType NoteProperty -Name "LastknowHash" -Value $fileHash.Hash
        $CSVObject | Export-Csv -NoTypeInformation -Path $csvPath
    } else {
        Write-Host "The csv file exist"
        $csvData = @(import-csv $csvPath)
        $onlineHash = $fileHash.Hash
        $lastKnowHash = $csvData | Where-Object {$_.Value -eq $onlineHash}
        if ($lastKnowHash -ne $onlineHash) {
            [PSCustomObject]@{
                CheckDate = $checkDate.DateTime
                LastknowHash = $fileHash.Hash
            } | Export-Csv -Path $csvPath -Append -NoTypeInformation
        }
    }
}

CheckforUpdate

错误如下:

The CheckDate property was not found for this object. Make sure that the property exists and can be set. The LastKnowHash property was not found for this object. Make sure that the property exists and can be set.

假设文件夹中已经有一个 CSV 文件给定 headers 你可以用这样的东西替换你的第二个函数:

$csvPath = Join-Path -Path $PSScriptRoot -ChildPath 'hashInfo.csv'
$csvData = Import-Csv -Path $csvPath

$LastFileHash = ($csvData | Select-Object -Last 1).LastknowHash
$CurrentFileHash = (GetFileHash).Hash
if ($LastFileHash -ne $CurrentFileHash) {
    [PSCustomObject]@{
        CheckDate    = Get-Date
        LastknowHash = $CurrentFileHash
    } |
    Export-Csv -Path $csvPath -Append -NoTypeInformation
}

它将读取现有的 CSV 文件,获取最后一个文件哈希并将其与您使用函数 GetFileHash 获得的当前文件进行比较。如果它们不同,则将当前文件哈希与当前时间戳一起写入 CSV 文件。