public/Open-KeePassRdpLink.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

function Open-KeePassRdpLink() {
    Param(
        [Parameter(Position = 0)]
        [String] $Path,

        [Parameter(ValueFromPipeline = $true)]
        [NerdyMishka.KeePass.IKeePassEntry] $Entry,

        [Parameter(ValueFromPipeline = $true)]
        [NerdyMishka.KeePass.IKeePassPackage] $Package
    )

    if($entry -eq $null -and $Package) {
        $entry = $Package.FindEntry($Path);
    }

    if($entry -eq $null) {
        Write-Warning "Could not find $entry at $Path";
    }
    $fields = $entry.Fields;
    if($fields.Url -and $fields.UserName) {
        $url = $fields.Url;
        $pw = $entry.Fields.UnprotectPassword();
        if($url -match "://") {
            $index = $url.IndexOf("://");
            $url = $url.substring($index + 3);
        }
        cmdkey.exe /generic:TERMSRV/$url /user:$($fields.UserName) /password:$pw 
        Start-Process -FilePath "$Env:Windir\system32\mstsc.exe" -ArgumentList "/v:$url" -Wait
        cmdkey.exe /delete:TERMSRV/$url 
    }
}