0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Organization

実行中のadb server/Unity組込み/Android Studio/環境変数からadbを探して実行するPowerShell関数

はじめに

PCに複数のadbやAndroid SDKがインストールされている時に起動中のadb serverと違うバージョンのadbを実行するとadb serverが再起動してしまいます。そのため、なるべく同じバージョンのadbを実行するPowerShellの関数を作りました。

スクリプト

PowerShellの$profileに以下のスクリプトを追加してadbを実行すると以下の順番でadbコマンドを探します。

  1. 実行中のadb server
  2. 実行中のUnityから一緒にインストールしたAndroid SDKのadb
  3. Android StudioからインストールしたAndroid SDKのadb
  4. 環境変数PATHのadb
function FindAdb() {
    # find from process list
    $adbPath = Get-Process -Name "adb" -ErrorAction Ignore |
        Sort-Object Id |
        Select-Object -First 1 -ExpandProperty Path
    if ($null -ne $adbPath) {
        return $adbPath
    }

    # find from Unity in process list
    $adbPath = Get-Process -Name "Unity" -ErrorAction Ignore |
        Select-Object @{
            label="adb"
            expression={
                Join-Path (Split-Path $_.Path) "Data" "PlaybackEngines" "AndroidPlayer" "SDK" "platform-tools" "adb.exe"
            }
        } |
        Where-Object { Test-Path -Path $_.adb -PathType Leaf } |
        Select-Object -First 1 -ExpandProperty adb
    if ($null -ne $adbPath) {
        return $adbPath
    }

    # find from LOCALAPPDATA
    $adbPath = Join-Path $env:LOCALAPPDATA "Android" "Sdk" "platform-tools" "adb.exe"
    if (Test-Path -Path $adbPath -PathType Leaf) {
        return $adbPath
    }

    # find from path
    $adbPath = Get-Command -Name "adb" -CommandType Application,ExternalScript -ErrorAction Ignore |
        Select-Object -First 1 -ExpandProperty Source
    if ($null -ne $adbPath) {
        return $adbPath
    }

    # not found
    return "adb.exe"
}

function ExecAdb() {
    $adb = FindAdb
    & "$adb" $args
}
Set-Alias -Name adb -Value ExecAdb
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
0
Help us understand the problem. What are the problem?