Authentication: currently loggedon user or from variable

This topic contains 2 replies, has 2 voices, and was last updated by  SuperSysAdmin 1 year, 8 months ago.

  • Author
  • #33610



    I am currently working on a big PowerShell GUI application which combines a bunch of functions.

    As these functions connect to remote machines I need to think about authentication. So I added a button which calls Get-Credential and saves this to a variable (let's say $savedcred). But I also want to leave the possibility that the functions can be launched without having to explicitly enter credentials (so just using the credentials of the currently logged on user from where the application is launched).

    So an example of a function would be:

    if ($savedcred)
        Enter-PSSession -ComputerName computer1 -Credentials $savedcred
        Enter-PSSession -ComputerName computer1

    But as you notice, this will render me with a lot of repetitive code. I have been trying to find a way to get the credentials of the currently loggedon user in and put it in a PSCredential type object, so that I declare the $savecred at the start of my application and if necessary, it can get overwritten with a new user in case the Credential button is used.

    I have been looking for instance into [System.Security.Principal.WindowsIdentity] but there seems no way to inject this into the PSCredential object.

    Anyone already did something like this? Is it possible at all?

  • #33613

    Dave Wyatt

    You can't get the password of the currently logged-on user. That would be a massive security hole. However, you can use the Splatting technique to simplify your code. Instead of just putting your credential object into $SavedCred, make it a hashtable like so:

    # If you want to use a specific credential
    $savedCred = @{ Credential = Get-Credential }
    # If you want to just use the current user:
    $savedCred = @{}

    Once you have a hashtable like this, you can splat it to any function which has a -Credential parameter. If $savedCred has a Credential key, it'll bind to that parameter, and if it's an empty hashtable, then it won't affect anything:

    Enter-PSSession -ComputerName computer1 @savedcred

    Note the @ symbol instead of $; that's what tells PowerShell to splat the variable instead of just passing it as an argument. The about_Splatting help file has more details on how this works. ( )

  • #33634


    Hi Dave,

    Thanks for pointing me in the right direction. This was exactly what I needed. Learned something again today 🙂

You must be logged in to reply to this topic.