Finding Constructors (and submitting Credentials unattended)

by Feb 5, 2013

When you need to log on with alternate credentials, cmdlets often pop up a login dialog, like here:

$cred = Get-Credential

If you wanted to run a script unattended, you would have to generate the credential object manually instead. To generate a new object, first find out its type:

$cred.GetType().FullName 

Then, use New-Object to create a new instance of this object.

PS> $cred = New-Object -TypeName System.Management.Automation.PSCredential
New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Management.Automation.PSCredential. 

This fails though, because to "construct" a new object, the constructor may need additional mandatory information. Here is how you can list the available constructor methods and view the additional information they require:

PS> ([Type]'System.Management.Automation.PSCredential').GetConstructors() | 
  ForEach-Object { $_.ToString() }

Void .ctor(System.String, System.Security.SecureString)

As you see, the constructor for credential objects needs two pieces of information: a string , and an encrypted string – the user name and the user password. So here is how you create logon credentials that you then can use whenever a cmdlet provides a parameter -Credential:

$username = 'testdomain\testuser'
$password = 'secret' | ConvertTo-SecureString -Force -AsPlainText
$cred = New-Object -TypeName System.Management.Automation.PSCredential $username, $password

Twitter This Tip! ReTweet this Tip!