Public/Connect-Teamviewer.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# .ExternalHelp Teamviewer-Help.xml
function Connect-Teamviewer
{
    [CmdletBinding(DefaultParameterSetName = 'List')]
    param
    (        
        [Parameter(ParameterSetName = 'List', Mandatory=$true)]
        [Parameter(ParameterSetName = 'Update', Mandatory=$true)]
        [string[]]$ComputerName,
        
        [Parameter(ParameterSetName = 'List', Mandatory=$true)]
        [Parameter(ParameterSetName = 'Update', Mandatory=$true)]
        [securestring]$Password,
        
        [Parameter(ParameterSetName = 'Update', Mandatory=$false)]
        [Switch]$UpdateDeviceList,

        [Parameter(ParameterSetName = 'Update', Mandatory=$false)]
        [securestring]$AccessToken
    )

    Begin
    {   
        Write-Verbose -Message 'Starting: Connect to Teamviewer Device'

        if ($PSBoundParameters.ContainsKey('UpdateDeviceList'))
        {
            if (!(Test-Path variable:Global:TeamviewerAccessToken ) -and !($AccessToken))
            {
                throw 'No Teamviewer Access Token has been specified or set. Use Set-TeamviewerAccessToken to set your AccessToken or Initialize-Teamviewer to load Teamviewer Global Variables.'
            }
            elseif ((Test-Path variable:Global:TeamviewerAccessToken ) -and !($AccessToken))
            {
                $AccessToken = $Global:TeamviewerAccessToken
            }  

            Write-Verbose -Message "Updating Teamviewer Device List before Connecting to Device"
            Set-TeamviewerDeviceList -AccessToken $AccessToken
        }

        $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
        $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
    }
    
    Process
    {
        [ValidateNotNullOrEmpty()]$Teamviewer = Get-ChildItem -Path "$Env:SystemDrive\Program File*\Teamviewer\Teamviewer.exe" -Recurse | Select-Object -ExpandProperty fullname

        Write-Verbose -Message "Teamviewer Exe Path: [$Teamviewer]"
        
        foreach ($Name in $ComputerName)
        {                    
            Try
            {
                $RemoteId = (Get-TeamviewerDeviceProperty -ComputerName $Name -remotecontrol_id).substring(1)
                Write-Verbose -Message "Connecting to ComputerName: [$Name] with Teamviewer ID: [$RemoteId]"

                Start-Process -FilePath $Teamviewer -ArgumentList "-i $RemoteId --Password $PlainPassword" -ErrorAction Stop -WindowStyle Maximized             
            }
            catch
            {
                Throw "Failed to Connect to ComputerName: [$Name] using Teamviewer ID: [$RemoteId]"
            }        
        }
    }

    End 
    {
    
    }
}