Managing INI files with PowerShell

The question came up on the newsgroup a few days ago on how to work with INI files from PowerShell.


A lot of great answers came up (using text parsing of the INI files,) but the Windows API actually supports reading and writing of INI file entries directly through its GetPrivateProfileString and WritePrivateProfileString functions. PowerShell doesn’t support P/Invoke to the Win32 API directly, but the Invoke-Win32 script given here does: http://www.leeholmes.com/blog/GetTheOwnerOfAProcessInPowerShellPInvokeAndRefOutParameters.aspx.


Since it’s reusable, that code sits better as a script of its own, named Invoke-WindowsApi (below.)





##############################################################################
##
## Invoke-WindowsApi.ps1
##
## From PowerShell Cookbook (O’Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
## Invoke a native Windows API call that takes and returns simple data types.
##
## ie:
##
## ## Prepare the parameter types and parameters for the 
## CreateHardLink function
## $parameterTypes = [string], [string], [IntPtr]
## $parameters = [string] $filename, [string] $existingFilename, [IntPtr]::Zero
## 
## ## Call the CreateHardLink method in the Kernel32 DLL
## $result = Invoke-WindowsApi ”kernel32″ ([bool]) ”CreateHardLink” `
##     $parameterTypes $parameters
##
##############################################################################

param(
    [string] $dllName
    [Type$returnType
    [string] $methodName,
    [Type[]] $parameterTypes,
    [Object[]] $parameters
    )

## Begin to build the dynamic assembly
$domain = [AppDomain]::CurrentDomain
$name = New-Object Reflection.AssemblyName ‘PInvokeAssembly’
$assembly = $domain.DefineDynamicAssembly($name‘Run’)
$module = $assembly.DefineDynamicModule(‘PInvokeModule’)
$type = $module.DefineType(‘PInvokeType’“Public,BeforeFieldInit”)

## Go through all of the parameters passed to us.  As we do this,
## we clone the user’s inputs into another array that we will use for
## the P/Invoke call.  
$inputParameters = @()
$refParameters = @()

for($counter = 1$counter -le $parameterTypes.Length; $counter++)
{
   ## If an item is a PSReference, then the user 
   ## wants an [out] parameter.
   if($parameterTypes[$counter - 1] -eq [Ref])
   {
      ## Remember which parameters are used for [Out] parameters
      $refParameters += $counter

      ## On the cloned array, we replace the PSReference type with the 
      ## .Net reference type that represents the value of the PSReference, 
      ## and the value with the value held by the PSReference.
      $parameterTypes[$counter - 1] = 
         $parameters[$counter - 1].Value.GetType().MakeByRefType()
      $inputParameters += $parameters[$counter - 1].Value
   }
   else
   {
      ## Otherwise, just add their actual parameter to the
      ## input array.
      $inputParameters += $parameters[$counter - 1]
   }
}

## Define the actual P/Invoke method, adding the [Out]
## attribute for any parameters that were originally [Ref] 
## parameters.
$method = $type.DefineMethod($methodName‘Public,HideBySig,Static,PinvokeImpl’,
    $returnType$parameterTypes)
foreach($refParameter in $refParameters)
{
   [void] $method.DefineParameter($refParameter“Out”$null)
}

## Apply the P/Invoke constructor
$ctor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([string])
$attr = New-Object Reflection.Emit.CustomAttributeBuilder $ctor$dllName
$method.SetCustomAttribute($attr)

## Create the temporary type, and invoke the method.
$realType = $type.CreateType()

$realType.InvokeMember($methodName‘Public,Static,InvokeMethod’$null$null
    $inputParameters)

## Finally, go through all of the reference parameters, and update the
## values of the PSReference objects that the user passed in.
foreach($refParameter in $refParameters)
{
   $parameters[$refParameter - 1].Value = $inputParameters[$refParameter - 1]
}

 

Using this script, you can easily wrap these APIs in a more friendly PowerShell scripts.




##############################################################################
##
## Get-PrivateProfileString.ps1
##
## Get an entry from an INI file.
##
## ie:
##
##  PS >Get-PrivateProfileString.ps1 C:\winnt\system32\ntfrsrep.ini text DEV_CTR_24_009_HELP
##
##############################################################################

param(
    $file,
    $category,
    $key)

## Prepare the parameter types and parameter values for the Invoke-WindowsApi script
$returnValue = New-Object System.Text.StringBuilder 500
$parameterTypes = [string], [string], [string], [System.Text.StringBuilder], [int], [string]
$parameters = [string] $category, [string] $key, [string] “”

   [System.Text.StringBuilder] $returnValue, [int] $returnValue.Capacity, [string] $file

## Invoke the API
[void] (Invoke-WindowsApi “kernel32.dll” ([UInt32]) “GetPrivateProfileString” `

   $parameterTypes $parameters)

## And return the results
$returnValue.ToString()

and




##############################################################################
##
## Set-PrivateProfileString.ps1
##
## Set an entry from an INI file.
##
## ie:
##
##  PS >copy C:\winnt\system32\ntfrsrep.ini c:\temp\
##  PS >Set-PrivateProfileString.ps1 C:\temp\ntfrsrep.ini text `
##  >> DEV_CTR_24_009_HELP ”New Value”
##  >>
##  PS >Get-PrivateProfileString.ps1 C:\temp\ntfrsrep.ini text DEV_CTR_24_009_HELP
##  New Value
##  PS >Set-PrivateProfileString.ps1 C:\temp\ntfrsrep.ini NEW_SECTION `
##  >> NewItem ”Entirely New Value”
##  >>
##  PS >Get-PrivateProfileString.ps1 C:\temp\ntfrsrep.ini NEW_SECTION NewItem
##  Entirely New Value
##
##############################################################################

param(
    $file,
    $category,
    $key,
    $value)

## Prepare the parameter types and parameter values for the Invoke-WindowsApi script
$parameterTypes = [string], [string], [string], [string]
$parameters = [string] $category, [string] $key, [string] $value, [string] $file

## Invoke the API
[void] (Invoke-WindowsApi “kernel32.dll” ([UInt32]) “WritePrivateProfileString” $parameterTypes $parameters)

9 Responses to “Managing INI files with PowerShell”

  1. Andreas Guther writes:

    Hi,

    I am having problems getting this to work. I created three files with the given names and copied the content as found on this post into the appropriate file. I changed the two usage files for writing and reading to call the InvokdWindowsApi to the following at the end since I am running the scripts within a single folder:

    [void] (./Invoke-WindowsApi "kernel32.dll" ([UInt32]) "GetPrivateProfileString" $parameterTypes $parameters).

    I created a small ini file with the following content:

    PS 72# gc ini2.ini
    [section1]
    key1=value1

    If I call the script Get-PrivateProfileString I get an empty output:

    PS 73# .\Get-PrivateProfileString ini2.ini section1 key1

    [C:\dev\powershell]
    PS 74#

    The content of the folder I am running the script:

    [C:\dev\powershell]
    PS 81# ls

    Directory: Microsoft.PowerShell.Core\FileSystem::C:\dev\powershell

    Mode LastWriteTime Length Name
    —- ————- —— —-
    -a— 4/12/2008 1:18 PM 987 Get-PrivateProfileString.ps1
    -a— 4/12/2008 1:02 PM 23 ini2.ini
    -a— 4/12/2008 12:46 PM 3377 Invoke-WindowsApi.ps1
    -a— 4/12/2008 1:00 PM 1384 Set-PrivateProfileString.ps1

    SFLTAG-G12TBB1 [13:27:40] Uptime: 4d 5h 7m 13s
    [C:\dev\powershell]
    PS 82#

    I am running under Windows XP. What am I missing here?

    Andreas

  2. David Mohundro writes:

    Thanks for the scripts!

    A year later and I’ve got a recommendation that I made for my copy of the script – a call to Resolve-Path within the Set and Get of the PrivateProfileString scripts. This way, I can pass in something like ~/application` data/etc and the API call will still work.

    I think that is the problem that Andreas ran into in the prior comment.

  3. Fábio Chicout writes:

    Very interesting solution! I’m posting about it on my blog too, and making a reference to your post. May I include the scripts there?

    Thanks

  4. Alexis MICHEL writes:

    Same problem here, doesn’t work at all, returns nothing, does nothing.

  5. Alexis MICHEL writes:

    Ok, indeed passing the fullPath for the ini file does resolve things a bit.
    Sorry

  6. Justin writes:

    For future readers, add this line after the parameters in the Get- and Set- scripts:

    #Flush out the full path to the filename
    $file=$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($file)

  7. erikcurtis writes:

    When I use this as a function such as Set-PrivateProfileString (“C:\erik.ini”,”Telnet”,”DeviceName”,”D100″)
    I get a file named erik.ini Telnet DeviceName D100
    The contents of this file are:

    []
    =

  8. Lee Holmes writes:

    Hi Erik;

    The syntax for specifying parameters in PowerShell is without the parenthesis or commas:

    Set-PrivateProfileString c:\erik.ini Telnet DeviceName D100

  9. erikcurtis writes:

    Lee,

    Thanks for that… works perfectly

Leave a Reply