1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

特定のポートを使用するプロセスをkillするPowerShellコマンド

Posted at

本旨

ワンライナー

Get-Process -Id (Get-NetTCPConnection -LocalPort PORT).OwningProcess | Stop-Process

※PORTを開放したいポート番号で置き換える

スクリプト

killport PORT

といったコマンドで実行するpowershellスクリプト

function Stop-ProcessByLocalPort ([parameter(mandatory)][uint16]$port) {
    $conn = Get-NetTCPConnection -LocalPort $port 2>$null
    if($conn.OwningProcess -lt 1){
        Write-Output "ポート $port は使用されていません。"
        return;
    }
    $proc = Get-Process -Id $conn.OwningProcess
    Write-Output "$($proc.ProcessName)を停止しますか?"
    $allow = Read-Host "Y/N"
    if($allow -eq "y"){
        Stop-Process $proc
    }
    Else {
        Write-Output "操作がキャンセルされました。"
    }
}

Set-Alias killport Stop-ProcessByLocalPort

好みですが、こちらではkillするプロセス名で確認をとるように。
※より良い書き方があれば教えてください。

スクリプトについて補足

作成したスクリプトをpowershellで使えるようにする

PowerShellのスクリプトを実行したことがないのであれば、事前に管理者権限のPowerShellで、

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

等のコマンドで実行ポリシーを変更してスクリプトを実行できるようにする。

その上で、上記のスクリプトをkillport.ps1として保存した場合は、powershellでそのkillport.ps1を実行すれば良い。

ただ、使用する度にkillport.ps1を実行するのでは不便なので、powershell起動時に読み込まれる環境設定用のスクリプト(PowerShellのプロファイル)に直接スクリプトを記載するか、読み込み用の処理を記載するのが便利。

(おまけ)PowerShellのプロファイルを編集する

プロファイルを使用したことがない場合はファイルが存在しないので作成する必要がある。

powershellが起動時に自動で読み込むスクリプトのパスは$profileで取得できるので、

New-Item $profile -force -type file

でファイルを作成して、

explorer (Split-Path $profile -Parent)

でプロファイルの親フォルダを開いてお好みのエディタで編集することができる。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?