Powershell still prompting for credential even when using System.Management.Automation.PSCredential

118 Views Asked by At

I have created the following variable $cred:

$User = "sa"
$PWord = ConvertTo-SecureString -String "teste" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord

Then, I open a connection with dbatools script.

$server1 = Connect-DbaInstance `
-SqlInstance '192.168.0.61\TESTE2017' `
-SqlCredential $cred`
-TrustServerCertificate;

But powershell still prompt asking for a credential:

enter image description here

Why?

1

There are 1 best solutions below

0
mklement0 On

There's great information in the comments; let me try to summarize:

PowerShell commands (pipelines) situationally require explicit line continuation using a line-ending ` (the so-called backtick, which is PowerShell's general escape character), notably when spreading distinct arguments across multiple lines.

  • By contrast, ` is not needed if a command's line is syntactically incomplete, because PowerShell then automatically looks for the command's completion on the next line; e.g.:

    # Example 1
    Get-ChildItem -File | # NO ` needed: | implies that the command continues
      Sort-Object Length -Descending
    
    # Example 2
    1..3 | ForEach-Object { # NO ` needed: { implies that the command continues
      1 + $_
    }
    
    # Example 3
    (Get-Date). # NO ` needed: . implies that the command continues
      Year
    

If and when you do need ` for line-continuation, the following strict rules apply:

  • The line-ending ` must NOT be followed by any additional characters - not even whitespace.

  • The line-ending ` must NOT be directly attached to the last argument to the line - make sure that it is preceded by a space.[1]

    • If you do accidentally directly attach ` to a (syntactically incomplete) last argument, it is (potentially) continued on the next line, including the newline, IF that newline starts with a non-whitespace character.

    • In your case, this meant that verbatim -TrustServerCertificate was appended to the stringified value of variable $cred, which resulted in a string value such as the following ($cred - uselessly - stringified to its type name):

      System.Management.Automation.PSCredential
      --TrustServerCertificate
      
      • It is this string value that became the argument to the -SqlCredential parameter, resulting in the symptom you saw.

[1] Technically, a space is not needed if the preceding argument is itself syntactically complete, but not only is it safe to always use a space, it also provides visual clarity.