トップ «前の日記(2017年10月08日) 最新 次の日記(2017年10月27日)» 編集

Masa's blog

検索キーワード:

2017年10月20日 Using named pipe with PowerShell [長年日記]

_ `echo' Server

$shutdown = $false
while (-not $shutdown){
        $pipe = New-Object System.IO.Pipes.NamedPipeServerStream "NamedPipeForEcho",InOut
        $pipe.WaitForConnection()
        $buf = New-Object byte[] 1024
        $loop = $true
        while($loop) {
                try {
                        $len = $pipe.Read($buf, 0, $buf.Length)
                        $cmd = [System.Text.Encoding]::Unicode.GetString($buf, 0, $len)
                        if($cmd -match '^exit|^quit|^shutdown') {
                                $loop = $false
                                if($cmd -match '^shutdown') {
                                        $shutdown = $true
                                }
                        } else {
                                $wb = [System.Text.Encoding]::Unicode.GetBytes($cmd)
                                $pipe.Write($wb, 0, $wb.Length)
                        }
                }catch{
                        $loop = $false
                }
        }
        $pipe.Close()
}

_ Client

$pipe = New-Object System.IO.Pipes.NamedPipeClientStream ".", "NamedPipeForEcho",InOut
$pipe.Connect()
$buf = New-Object byte[] 1024

$wb = [System.Text.Encoding]::Unicode.GetBytes("Hello, world.")
$pipe.Write($wb, 0, $wb.Length)
$len = $pipe.Read($buf, 0, $buf.Length)
[System.Text.Encoding]::Unicode.GetString($buf, 0, $len)

$wb = [System.Text.Encoding]::Unicode.GetBytes("exit")
$pipe.Write($wb, 0, $wb.Length)
#$wb = [System.Text.Encoding]::Unicode.GetBytes("shutdown")
#$pipe.Write($wb, 0, $wb.Length)