Last week, I posted
a script to gather user information from a different domain. In that script the -Credential parameter was
set to a specific account name. When
running the script, a prompt would ask for the password. Although it worked it isn't the most secure
way of getting the information.
This week, let's add
some additional security and eliminate the need for any additional information.
First, you need a
way to store an encrypted password. The
following script will do just that:
$credfilepath =
"c:\scripts\password_file.txt"
$cred = read-host
-AsSecureString "`nPlease enter the new password "
$cred |
ConvertFrom-SecureString | Set-Content $credfilepath
The first line sets
the $credfilepath variable to where you want the credential file to reside.
The second line is
what will prompt you for the password of the account you will be using to run
the Get-ADUser statement in the main script.
The third line reads
the $cred variable, converts the $cred information from a secured string to an
encrypted string, and stores the information in the file assigned to the
$credfilepath variable.
Once you have the
password in an encrypted format, we can make the following changes to the
original script:
$pwd = get-content
C:\scripts\password_file.txt | ConvertTo-SecureString
$EXTUser =
'<domain>\<user name.'
$cred = New-Object
System.Management.Automation.PSCredential $EXTUser, $pwd
invoke-command
-ComputerName server1.mydomain.net -Credential $cred -ScriptBlock { get-aduser
-filter * -Properties * -SearchBase 'OU=Titles,DC=MyDomain,DC=Net' |
Select-Object DisplayName,sAMAccountName,ObjectSid | FL }
The first line
variable converts the encrypted information in password_file.txt to a secured
string.
The second line
variable holds the account that has permissions to run the script.
The third line
variable gets the credential information using the
System.Management.Automation.PSCredential class.
Change the
-Credential value, in the Invoke-Command line, to -Credential $Cred.
Now, when you run
the script, you will not be prompted for a password.
I use this type of
security method a lot at my real job. In
my opinion, it is a easy way to add a level of security to scripts.
Please let me know
if you have any questions about this script.
No comments:
Post a Comment