Emsg
Emsg

Reputation: 441

Powershell .ini file processing: retrieve values with numeric keys

I've been using Get-IniContent Powershell script written by Oliver Lipkau and it works splendidly, however the ini file I'm processing has a STAFF section in it that has numeric keys in it like this;

PS C:\Windows\System32\WindowsPowerShell\v1.0> $FileContent.STAFF

Name                           Value                                                                                                           
----                           -----                                                                                                           
11                             STFDUTY,CHAR,nvarchar,16,,NULL,,Duty roster                                                                
41                             STFKEY3,CHAR,nvarchar,8,,NULL,,Analysis key

If I put the key in single quotes like this;

Write-Output $FileContent.STAFF.'11';
Write-Output $FileContent.STAFF.'41';

I get the values back fine, however I was hoping to automate it in order to build a SQL statement, rather than hard code the keys, something like below but I can't quite seem to get it to work;

$nFields = $FileContent.STAFF.FIELDS;
for($x = 0; $x -le $nFields; $x++) 
{   Write-Output ("iteration: " + $x + " of " + $nFields);
    $xString = ("'" + $x.ToString() + "'");
    Write-Output ($FileContent.STAFF.$xString);
}

Doesn't seem to like a number directly as the third segment/argument when reading the hashtable (even though it is available in the Powershell helper) and my concatenation here with the single quotes returns nothing.

Normal String keys seem to work absolutely fine and Write-Output is temporary while I build the script.

Any tips appreciated, thanks!

Upvotes: 2

Views: 997

Answers (2)

meue
meue

Reputation: 148

Using Get-IniContent given myinifile.ini containing:

[STAFF]
11=STFDUTY,CHAR,nvarchar,16,,NULL,,Duty rosteR
41=STFKEY3,CHAR,nvarchar,8,,NULL,,Analysis key

We can use GetEnumerator() to iterate over the hash-table

$FileContent.STAFF.GetEnumerator() | ForEach-Object{
        $message = '{0}={1}' -f $_.key, $_.value
        Write-Output $message
}

Which will return:

11:STFDUTY,CHAR,nvarchar,16,,NULL,,Duty rosteR
41:STFKEY3,CHAR,nvarchar,8,,NULL,,Analysis key

Given the same principle above you could store each key and value in a separate variable, store only name or only key, and so forth.

Upvotes: 4

Micah Hunsberger
Micah Hunsberger

Reputation: 246

Try using string interpolation

Write-Output ($FileContent.STAFF."$x")

Or if it really is a hash table, you should be able to access the values using the $table[key] syntax

Write-Output ($FileContent.STAFF["$x"])

Upvotes: 3

Related Questions