メインコンテンツへスキップ
見出し画像

PowerShell はじめました #48 Win32APIでINIファイル読み書き

    ども。

    ちょっとINIファイル使いたいご用事がありましてね。
    でも自分でセクションやらなんやらまで処理するのつらいなーって。

    Win32APIになんかあったなーっての思い出したんですよ。

    コパ先生にコード出してーって頼んだら動いちゃったので、そのまま載せます。


    PowerShellは5.1です。


    とりあえず使いやすいように関数化してっておねがいしたら、
    Get-IniValue と Set-IniValue を用意してくれました。

    # INIファイルAPI
    Add-Type @"
    using System;
    using System.Text;
    using System.Runtime.InteropServices;
    
    public class IniAPI {
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        public static extern int GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            StringBuilder lpReturnedString,
            int nSize,
            string lpFileName);
    
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        public static extern bool WritePrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpString,
            string lpFileName);
    }
    "@
    
    
    # iniファイル読込
    function Get-IniValue {
        param(
            [string]$Section,
            [string]$Key,
            [string]$Path
        )
        $sb = New-Object System.Text.StringBuilder 1024
        [IniAPI]::GetPrivateProfileString($Section, $Key, "", $sb, $sb.Capacity, $Path) | Out-Null
        return $sb.ToString()
    }
    
    # iniファイル書込
    function Set-IniValue {
        param(
            [string]$Section,
            [string]$Key,
            [string]$Value,
            [string]$Path
        )
        [IniAPI]::WritePrivateProfileString($Section, $Key, $Value, $Path) | Out-Null
    }
    

    では!


    はじめました まとめました

     
     
    こんにちは。 大した知識があるわけではありませんが、物や物事の仕組みを考える時間が好きです。 最近はPowerShellが楽しくなってきています。 (サムネ画像はAIで生成しています)

    あなたへのおすすめ