I am having a file where component Baseline and component names where stored as follows
(Mailcomp@\My_PVOB) BL_2.1.0.9.5179@\My_PVOB
(OfficeComp@\My_PVOB) BL_2.1.0.17.6972@\MY_PVOB
Actually i need to Construct a hash table which may have entries like
@(Key=Mailcomp,Value=BL_2.1.0.9.5179)
@(Key=OfficeComp, Value=BL_2.1.0.17.6972)
I was trying to replace like follows
(Get-Content $BaselineFile) | foreach{ $_ -replace "@\My_PVOB[?]",''} | Out-File $BaselineFile
Then i tried to Create hash table , but the first command itself failed and i don’t know how to create hash table from file entries. Can some one help me please?
At the time of writing there are two answers (one from Shay Levy and one from jon Z) that are both close, but neither is quite right–despite the fact that Shay’s answer has already been accepted (!). Here’s why:
Issues with Shay’s code
Shay’s answer is too literal, based on an inaccurately stated requirement that specifies creating a “hash table which may have entries like” this:
But if one is going to use PowerShell syntax, that is stated incorrectly. The requirement in reality should look like this:
That is to say, the first line specifies a hash key of
Mailcompand a hash value ofBL_2.1.0.9.5179. This modified version of Shay’s code delivers precisely that:Here’s the output:
This is much easier to work with, as I can now access
$hash["Mailcomp"]or$hash["OfficeComp"]to retrieve their respective values.A second problem with Shay’s code is the hash entry creation itself (
@{ key=$matches[1]; value=$matches[2] }). That statement creates a separate “mini” hashtable for each iteration (i.e. each line of the input). It only seems to produce reasonable output because of the amalgamation of the implicit Write-Output in his code. To prove this–and to compare apples to apples–take my code above and replace the conditional with this equivalent to Shay’s code:You will find that
$hash["Mailcomp"]does not return the expectedBL_2.1.0.9.5179.Issues with Jon’s code
I like jon Z’s answer; I really do. Really. But it reminds me of the great old joke with the punchline assume we have a can opener… It is a very good solution if and only if the input is amenable to a simple delimiter. Not the case here–a regular expression (or other mechanism) is required to massage the input. In all fairness, Jon notes that explicitly by stating he is assuming some preprocessing. `Nuff said.