To avoid entering your credentials for every connection in a foreach loop statement with browser authentication, you can use the PowerShell parameter -UseCredentialsFrom
to create a single connection, and then reuse the credentials from that connection in your script.
-UseCredentialsFrom
To illustrate how the -UseCredentialsFrom works, here is a basic connection script:
$connection = Connect-Site -Url "http://mytenant/sites/mysitecollection1" -Browser
Connect-Site -Url "http://mytenant/sites/mysitecollection2" -UseCredentialsFrom $connection
Connect-Site -Url "http://mytenant/sites/mysitecollection3" -UseCredentialsFrom $connection
When you run this script, a browser window will appear so you can connect to mysitecollection1, and once the connection is made, the script will automatically use your credentials to connect to mysitecollection2 and mysitecollection3.
How to use -UseCredentialsFrom with a foreach loop
A foreach loop statement typically uses brackets to repeat connection and copy commands for every row of a CSV file with the app. Here is an example:
Import-Module ShareGate
$csvFile = "C:\CSV\CopySites.csv"
$table = Import-Csv $csvFile -Delimiter ","
$srcUsername = "sourceusername"
$srcPassword = ConvertTo-SecureString 'sourcepassword' -AsPlainText -Force
$dstsiteConnection = Connect-Site -Url https://tenantname.sharepoint.com/sites/sitename -Browser
Set-Variable srcSite, dstSite
foreach ($row in $table) {
Clear-Variable srcSite
Clear-Variable dstSite
$srcSite = Connect-Site -Url $row.SourceSite -Username $srcUsername -Password $srcPassword
$dstSite = Connect-Site -Url $row.DestinationSite -UseCredentialsFrom $dstsiteConnection
Copy-Site -Site $srcSite -DestinationSite $dstSite -Merge -Subsites
}
When you run this script, you get prompted to enter your credentials in a browser window before the foreach
statement.
The connection gets stored as the $dstsiteConnection
variable, which is then reused in each pass of -UseCredentialsFrom $dstsiteConnection
in the loop. This ensures that you do not need to re-enter your credentials for every site that is being copied.
Note: Avoid using any of the URLs listed in your CSV for the $dstsiteConnection variable. If you use one of your listed URLs, your credentials will get cleared by the Clear-Variable
command.