as a wild thought - have you tired casting the credentials to the appropriate datatype?
Looks like you may need to do something like this:
The above is a powershell script to allow casting of credentials to be cast to other supported credential types.
Now, an alternate method (which is less risky in my opinion) as provided by this site:
is to pass the username and password separately by using $cred.username and $cred.password. Something along the lines of this:
$cred = Get-StoredCredential -Target dbStoredCredentials
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server MyServer
$srv.ConnectionContext.LoginSecure = $false
NOTE - the above is copy-pasted from the second link above with minor changes to meet what you had in your code. The above is fully untested by me and I would recommend testing it on a test system prior to any live database connections. Same applies to the first comment about casting - test it out on a test system first.
And now - the EASY way - DBATOOLS:
$cred = Get-Credential
$srv = Connect-DbaSqlServer -Sqlserver MyServer -Credential $cred
And another solution (copy-pasted from 2nd link with no changes this time):
# First create the PSCredential object
$cred = Get-Credential
#set the password as read only
# Create the SqlCredential object
$sqlCred = New-Object
$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = “Server=localhost\sql12;Initial Catalog=master”
$sqlConn.Credential = $sqlCred
You will need to update that "Get-Credential" bit to pull from the credential store.
So there are options. Which one you use is up to you. I personally like DBATOOLS, but your company may not allow importing that. If they don't, I like the last option. The other 2, to me, are harder to support. You will need to adjust whichever one of the above you choose to use to connect to your database as none of the above suggestions took that into consideration.
The above is all just my opinion on what you should do.
As with all advice you find on a random internet forum - you shouldn't blindly follow it. Always test on a test server to see if there is negative side effects before making changes to live!
I recommend you NEVER run "random code" you found online on any system you care about UNLESS you understand and can verify the code OR you don't care if the code trashes your system.