LoginSignup
7
8

More than 5 years have passed since last update.

PowerShell (with C#) でINIファイルの読み書き

Last updated at Posted at 2016-12-18
settings.ini
[section1]
Key1=Value1
Key2=Value2
Key3=Value3
; ...

次の Win32API の力を借りる。

  1. まず C# で上記の関数をラップする。

    • GetPrivateProfileString → ReadFromIniFile
    • WritePrivateProfileString → WriteToIniFile
    IniFileManager.cs
    using System.Runtime.InteropServices;
    using System.Text;
    
    public class IniFileManager
    {
        [DllImport("KERNEL32.DLL")]
        private static extern uint GetPrivateProfileString(string lpAppName,
                                                           string lpKeyName,
                                                           string lpDefault,
                                                           StringBuilder lpReturnedString,
                                                           uint nSize,
                                                           string lpFileName);
    
        [DllImport("KERNEL32.DLL")]
        private static extern uint WritePrivateProfileString(string lpAppName,
                                                             string lpKeyName,
                                                             string lpString,
                                                             string lpFileName);
    
        public static string ReadFromIniFile(string iniFilePath, string appName, string key)
        {
            StringBuilder sb = new StringBuilder(1024);
    
            GetPrivateProfileString(appName, key, null, sb, (uint)sb.Capacity, iniFilePath);
    
            return sb.ToString();
        }
    
        public static void WriteToIniFile(string iniFilePath, string appName, string key, string value)
        {
            WritePrivateProfileString(appName, key, value, iniFilePath);
        }
    }
    
  2. PowerShell からこれを使う。

    Add-Type -Path IniFileManager.cs
    
    • INIファイル (settings.ini) に書き込む

      [IniFileManager]::WriteToIniFile("C:\Path\to\settings.ini", "ThisApplication", "SomeKey", "SomeValue")
      
      結果(settings.ini)
      [ThisApplication]
      SomeKey=SomeValue
      
    • INIファイルから読み込む

      [IniFileManager]::ReadFromIniFile("C:\Path\to\settings.ini", "ThisApplication", "SomeKey")
      
      結果
      SomeValue
      

追記

単に読み込むだけなら、ConvertFrom-StringDataを使ったほうがお手軽かもしれない。

Get-Content settings.ini | where { $_ -match ".*=.*" } | ConvertFrom-StringData
結果
Name                           Value
----                           -----
SomeKey                        SomeValue
7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8