Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell 5.1 What's the newer way of creating a PSCredential object

Tags:

powershell

PowerShell 5.1

What's a newer way of creating the PSCredential object?

$Credential = New-Object -TypeName PSCredential -ArgumentList $_config.DBUserID, $_config.DBPassword

I was reading here that this is the legacy way of creating the object. I didn't quite understand it.

like image 664
Rod Avatar asked Oct 29 '25 09:10

Rod


1 Answers

The link from your last comment was regarding the PSCustomObject creation specifically.

The "Legacy" approach from Microsoft Doc here was

$myHashtable = @{
    Name     = 'Kevin'
    Language = 'PowerShell'
    State    = 'Texas'
}

$myObject = New-Object -TypeName PSObject -Property $myHashtable

It is still a valid way to do it and I don't see it going away anytime soon. That being said, you can cast a hashtable into a PSCustomObject directly instead, which is the preferred way. It is shorter and right to the point.

$myHashtable = @{
    Name     = 'Kevin'
    Language = 'PowerShell'
    State    = 'Texas'
}
$myObject = [pscustomobject]$myHashtable

My original answer, that was regarding the PSCredential specifically

The way you are creating your credentials is perfectly fine.

I personally use the [PsCredential]::New($Username,$Password) constructor but it is not a better alternative.

In fact, using the New-Object still have an advantage over using the constructor, which is that you can set properties that are not part of the constructor upon object creation, which you cannot do when using the constructor.

Here is how you create a PSCredential object using the constructor

# Name credentials
$username = 'Username'
$password = 'Password' | ConvertTo-SecureString -AsPlainText -Force
$credential = [PSCredential]::New($username,$password)

VSCode snippet I created myself for reference

(Trivia: I named my snipped "cheap-cred" because having credentials in plain text in a script is not the best practice and it is a permanent reminder of that each time I use it.)

    "cheap-cred": {
        "prefix": "cheap-cred",
        "body": [
            "# ${1:Name} credentials",
            "\\$username = '${2:Username}'",
            "\\$password = '${3:Password}' | ConvertTo-SecureString -AsPlainText -Force",
            "\\$credential = [PSCredential]::New(\\$username,\\$password)\r\r$0"
        ],
        "description": "Create credentials object from string within script (insecure)"
    }

Reference:

You can read about object creation in the official doc, where both method are shown, with no indication of a legacy one: about_Object_Creation

like image 109
Sage Pourpre Avatar answered Oct 31 '25 01:10

Sage Pourpre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!