2021-06-26

User Scrcpy to Connect to Android Devices over WiFi by PowerShell

只需要開啟 Android 的 USB 偵錯模式
再透過 Scrcpy 就能讓你在 PC 上連接 Android 裝置並顯示、操作
甚至可以透過無線網路來連接 (adb 內建功能)
以下為快速連接的 PowerShell Script
只要先指定好 adb.exe 及 scrcpy.exe 的 Path 就可以運作
達到快速連接的目的


$ADBPath = 'C:\scrcpy\adb.exe';
$ScrcpyPath = 'C:\scrcpy\scrcpy.exe';

$ConnectedDevices = @();
$ConnectionPrompt = '';
$ConnectionTargetIndex = 0;
$Reconnect = 'y';

foreach ($Device in ((Invoke-Expression '& $ADBPath devices -l') -Split "`r`n")) {

    if ( ($Device -notlike '*:5555*') -and (($Device -Split ' ').Count -gt 5) ) {
        $ConnectedDevices += $Device;
        $ConnectionPrompt += ([String]($ConnectionTargetIndex+1) + ' - ' + $Device + "`n");
        $ConnectionTargetIndex++;
    };
};

if ($ConnectionTargetIndex -eq 0) {
    Read-Host -Prompt 'Found no Device.'
    exit;
};

$ConnectTarget = ((Read-Host -Prompt ('Choose Device to Connect (1-' + $ConnectionTargetIndex + ")`n" + $ConnectionPrompt)) - 1);

if (($ConnectedDevices[$ConnectTarget] -Split ' ')[0] -ne $Null) {
    $DeviceIP = (Invoke-Expression '& $ADBPath -s ($ConnectedDevices[$ConnectTarget] -Split " ")[0] shell ip route') -Split ' ';
    $DeviceIP = $DeviceIP[($DeviceIP.Count - 2)];
    $DeviceIP;
    Invoke-Expression '& $ADBPath -s ($ConnectedDevices[$ConnectTarget] -Split " ")[0] tcpip 5555';
    Invoke-Expression '& $ADBPath connect ($DeviceIP + ":5555")';
    Invoke-Expression '& $ScrcpyPath -s ($DeviceIP + ":5555")';
};

while ($Reconnect -ne 'n') {
    foreach ($Device in ((Invoke-Expression '& $ADBPath devices -l') -Split "`r`n")) {
        if ($Device -like ('*' + $DeviceIP + ':5555*')) {
            $Reconnect = (Read-Host -Prompt ("`n" + $ConnectedDevices[$ConnectTarget] + "`n`nact as`n`n" + $Device + "`n`nReconnect to Device? (Y/n)")).ToLower();
            if ($Reconnect -eq 'n') {
                Invoke-Expression '& $ADBPath disconnect ($DeviceIP + ":5555")';
            } else {
                Invoke-Expression '& $ScrcpyPath -s ($DeviceIP + ":5555")';
            };
        };
    };
};

if (((Invoke-Expression '& $ADBPath devices -l') -Split "`r`n").count -eq 2) {
    Invoke-Expression '& $ADBPath kill-server'
};

沒有留言:

張貼留言