0

I am writing a script to launch MSTSC from a grid of buttons. These buttons will each open up a different server connection. I have a separate button that gets and stores admin creds, that I borrowed from another script. When clicked, the button calls the getAdmin function:

function getAdmin {
$returnObject = $null; $credValid = $null;

$cred = Get-Credential #Read credentials
$username = $cred.username
$password = $cred.GetNetworkCredential().password

$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)

if ($domain.name -eq $null)
{
    $credValid = $false
    $cred = $null
} else {
    $credValid = $true
}
$returnobject = new-object psobject -property @{ Valid = $credValid; Credentials = $cred }
return $returnObject }

Then I have my "server buttons:"

$btnServ = new-object system.windows.forms.button
$btnServ.location = new-object system.drawing.point (10,200)
$btnServ.text = "Server Name (SERVER)"
$btnServ.width=250
$btnServ.height = 30
$btnServ.add_click({ Start-Process mstsc -ArgumentList "/v:SERVER" -Credential $cred })

Now, when I store creds using my first button, then I click the btnServ button, it still prompts me for "Windows PowerShell Credential Request" instead of grabbing the stored creds from the previous action. If I remove -Credential $cred from the call, whether I click on the first getAdmin button or not, it just says that my logon attempt has failed and that I provided the incorrect information.

Ideally, I want to store my creds, then no matter which server button I press it will log me in instead of making my type in my creds twice.

Ben
  • 21
  • 7
  • Where are you calling `getAdmin`? Do you have a line somewhere that populates `$cred`? The function is returning an object with a property Credentials. I would expect something like this in your code. `$cred = (getAdmin).Credentials` inside an if that would check if they were `.Valid` or not. – Matt Feb 18 '15 at 19:15

1 Answers1

1

This is most probably a scoping issue - the code inside the click event delegate (the .add_click({}) action) treats the $cred variable as local, defaulting to $null.

Since you haven't specified a scope for the $cred variable inside the getAdmin function, they are treated as two separate variables that can't "see" eachother

You can specify the scope like this:

$Script:cred 

So the resulting code becomes:

function getAdmin(){
    # code code code
    $Script:cred = Get-Credential
    # more code
}

and then:

$btnServ.add_click({ Start-Process mstsc -ArgumentList "/v:SERVER" -Credential $Script:cred })

Now, both ScriptBlocks refer to the same variable in a parent scope, and your -Credential switch should work

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206