I am new in PowerShell, and I am a bit lost, I have created a new PSobject that stores Dates and the Hash of a file and that data is stored in a .csv file. My problem lies in trying to update the information when the Hash of the file changes. I would not want to overwrite the file, but add the new information. Below is what I have done so far and the error I get. I hope someone can clarify the problem that I have. Thanks in advance
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
Here is the error:
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.
CodePudding user response:
Assumed there already is a CSV file in the folder with the given headers you could replace your second function with something like this:
$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
}
It will read the existing CSV file, take the last file hash and compare it against the current one you get with your function GetFileHash
. If they're different the current file hash is written to the CSV file along with the current time stamp.