Issue:
Recently, my colleague was working on a migration project. He faced a really strange issue with
PowerShell. We have created that script for big site migration and we have done tons of site migration with that in the past. But this time it was throwing an error while we were trying to connect the site. Below is the sample code portion:
#Prompt the user for the source environment username
$sourceUserName = "domain\username"
# Prompt the user for the source environment password
$password = 'My&$P@ssw0rd'
$securePassword = $password | ConvertTo-SecureString -AsPlainText -Force
Connect-Site "Site URL" -Username $sourceUserName -Password $securePassword
Error - Connect-Site : Cannot bind parameter 'Password'. Cannot convert the value of type "System.String" to type "System.Security.SecureString". At line:1 char:131
Analysis:
The first thing I checked on my end was whether there was any change in the "connect-site" command. But there was no update there. So, we try to run the connect-site command without passing a password. Powershell showcased the dialog for the password and it worked like a charm. That means the password was also correct. But we were not able to pass it correctly.
Generally, when we get any projects, we used to set our passwords but this time it was set by the client and it contained many special characters. In the above code, we have showcased 2 of them - & and $. These 2 characters are not handled when you try to treat them normally in convert to secure string.
Resolution:
So, we copy the error and google it. But there were tons of sites. So, we go to the copilot in the edge browser and ask resolution of the same error. It provided a response with possible resolutions and the source sites list where it has gathered the information. The response was correct but still I went through the reference site. I found one stack overflow site which I mentioned in reference that explained things in much easier language than copilot.
The PowerShell herestring exists for just such an occasion.
$password = @'
My&$P@ssw0rd
'@
The @" and "@ characters have to be on their own line, but allow for any characters inside of them.
Once we handled the password like that, it was able to run successfully. The full code will be like below:
#Prompt the user for the source environment username
$sourceUserName = "domain\username"
# Prompt the user for the source environment password
$password = @'
My&$P@ssw0rd
'@
$securePassword = $password | ConvertTo-SecureString -AsPlainText -Force
Connect-Site "Site URL" -Username $sourceUserName -Password $securePassword
References:
No comments:
Post a Comment