HI,
I'm having a bad PowerShell day today!
My sample script to read in a text file and put the data into a hash table works just fine:
$InputFile=Get-Content C:\Out\ktf06011.REQ
$CurrentUserHashTable = @{}
ForEach ($Line in $InputFile)
{
$Data=$Line.Split("=")
$Label=$Data[0].Trim()
$Label=$Label.Insert(($Label.Length),"`"")
$Label=$Label.Insert(0,"`"")
$Value=$Data[1].Trim()
$Value=$Value.Insert(($Value.Length),"`"")
$Value=$Value.Insert(0,"`"")
$CurrentUserHashTable.Add($Label,$Value)
}
$CurrentUserHashTable However, when I use this within a script that uses a file system watcher event to discover the presence of the text file, I cannot get anything from the hash table. I can see my variables being created, ready to pass on to the .add statement. I have found a workaround for now - not using a hash table - but would love to know why I see this behaviour and suggestions for getting at the data.
Here is the code that I'm having trouble with.
$folder = 'c:\In'
$OutFolder = 'c:\Out'
$filter = '*.*'
$CurrentUserHashTable = $NULL
$FileSystemWatcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $FileSystemWatcher Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$InputFile=Get-Content $folder\$name
ForEach ($Line in $InputFile)
{
#Write-Host $Line
$CurrentUserHashTable = @{}
$Data=$Line.Split("=")
#Write-Host "Data: " $Data
$Label=$Data[0].Trim()
$Label=$Label.Insert(($Label.Length),"`"")
$Label=$Label.Insert(0,"`"")
#Write-Host "Label: " $Label
$Value=$Data[1].Trim()
$Value=$Value.Insert(($Value.Length),"`"")
$Value=$Value.Insert(0,"`"")
#Write-Host "Value: " $Value
$CurrentUserHashTable.Add($Label,$Value)
}
$CurrentUserHashTable
Move-Item $folder\$name $OutFolder -Force
}
#Label: "ID"
#Value: "abc00001"
#Label: "PID"
#Value: "00001"
#Label: "Title"
#Value: "Mr"
#Label: "Initials"
#Value: "XY"
#Label: "Forename"
#Value: "Mickey"
#Label: "Surname"
#Value: "Mouse"
#Label: "Siteabbrev"
#Value: "UK"
#Label: "Status"
#Value: "STAFF"
#Label: "BUabbrev"
#Value: "NOBU"
#Label: "Department"
#Value: "Finance"Note the commented bits at the bottom are the output of
Write-Host "Value: " $Value
and
Write-Host "Label: " $Label
Also, if the following are placed within the loop, I see all data items being returned, so I know that they are added to the hash table. If they are added outside the loop, I just get the final entry "Department"
Write-Host "Keys:" $CurrentUserHashTable.Keys Write-Host "Values:" $CurrentUserHashTable.Values
Many thanks,
Jon