Creating PSCredential Object

This topic contains 12 replies, has 4 voices, and was last updated by Profile photo of Max Kozlov Max Kozlov 4 weeks, 1 day ago.

  • Author
    Posts
  • #57034
    Profile photo of OCram85
    OCram85
    Participant

    Hi guys,

    I was wondering if there is an faster way to create an pscredential object like this:

    $UserName = "Foo"
     $pass = ConvertTo-SecureString "bar" -AsPlainText -Force
     $mycreds =  New-Object -TypeName PSCredential -ArgumentList $UserName, $pass
    

    Usually I try to use the type accelerator but but i don't get it here ^^

    $UserName = "Foo"
    $pass = ConvertTo-SecureString "bar" -AsPlainText -Force
    
     $mycreds = [pscredential] @{
        UserName = $UserName
        Password = $pass
     }
    
  • #57043
    Profile photo of Ron
    Ron
    Participant

    Not sure what your goal is here. If you are frequently create pscredential objects on the fly:

    $mycreds = Get-Credential

    If you are need to do it in a batch environment, create your own function and include it in your scripts.

    • #57094
      Profile photo of OCram85
      OCram85
      Participant

      I like creating objects with the type accelerator and a hash table how it was introduced in V3.

      $obj = [PSCustomObject]@{
        Property1 = 'one'
        Property2 = 'two'
        Property3 = 'three'
      }
      

      So I was thinking I could use it for all types. But every time I try this with a pscredential i get stuck.

  • #57097
    Profile photo of Peter Jurgens
    Peter Jurgens
    Participant

    That is a slight misunderstanding of creating an instance of an object. When using a .NET type accelerator to create a new instance of that type, you should look at the "new" method of that type to determine what input is required to create a new instance of that class. For the PSCredential class the following should (I'm on my phone, unable to validate) work:

    [PSCredential]@($username, $passwordassecurestring)
    

    This can be verified by the MSDN article for this class as a constructor, used to create a new instance of that class. (https://msdn.microsoft.com/en-us/library/system.management.automation.pscredential(v=vs.85).aspx)

    Now, the documentation for the PSCustomObject class does not indicate that a hash table is an acceptable input as a constructor for the class, but I imagine that it may be due to the implementation of that specific type accelerator in PS.

    Creating a new PSCustomObject by [PSCustomObject]@{hash table} was introduced in PSv3, but this was specific to that object class, and shouldn't be confused with constructors for .NET classes and constructors for other object types, which have been around for much longer.

    • #57104
      Profile photo of OCram85
      OCram85
      Participant

      Thank you for the detailed explanation!

      Well I guess it won't work with the type acceleration and an argument list:

      $UserName = "myuser"
      $Password = ConvertTo-SecureString -String "mypassword" -AsPlainText -Force
      
      $Creds = [PSCredential]@($UserName, $Password)
      
      Cannot convert the "System.Object[]" value of type "System.Object[]" to type 
      "System.Management.Automation.PSCredential".
      At line:4 char:26
      + $Creds = [PSCredential]@($UserName, $Password)
      +                          ~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
          + FullyQualifiedErrorId : ConvertToFinalInvalidCastException
      
  • #57110
    Profile photo of Max Kozlov
    Max Kozlov
    Participant

    Why you feel youself bad with

    New-Object PSCredential $user, $password
    

    ?
    [pscustomobject]@{p1='1';p2='2'}
    is equivalent for c#'s
    new object() { p1='1';p2='2' }
    but not
    new object('1','2')

    • #57112
      Profile photo of OCram85
      OCram85
      Participant

      Comparing both following ways to create object, I thought the second one is more elegant

      Traditional way:

      $ObjectParams = @{
          Property1 = "Value1"
          Property2 = "Value2"
          Property3 = "Value3"
      }
      
      $Obj = New-Object -TypeName PSObject -Property $ObjectParams
      

      type accelerator approach:

      $Obj = [PSCustomObject]@{
          foo = "bar"
          bar = "bar"}
      

      So I thought I could adopt it and use it with other types/classes than psobject. And finally because I have to review big scripts containing vmware power cli classes and it would make it more readable for me 😀

      But like Peter sad, I misunderstood it. I can only create a psobject with a hashtable. If I want to create Object based on other .Net classes I have to use:

      $Obj = [PSCredential]@($param1, $param2)

      If I get it right, this should use the class constructor with the given params.

  • #57113
    Profile photo of Max Kozlov
    Max Kozlov
    Participant

    I think Peter want to say that you can use new (v5+) class constructor
    and it can be used like

    [PSCredential]::New($user,$password)

    and, btw, you still mix New-Object -Property with New-Object -ArgumentList
    as I already said before (but on c# examples) this is different things

    [typeaccelerator]@{hash} is -Property, and [TypeAccelerator]::new(Arguments) is -ArgumentList equivalent

    • #57119
      Profile photo of OCram85
      OCram85
      Participant

      I guess now I unterstand 😀
      The longer I work with powershell, the more I mixed up with c# syntax ^^

  • #57175
    Profile photo of OCram85
    OCram85
    Participant

    By the way the poweshell reference and especially the about_Object_Creation says:

    CREATE NON-CUSTOM OBJECTS FROM HASH TABLES
    
        You can also use hash tables to create objects for non-custom classes.
        When you create an object for a non-custom class, the full namespace 
        name is required unless class is in the System namespace. Use only the 
        properties of the class. 
     
        For example, the following command creates a session option object.
    
           [System.Management.Automation.Remoting.PSSessionOption]@{IdleTimeout=43200000; SkipCnCheck=$True}
    
        The requirements of the hash table feature, especially the default
        constructor requirement, eliminate many existing classes. However, 
        most Windows PowerShell option classes are designed to work with 
        this feature, as well as other very useful classes, such as the 
        ScheduledJobTrigger class.
    
           [Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{Frequency="Daily";At="15:00"}    
    
           Id         Frequency       Time                   DaysOfWeek              Enabled
           --         ---------       ----                   ----------              -------
           0          Daily           6/6/2012 3:00:00 PM                            True
    

    One last thing here:

    Is there a name or keyword for this approach of interacting with .NET Classes: ` [ClassType]::Method(Params) ` ?

    • #57197
      Profile photo of Max Kozlov
      Max Kozlov
      Participant

      as usual, "invoke static class method" ?

    • #57211
      Profile photo of OCram85
      OCram85
      Participant

      Thanks! Do you know if there is any official documentation about that on technet? I never read anything about it in the about pages 😀

  • #57296
    Profile photo of Max Kozlov
    Max Kozlov
    Participant

    I khow it for a so long time that I forget where I read it. may be something like that ? 😉
    http://bfy.tw/8g8H

    https://msdn.microsoft.com/en-us/powershell/scripting/getting-started/cookbooks/using-static-classes-and-methods

You must be logged in to reply to this topic.