LoginSignup
8
5

More than 5 years have passed since last update.

PowerShellでTCPポートに標準入力からの文字列を投入

Posted at

あるTCPポートでデータが受信されるのを待っているサーバプログラムをデバッグするのに、WindowsのPowerShellからデータを投入するための簡単なスクリプトです。

参考にした記事
http://qiita.com/_norin_/items/8f534bd0531a960af5e9
http://qiita.com/alchemist/items/e6706cd425f8f5e5032e
http://tech.guitarrapc.com/entry/2013/07/21/230726
http://d.hatena.ne.jp/chabom/20100715/1279171891
https://www.ipentec.com/document/document.aspx?page=powershell-text-in

手順

スクリプト保存

以下のコードをテキストエディターで任意の場所に保存

socket_client.ps1
Clear-Host
Write-Output "「>>> : 」に続いてコマンドを投入してください。"
Write-Host "Press [q] to quit" -ForegroundColor Red -BackgroundColor White
while ($TRUE)
{
  $data = Read-Host(">>> ")
  if ($data -eq "q") {break}
  $sendData = [System.Text.Encoding]::UTF8.GetBytes($data)

  $soc = New-Object System.Net.Sockets.tcpClient
  $soc.connect("localhost", 30000) # ポート番号はサーバプログラムにあわせる
  $soc.GetStream().Write($sendData, 0, $sendData.Length)
  $soc.close()
}

PowerShell起動

Windowsキー + R 押下
powershell -ExecutionPolicy RemoteSigned

スクリプト実行

PS C:\> C:\[任意の場所]\socket_client.ps1

「>>> : 」に続いてコマンドを投入してください。
Press [q] to quit
>>> : _

[q]を押すまで標準入力からサーバプログラムにデータを投げられます。

※ソケットのOpen/Closeのタイミング等はサーバプログラム次第でループの外に記述してください。

8
5
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
8
5