Archive for the ‘PowerShell’ Category

  1. Hello, Connector/NET(PowerShell) World!

    Posted on 4月 6th, 2013 by cx20

    Connector/NET(PowerShell)

    Connector/NET は、.NET ベースの MySQL 接続用 API である。
    以下は PowerShell による Connector/NET ライブラリを使用した MySQL への接続例となっている。

    ソースコード(PowerShell + Connector/NET + MySQL)

    [void][Reflection.Assembly]::LoadWithPartialName("MySql.Data")
    $conStr = "server=localhost;user id=root;password=P@ssW0rd"
    $sqlStr = "SELECT 'Hello, Connector/NET World!' AS Message"
    $con = New-Object MySql.Data.MySqlClient.MySqlConnection($conStr)
    $cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sqlStr, $con)
    $con.Open()
    $reader = $cmd.ExecuteReader()
    while ( $reader.read() )
    {
        $reader.getName(0)
        "---------------------"
        $reader[0]
    }
    $con.Close()

    実行方法

    C:¥> powershell -file Hello.ps1

    実行結果

    MESSAGE
    ---------------------
    Hello, Connector/NET World!
  2. Hello, ADO.NET(PowerShell) World!

    Posted on 9月 10th, 2012 by cx20

    ADO.NET(PowerShell)

    ADO.NET(ActiveX Data Objects .NET)は、ADO の後継で .NET ベースの DBMS 接続用 API である。
    .NET データプロバイダを介することで様々な DBMS への接続が可能となっている。
    .NET Framework 標準で使用できる .NET データプロバイダとしては、以下のようなプロバイダがある。

    データプロバイダ名 説明
    System.Data.SqlClient Microsoft SQL Server
    System.Data.OleDb OLE DB
    System.Data.Odbc ODBC
    System.Data.OracleClient Oracle

    ソースコード(PowerShell + ADO.NET + OLE DB + Jet データベース)

    $conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=hello.mdb;"
    $sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message"
    $con = New-Object System.Data.OleDb.OleDbConnection($conStr)
    $cmd = New-Object System.Data.OleDb.OleDbCommand($sqlStr, $con)
    $con.Open()
    $reader = $cmd.ExecuteReader()
    while ( $reader.read() )
    {
        $reader.getName(0)
        "---------------------"
        $reader[0]
    }
    $con.Close()

    ソースコード(PowerShell + ADO.NET + OLE DB + ACE データベース)

    $conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=hello.accdb;"
    $sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message"
    $con = New-Object System.Data.OleDb.OleDbConnection($conStr)
    $cmd = New-Object System.Data.OleDb.OleDbCommand($sqlStr, $con)
    $con.Open()
    $reader = $cmd.ExecuteReader()
    while ( $reader.read() )
    {
        $reader.getName(0)
        "---------------------"
        $reader[0]
    }
    $con.Close()

    ソースコード(PowerShell + ADO.NET + SQL Server)

    $conStr = "SERVER=(local);DATABASE=master;UID=sa;PWD=P@ssW0rd"
    $sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message"
    $con = New-Object System.Data.SqlClient.SqlConnection($conStr)
    $cmd = New-Object System.Data.SqlClient.SqlCommand($sqlStr, $con)
    $con.Open()
    $reader = $cmd.ExecuteReader()
    while ( $reader.read() )
    {
        $reader.getName(0)
        "---------------------"
        $reader[0]
    }
    $con.Close()

    ソースコード(PowerShell + ADO.NET + Oracle)

    [void][Reflection.Assembly]::LoadWithPartialName("System.Data.OracleClient")
    $conStr = "Data Source=ORCL;User ID=scott;Password=tiger"
    $sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message FROM DUAL"
    $con = New-Object System.Data.OracleClient.OracleConnection($conStr)
    $cmd = New-Object System.Data.OracleClient.OracleCommand($sqlStr, $con)
    $con.Open()
    $reader = $cmd.ExecuteReader()
    while ( $reader.read() )
    {
        $reader.getName(0)
        "---------------------"
        $reader[0]
    }
    $con.Close()

    ソースコード(PowerShell + ADO.NET + ODBC + MySQL)

    [void][Reflection.Assembly]::LoadWithPartialName("System.Data.Odbc")
    $conStr = "Driver={MySQL ODBC 5.1 Driver};Server=localhost;UID=root;PWD=P@ssW0rd"
    $sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message"
    $con = New-Object System.Data.Odbc.OdbcConnection($conStr)
    $cmd = New-Object System.Data.Odbc.OdbcCommand($sqlStr, $con)
    $con.Open()
    $reader = $cmd.ExecuteReader()
    while ( $reader.read() )
    {
        $reader.getName(0)
        "---------------------"
        $reader[0]
    }
    $con.Close()

    実行方法

    C:¥> powershell -file Hello.ps1

    実行結果

    Message
    ---------------------
    Hello, ADO.NET World!
  3. Hello, Win32 GUI(UWSC) World!

    Posted on 7月 17th, 2012 by cx20

    Win32 GUI(UWSC)

    Win32 アプリケーションは Windows 標準 API である Win32 API を使用した Windows アプリケーションである。
    以下は UWSC にて PowerShell を呼び出す機能により C# を使用した Win32 GUI アプリケーション の例となっている。

    ソースコード(UWSC + PowerShell + C# + Win32)

    Option Explicit
     
    Main()
     
    Procedure Main()
        PowerShell( helloBlock, True, True )
    FEnd
     
    TextBlock helloBlock
        $source = @"
    using System;
    using System.Runtime.InteropServices;
     
    public class Hello
    {
        [StructLayout(LayoutKind.Sequential)]
        struct POINT
        {
            public int x;
            public int y;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct MSG
        {
            public IntPtr hwnd;
            public uint message;
            public IntPtr wParam;
            public IntPtr lParam;
            public uint time;
            public POINT pt;
        }
     
        delegate IntPtr WndProcDelgate(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct WNDCLASSEX
        {
            public uint cbSize;
            public uint style;
            public WndProcDelgate lpfnWndProc;
            public Int32 cbClsExtra;
            public Int32 cbWndExtra;
            public IntPtr hInstance;
            public IntPtr hIcon;
            public IntPtr hCursor;
            public IntPtr hbrBackground;
            public string lpszMenuName;
            public string lpszClassName;
            public IntPtr hIconSm;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct PAINTSTRUCT
        {
            public IntPtr hdc;
            public int fErase;
            public RECT rcPaint;
            public int fRestore;
            public int fIncUpdate;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
            public byte[] rgbReserved;
        }
     
        const uint WS_OVERLAPPED = 0x00000000;
        const uint WS_POPUP = 0x80000000;
        const uint WS_CHILD = 0x40000000;
        const uint WS_MINIMIZE = 0x20000000;
        const uint WS_VISIBLE = 0x10000000;
        const uint WS_DISABLED = 0x08000000;
        const uint WS_CLIPSIBLINGS = 0x04000000;
        const uint WS_CLIPCHILDREN = 0x02000000;
        const uint WS_MAXIMIZE = 0x01000000;
        const uint WS_CAPTION = 0x00C00000; // WS_BORDER | WS_DLGFRAME
        const uint WS_BORDER = 0x00800000;
        const uint WS_DLGFRAME = 0x00400000;
        const uint WS_VSCROLL = 0x00200000;
        const uint WS_HSCROLL = 0x00100000;
        const uint WS_SYSMENU = 0x00080000;
        const uint WS_THICKFRAME = 0x00040000;
        const uint WS_GROUP = 0x00020000;
        const uint WS_TABSTOP = 0x00010000;
     
        const uint WS_MINIMIZEBOX = 0x00020000;
        const uint WS_MAXIMIZEBOX = 0x00010000;
     
        const uint WS_TILED = WS_OVERLAPPED;
        const uint WS_ICONIC = WS_MINIMIZE;
        const uint WS_SIZEBOX = WS_THICKFRAME;
        const uint WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;
     
        const uint WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
        const uint WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU;
        const uint WS_CHILDWINDOW = WS_CHILD;
     
        const uint WM_CREATE = 0x0001;
        const uint WM_DESTROY = 0x0002;
        const uint WM_PAINT = 0x000F;
        const uint WM_CLOSE = 0x0010;
        const uint WM_COMMAND = 0x0111;
     
        const uint COLOR_WINDOW = 5;
        const uint COLOR_BTNFACE = 15;
     
        const uint CS_VREDRAW = 0x0001;
        const uint CS_HREDRAW = 0x0002;
     
        const int CW_USEDEFAULT = -2147483648; // ((uint)0x80000000)
     
        const uint SW_SHOWDEFAULT = 10;
     
        const int IDI_APPLICATION = 32512;
        const int IDC_ARROW = 32512;
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadIcon(IntPtr hInstance, IntPtr lpIconName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern short RegisterClassEx(ref WNDCLASSEX pcWndClassEx);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr CreateWindowEx(uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool UpdateWindow(IntPtr hWnd);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int TranslateMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DispatchMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern void PostQuitMessage(int nExitCode);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DefWindowProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr BeginPaint(IntPtr hWnd, out PAINTSTRUCT lpPaint);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint);
     
        [DllImport("gdi32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr TextOut( IntPtr hdc, int x, int y, string lpString, int nCount );
     
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr GetModuleHandle(string lpModuleName);
     
        static IntPtr WndProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam)
        {
            PAINTSTRUCT ps = new PAINTSTRUCT();
            IntPtr hdc;
            string strMessage = "Hello, Win32 GUI(UWSC) World!";
     
            switch (uMsg)
            {
                case WM_PAINT:
                    hdc = BeginPaint( hWnd, out ps );
                    TextOut( hdc, 0, 0, strMessage, strMessage.Length );
                    EndPaint( hWnd, ref ps );
                    break;
                case WM_DESTROY:
                    PostQuitMessage(0);
                    break;
                default:
                    return DefWindowProc(hWnd, uMsg, wParam, lParam);
            }
     
            return IntPtr.Zero;
        }
     
        static int WinMain()
        {
            IntPtr hInstance = Marshal.GetHINSTANCE(typeof(Hello).Module);
            const string CLASS_NAME = "helloWindow";
            const string WINDOW_NAME = "Hello, World!";
     
            WNDCLASSEX wcex = new WNDCLASSEX();
            wcex.cbSize = (uint)Marshal.SizeOf(wcex);
            wcex.style = CS_HREDRAW | CS_VREDRAW;
            wcex.lpfnWndProc = new WndProcDelgate(WndProc);
            wcex.cbClsExtra = 0;
            wcex.cbWndExtra = 0;
            wcex.hInstance = hInstance;
            wcex.hIcon = LoadIcon(hInstance, new IntPtr(IDI_APPLICATION));
            wcex.hCursor = LoadIcon(hInstance, new IntPtr(IDC_ARROW));
            wcex.hbrBackground = new IntPtr(COLOR_WINDOW + 1);
            wcex.lpszMenuName = "";
            wcex.lpszClassName = CLASS_NAME;
            wcex.hIconSm = IntPtr.Zero;
     
            RegisterClassEx(ref wcex);
     
            IntPtr hWnd = CreateWindowEx(
                0,
                wcex.lpszClassName,
                WINDOW_NAME,
                WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                640,
                480,
                IntPtr.Zero,
                IntPtr.Zero,
                wcex.hInstance,
                IntPtr.Zero);
     
            ShowWindow(hWnd, SW_SHOWDEFAULT);
            UpdateWindow(hWnd);
     
            MSG msg = new MSG();
            while (GetMessage(out msg, IntPtr.Zero, 0, 0) != 0)
            {
                TranslateMessage(ref msg);
                DispatchMessage(ref msg);
            }
     
            return (int)msg.wParam;
        }
     
        [STAThread]
        public static int Main()
        {
            return WinMain();
        }
    }
    "@
        Add-Type -Language CSharp -TypeDefinition $source -ReferencedAssemblies ("System.Drawing", "System.Windows.Forms" )
        [void][Hello]::Main()
    EndTextBlock

    実行方法

    C:¥> uwsc /K hello.uws

    実行結果

    +------------------------------------------+
    |Hello, World!                    [_][~][X]|
    +------------------------------------------+
    |Hello, Win32 GUI(UWSC) World!             |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    +------------------------------------------+
  4. Hello, Win32 GUI(PowerShell) World!

    Posted on 7月 12th, 2012 by cx20

    Win32 GUI(PowerShell)

    Win32 アプリケーションは Windows 標準 API である Win32 API を使用した Windows アプリケーションである。
    以下は PowerShell にて Add-Type コマンドレット経由で C# を呼び出すことにより Win32 API を使用した GUI アプリケーション の例となっている。

    ソースコード

    $source = @"
    using System;
    using System.Runtime.InteropServices;
     
    public class Hello
    {
        [StructLayout(LayoutKind.Sequential)]
        struct POINT
        {
            public int x;
            public int y;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct MSG
        {
            public IntPtr hwnd;
            public uint message;
            public IntPtr wParam;
            public IntPtr lParam;
            public uint time;
            public POINT pt;
        }
     
        delegate IntPtr WndProcDelgate(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct WNDCLASSEX
        {
            public uint cbSize;
            public uint style;
            public WndProcDelgate lpfnWndProc;
            public Int32 cbClsExtra;
            public Int32 cbWndExtra;
            public IntPtr hInstance;
            public IntPtr hIcon;
            public IntPtr hCursor;
            public IntPtr hbrBackground;
            public string lpszMenuName;
            public string lpszClassName;
            public IntPtr hIconSm;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct PAINTSTRUCT
        {
            public IntPtr hdc;
            public int fErase;
            public RECT rcPaint;
            public int fRestore;
            public int fIncUpdate;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
            public byte[] rgbReserved;
        }
     
        const uint WS_OVERLAPPED = 0x00000000;
        const uint WS_POPUP = 0x80000000;
        const uint WS_CHILD = 0x40000000;
        const uint WS_MINIMIZE = 0x20000000;
        const uint WS_VISIBLE = 0x10000000;
        const uint WS_DISABLED = 0x08000000;
        const uint WS_CLIPSIBLINGS = 0x04000000;
        const uint WS_CLIPCHILDREN = 0x02000000;
        const uint WS_MAXIMIZE = 0x01000000;
        const uint WS_CAPTION = 0x00C00000; // WS_BORDER | WS_DLGFRAME
        const uint WS_BORDER = 0x00800000;
        const uint WS_DLGFRAME = 0x00400000;
        const uint WS_VSCROLL = 0x00200000;
        const uint WS_HSCROLL = 0x00100000;
        const uint WS_SYSMENU = 0x00080000;
        const uint WS_THICKFRAME = 0x00040000;
        const uint WS_GROUP = 0x00020000;
        const uint WS_TABSTOP = 0x00010000;
     
        const uint WS_MINIMIZEBOX = 0x00020000;
        const uint WS_MAXIMIZEBOX = 0x00010000;
     
        const uint WS_TILED = WS_OVERLAPPED;
        const uint WS_ICONIC = WS_MINIMIZE;
        const uint WS_SIZEBOX = WS_THICKFRAME;
        const uint WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;
     
        const uint WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
        const uint WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU;
        const uint WS_CHILDWINDOW = WS_CHILD;
     
        const uint WM_CREATE = 0x0001;
        const uint WM_DESTROY = 0x0002;
        const uint WM_PAINT = 0x000F;
        const uint WM_CLOSE = 0x0010;
        const uint WM_COMMAND = 0x0111;
     
        const uint COLOR_WINDOW = 5;
        const uint COLOR_BTNFACE = 15;
     
        const uint CS_VREDRAW = 0x0001;
        const uint CS_HREDRAW = 0x0002;
     
        const int CW_USEDEFAULT = -2147483648; // ((uint)0x80000000)
     
        const uint SW_SHOWDEFAULT = 10;
     
        const int IDI_APPLICATION = 32512;
        const int IDC_ARROW = 32512;
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadIcon(IntPtr hInstance, IntPtr lpIconName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern short RegisterClassEx(ref WNDCLASSEX pcWndClassEx);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr CreateWindowEx(uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool UpdateWindow(IntPtr hWnd);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int TranslateMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DispatchMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern void PostQuitMessage(int nExitCode);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DefWindowProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr BeginPaint(IntPtr hWnd, out PAINTSTRUCT lpPaint);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint);
     
        [DllImport("gdi32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr TextOut( IntPtr hdc, int x, int y, string lpString, int nCount );
     
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr GetModuleHandle(string lpModuleName);
     
        static IntPtr WndProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam)
        {
            PAINTSTRUCT ps = new PAINTSTRUCT();
            IntPtr hdc;
            string strMessage = "Hello, Win32 GUI(PowerShell) World!";
     
            switch (uMsg)
            {
                case WM_PAINT:
                    hdc = BeginPaint( hWnd, out ps );
                    TextOut( hdc, 0, 0, strMessage, strMessage.Length );
                    EndPaint( hWnd, ref ps );
                    break;
                case WM_DESTROY:
                    PostQuitMessage(0);
                    break;
                default:
                    return DefWindowProc(hWnd, uMsg, wParam, lParam);
            }
     
            return IntPtr.Zero;
        }
     
        static int WinMain()
        {
            IntPtr hInstance = Marshal.GetHINSTANCE(typeof(Hello).Module);
            const string CLASS_NAME = "helloWindow";
            const string WINDOW_NAME = "Hello, World!";
     
            WNDCLASSEX wcex = new WNDCLASSEX();
            wcex.cbSize = (uint)Marshal.SizeOf(wcex);
            wcex.style = CS_HREDRAW | CS_VREDRAW;
            wcex.lpfnWndProc = new WndProcDelgate(WndProc);
            wcex.cbClsExtra = 0;
            wcex.cbWndExtra = 0;
            wcex.hInstance = hInstance;
            wcex.hIcon = LoadIcon(hInstance, new IntPtr(IDI_APPLICATION));
            wcex.hCursor = LoadIcon(hInstance, new IntPtr(IDC_ARROW));
            wcex.hbrBackground = new IntPtr(COLOR_WINDOW + 1);
            wcex.lpszMenuName = "";
            wcex.lpszClassName = CLASS_NAME;
            wcex.hIconSm = IntPtr.Zero;
     
            RegisterClassEx(ref wcex);
     
            IntPtr hWnd = CreateWindowEx(
                0,
                wcex.lpszClassName,
                WINDOW_NAME,
                WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                640,
                480,
                IntPtr.Zero,
                IntPtr.Zero,
                wcex.hInstance,
                IntPtr.Zero);
     
            ShowWindow(hWnd, SW_SHOWDEFAULT);
            UpdateWindow(hWnd);
     
            MSG msg = new MSG();
            while (GetMessage(out msg, IntPtr.Zero, 0, 0) != 0)
            {
                TranslateMessage(ref msg);
                DispatchMessage(ref msg);
            }
     
            return (int)msg.wParam;
        }
     
        [STAThread]
        public static int Main()
        {
            return WinMain();
        }
    }
    "@
    Add-Type -Language CSharp -TypeDefinition $source -ReferencedAssemblies ("System.Drawing", "System.Windows.Forms" )
    [void][Hello]::Main()

    実行方法

    C:¥> powershell -file Hello.ps1

    実行結果

    +------------------------------------------+
    |Hello, World!                    [_][~][X]|
    +------------------------------------------+
    |Hello, Win32 GUI(PowerShell) World!       |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    +------------------------------------------+
  5. Hello, Windows Forms(PowerShell) World!

    Posted on 6月 7th, 2012 by cx20

    Windows Forms(PowerShell)

    Windows フォーム(Windows Forms)は .NET Framework におけるユーザーインターフェイス基盤である。Windows アプリケーションにおけるウィンドウやダイアログに対応する。
    以下は PowerShell における Windows フォーム の例となっている。

    ソースコード(PowerShell のみ)

    [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    $form = New-Object Windows.Forms.Form
    $form.Size = New-Object Drawing.Size 640,480
    $form.Text = "Hello, World!"
    $label1 = New-Object Windows.Forms.Label
    $label1.Size = New-Object Drawing.Size 320, 20
    $label1.Text = "Hello, Windows Forms(PowerShell) World!"
    $form.Controls.Add( $label1 )
    $form.ShowDialog()

    なお、PowerShell 2.0 から Add-Type コマンドレットを用いることにより C# や VB.NET のコードも呼び出せるようになっている。

    ソースコード(PowerShell + C#)

    $source = @"
    using System;
    using System.Drawing;
    using System.Windows.Forms;
     
    public class HelloForm : Form
    {
        public HelloForm()
        {
            this.Size = new Size( 640, 480 );
            this.Text = "Hello, World!";
     
            Label label1 = new Label();
            label1.Size = new Size( 320, 20 );
            label1.Text = "Hello, Windows Forms(PowerShell) World!";
     
            this.Controls.Add( label1 );
        }
        [STAThread]
        public static void Main()
        {
            HelloForm form = new HelloForm();
            Application.Run(form);
        }
    }
    "@
    Add-Type -Language CSharp -TypeDefinition $source -ReferencedAssemblies ("System.Drawing", "System.Windows.Forms" )
    [HelloForm]::Main()

    ソースコード(PowerShell + VB.NET)

    $source = @"
    Imports System
    Imports System.Drawing
    Imports System.Windows.Forms
     
    Public Class HelloForm
        Inherits Form
     
        Public Sub New()
            Me.Size = New Size( 640, 480 )
            Me.Text = "Hello, World!"
     
            Dim label1 As New Label
            label1.Size = New Size( 320, 20 )
            label1.Text = "Hello, Windows Forms(PowerShell) World!"
     
            Me.Controls.Add( label1 )
        End Sub
     
        <STAThread> _
        Shared Sub Main()
            Dim form As New HelloForm()
            Application.Run(form)
        End Sub
    End Class
    "@
    Add-Type -Language VisualBasic -TypeDefinition $source -ReferencedAssemblies ("System.Drawing", "System.Windows.Forms" )
    [HelloForm]::Main()

    実行方法

    C:¥> PowerShell -File Hello.ps1

    実行結果

    +------------------------------------------+
    |Hello, World!                    [_][~][X]|
    +------------------------------------------+
    |Hello, Windows Forms(PowerShell) World!   |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    +------------------------------------------+
  6. Hello, COM(PowerShell) World!

    Posted on 5月 16th, 2012 by cx20

    COM(PowerShell)

    COM(Component Object Model)はマイクロソフトの提唱するプログラム部品の仕様である。
    COM を用いて開発された部品であれば言語を問わず利用することができる。
    以下は PowerShell による COM クライアント(実行時バインディング)の例となっている。

    ソースコード

    $ssfWINDOWS = 36
     
    function Main() {
        $shell = new-object -comobject Shell.Application
        $folder = $shell.BrowseForFolder( 0, "Hello, COM(PowerShell) World!", 0, $ssfWINDOWS )
    }
     
    Main

    実行方法

    C:¥> PowerShell -File hello.ps1
    

    実行結果

    +----------------------------------------+
    |Browse For Folder                    [X]|
    +----------------------------------------+
    | Hello, COM(PowerShell) Wolrd!          |
    |                                        |
    | +------------------------------------+ |
    | |[Windows]                           | |
    | | +[addins]                          | |
    | | +[AppCompat]                       | |
    | | +[AppPatch]                        | |
    | | +[assembly]                        | |
    | |     :                              | |
    | |     :                              | |
    | |     :                              | |
    | +------------------------------------+ |
    | [Make New Folder]    [  OK  ] [Cancel] |
    +----------------------------------------+
  7. Hello, Win32 API(PowerShell) World!

    Posted on 4月 22nd, 2012 by cx20

    Win32 API(PowerShell)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は PowerShell での P/Invoke による呼出し例である。

    ソースコード

    function Main
    {
       MessageBox 0 "Hello, Win32 API(PowerShell)!" "Hello, World!" 0
    }
     
    ## Invoke a Win32 P/Invoke call. 
    ## http://www.leeholmes.com/blog/2006/07/21/get-the-owner-of-a-process-in-powershell-%e2%80%93-pinvoke-and-refout-parameters/
    function Invoke-Win32([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") 
     
       ## Define the actual P/Invoke method
       $method = $type.DefineMethod($methodName, 'Public,HideBySig,Static,PinvokeImpl',  
          $returnType, $parameterTypes) 
     
       ## 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,  
          $parameters) 
    } 
     
    function MessageBox([Int32] $hWnd, [String] $lpText, [String] $lpCaption, [Int32] $uType) 
    { 
       $parameterTypes = [Int32], [String], [String], [Int32]
       $parameters = $hWnd, $lpText, $lpCaption, $uType
     
       Invoke-Win32 "user32.dll" ([Int32]) "MessageBoxA" $parameterTypes $parameters
    } 
     
    . Main

    実行方法

    C:¥> PowerShell -file hello.ps1

    実行結果

    ---------------------------
    Hello, World!
    ---------------------------
    Hello, Win32 API(PowerShell) World!
    ---------------------------
    OK   
    ---------------------------
  8. Hello, PowerShell World!

    Posted on 12月 27th, 2011 by cx20

    PowerShell

    PoweShell は Windows における新しいコマンドラインシェルである。
    POSIX系シェルをベースとし、Perl や Python、PHP、C# の特徴を組み合わせた言語とされている。
    .NET Framework を基盤としており、コマンドの実行結果は .NET のオブジェクトとして処理される。

    ソースコード

    "Hello, PowerShell World!"

    ソースコード(.NET ライブラリを使用した場合)

    [Console]::WriteLine("Hello, PowerShell World!")

    事前準備(実行ポリシーを変更する方法)

    PowerShell はスクリプト実行ポリシーが設定され、既定では Restricted(実行は無効)となっている。設定を確認するには Get-ExecutionPolicy コマンドレット、変更するには Set-ExecutionPolicy コマンドレットを用いる。

    C:¥> PowerShell
    Windows PowerShell
    Copyright (C) 2009 Microsoft Corporation. All rights reserved.
    
    PS C:¥> Get-ExecutionPolicy
    Restricted
    PS C:¥> Set-ExecutionPolicy RemoteSigned
    

    実行方法

    C:¥> PowerShell -File hello.ps1
    

    実行結果

    Hello, PowerShell World!