PowerShell and scripting. It is supposed to make your everyday tasks easier! Yet if your script needs to have administrative rights to run, then you might as well sit there and run them one by one. How would you even schedule it to run as a task? Let’s look at some ways that can be done.
You can embed your credentials
You can always use $cred=Get-Credential or enter the credentials in the script itself. In this scenario:
- It will ask once and save them for that PowerShell session only.
- Note: saving credentials in the script may allow others to get administration credentials if the script is seen or copied.
- This must be run interactively if you enter credentials. That may work fine if you are actively running the script but if you need to schedule it then it’s a no-go unless you hardcode the credentials inside your script.
You can also save the credentials to a text file with encrypted information. An example:
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File -FilePath .\cred.txt
$pass = Get-Content -Path .\cred.txt | ConvertTo-SecureString
$creds = New-Object -TypeName PSCredential -ArgumentList ‘administrator’, $pass
In this scenario:
- Credentials are not stored in your script.
- Credentials are in a plain text file while contents are encrypted.
- The file can be decrypted only on the machine and as the user it was encrypted with.
You can use Windows credential manager
By default, credential manager stores your Windows and web passwords. You can leverage that capability for your script. In order to do this, use the New-StoredCredential cmdlet to store it in Credential manager.
In this scenario, you:
- Leverage stored credentials in Credential Manager in Windows.
- Can schedule the script to run.
- Can use a parameter where creds are used per session, Local Machine or Enterprise.
You will need to download from PSGallery the CredentialManager module and install it on the machine where the script will run. It is also possible to store the credentials in Azure by downloading and installing the module AXCredentialVault.
There are many ways to call credentials to run your scripts, but always keep in mind security, security, security. If you have questions, or need further assistance, email email@example.com. We are happy to help!