I'm trying to create a module with a bunch of functions, but I'm stuck with a problem: sometimes I need to run functions with a different from current credentials. But the thing is: I don't want to ask for credentials if I didn't specify a username. Like this:
function MyFunction ($ComputerName='localhost', $UserName) {
if ($UserName) {
Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName -Credential $UserName
} else {
Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName
}
}
Can I somehow get rid of the if
statement? Can I just let the function use current credentials unless I specify -UserName
?
If I leave it like this:
Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName -Credential $UserName
and call a function without specifying -UserName
, it asks for credentialls every time. Yes, it uses current if I close the 'get-cred' box, but it's not what I want.
You can populate aPSCredential
object with current credentials using the default credential acquired like in here:Then just use
-credential $cred
whenever you need without building a wall of if's.EDIT: Apparently, as the current user's
PSCredential
object has its password asSecureString
encrypted by the very same user's private key, if one would be able to get aPSCredential
out of default credentials object, he'll be able to decrypt the password into plaintext, so this hole existed but was eventually closed. (Maybe let this answer hang here so that people won't get the asme error as I did) This question has the canonical answer on what arised in here.Another way to do this might be using a variation of splatting, explained in detail by Ansgar Wiechers and here to construct only credential block in a single if statement and then use that block wherever you need, instead of writing direct
-credential
parameter.And then add @creds wherever you require alternate credentials:
This way you'll be asked for user's password once if
$UserName
is supplied, and then the$creds
will either be empty or contain valid credentials of$UserName
, so all subsequent if's can be replaced by explicit adding of@creds
.