You can use the Get-Credential cmdlet to prompt for username and password which avoid saving the password inside the script, but it means you'll not be able to run the script unattended.
However, what you can do is to use Get-Credential the first time to store the password encrypted somewhere, and call it from that file everytime the script runs. Editing the file will not reveal the password as it's encrypted, and to avoid anyone to use it, you could use NTFS permissions to ensure the file is only readable by expected administrators.
So, here is how you could do it:
# Set the file path variable (extension is not important)
[string]$credential_filepath = "c:\credential.pwd"
# Check if the file exists; if not, create it (should be used once)
if ((Test-Path -Path $credential_filepath ) -eq $False) { (Get-Credential).Password | ConvertFrom-SecureString | Out-File $credential_filepath }
# Read the password
$my_stored_password = cat $credential_filepath | ConvertTo-SecureString
# Add it back to a credential object
$cred = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList "username", $my_stored_password
So now, you can use it with any cmdlet where pscredential objects are used like Get-WmiObject.
It's not a highly secure solution but it's definitely a good balance between security and efficiency.
No comments:
Post a Comment