Three ways to pass credentials in a Powershell Script

I thought I’d pull together something that might prove interestingly useful for those new to Powershell.   Passing credentials.


Here’s your typical scenario.   You have a script that requires credentials internally.  So to provide those credentials you would do something like

$MyCredentials=GET-CREDENTIAL –credential “CONTOSOUsername”

and you of course see a box like this normally on the screen


Then you would type in the password and life would go on about it’s Merry Little Way…

Build from clear text in a Script

The other method you could leverage would be to embed the credentials in a Powershell script like this.



$SecurePassword=Convertto-SecureString –String $MyClearTextPassword –AsPlainText –force

$MyCredentials=New-object System.Management.Automation.PSCredential $MyUsernameDomain,$SecurePassword

This second method is of course very insecure as the credentials are stored directly and viewable within the script.   But the advantage to this is the ability to work with a legacy setup like a BAT, CMD or vbScript as the calling system.  

You can pass the credentials to a Powershell and have it invoke the Cmdlets (like those in Exchange 2007) with the same flow and no modification to the source script.

Store Credentials in an XML file

Using the EXPORT-CLIXML and IMPORT-CLIXML gives us a better option.   We can store away the entire System.Management.Automation.PSCredential Object as an XML file.   It’s actually VERY easy to use.

Create your credentials in any of the normal manners.   Let’s use the Interactive one as an example

Instead of just doing this for Credentials and keying in the password

$MyCredentials=GET-CREDENTIAL –Credential “CONTOSOUsername”

You can pipe the output EXPORT-CLIXML

$MyCredentials=GET-CREDENTIAL –Credential “CONTOSOUsername” | EXPORT-CLIXML C:ScriptfolderSecureCredentials.xml

Now if you ever need to re-use those credentials it’s just a simple matter of running an IMPORT-CLIXML and bringing the data back in as an Object.

$MyCredentials=IMPORT-CLIXML C:ScriptfolderSecureCredentials.xml

Now wherever this XML file exists SHOULD be a secure location.  That goes without saying.   But the beautiful part here is if you have a series of systems or scripts that may need to have those credentials reset, you’re just into rebuilding a single XML file and just having the scripts use an IMPORT-CLIXML file to bring in the data.

Remember Powershell is just another technology to get you home earlier.   Leverage these credential methods in your environment in whatever suits your organization best.

Remember, the Power of Shell is in YOU

The Energized Tech

One Reply to “Three ways to pass credentials in a Powershell Script”

Leave a Reply