Managing Credentials (Part 3)

by Jan 6, 2017

For unattended scripts, it is generally unsafe and not recommended to hard-code secret passwords into a script.

As an alternative, you could ask for the password once, then create a credential object and use it wherever needed in your script. This part asks for a password, then constructs a credential object:

$password = Read-Host -AsSecureString -Prompt 'Enter Password'
$username = 'myCompany\myUserName'
$credential = New-Object -TypeName PSCredential($username, $password)

The credential object can then be used with any cmdlet that takes the -Credential parameter.

# use the credential with any cmdlet that exposes the –Credential parameter
# to log in to remote systems
Get-WmiObject -Class Win32_LogicalDisk -ComputerName SomeServer -Credential $credential

Twitter This Tip! ReTweet this Tip!