Skip to main content
Hide credentials in scripts
Updated over 4 months ago

Command

Get-Credential

Details

If you need to use manual mode to connect to your SharePoint site, you will need to enter your credentials in the script. This can be a concern since anyone with access to the script can see your credentials. Use this PowerShell alternative with the Connect-Site command.

How-to

$credentials = Get-Credential

This opens a window where you can enter the credentials for this execution of the script.

You can then use those credentials to connect to your site:

# Prompt for user credentials
$credentials = Get-Credential

# Connect to the site using the provided credentials
$site = Connect-Site -Url "http://farm/sites/siteCollection" -Credential $credentials

Using this technique, you will never expose your credentials in a script. However, you will need to manually enter your credentials for every execution of the scripts, which makes scheduling difficult.

As an alternative, it is possible to output the encrypted string generated by PowerShell and use it for your password in a PowerShell script.

Note: A user cannot decrypt your password but could take the encrypted password and use it in an unauthorized way. However, since secure strings are generated using your local machine encryption key and the current user's permissions, they can only be used on the same machine and cannot be transferred to a script running on a different machine.

To generate your encrypted password, create a script using the following example as a guide:

# Prompt for user credentials
$credentials = Get-Credential

# Convert the secure string password to an encrypted standard string
ConvertFrom-SecureString $credentials.Password

# Example encrypted password string (for demonstration purposes)
01000000d08c9ddf0115d1118c7a00c04fc297eb01000000c57ba489a6781343983ef0deba79d0250000000002000000000003660000c0000000100000007ba4ea450748178832c0187a37c513270000000004800000a000000010000000a3fe44ced5ac805a2fcf7a6c3652994510000000ccc7701593bd519546d09f216962fac4140000003904619dc8c320b7fb0cafa6efdd78dd2c69c8e5

Next, copy the encrypted password string and paste it into your script to connect to your site:

# Define the encrypted secure string password
$secureString = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000c57ba489a6781343983ef0deba79d0250000000002000000000003660000c0000000100000007ba4ea450748178832c0187a37c513270000000004800000a000000010000000a3fe44ced5ac805a2fcf7a6c3652994510000000ccc7701593bd519546d09f216962fac4140000003904619dc8c320b7fb0cafa6efdd78dd2c69c8e5"

# Convert the encrypted secure string back to a secure string object
$password = ConvertTo-SecureString $secureString

# Define the username for the site connection
$username = "[email protected]"

# Connect to the SharePoint site using the username and password
Connect-Site -Url "http://farm/sites/siteCollection" -Username $username -Password $password

Did this answer your question?