The constant [PSCredential]::Empty
(aka [System.Management.Automation.PSCredential]::Empty
) gives you a valid object of type PSCredential
but with both username
and password
set to null.
However, that is not the current user's credentials; rather it means "no credentials". There may be logic in the function you're calling for this to be a moot point (i.e. where the function's the logic says to use the current security context when $credentials -eq [PSCredential]::Empty
), but in some contexts this same value may be used for other purposes (e.g. to say you want to use anonymous authentication).
You cannot get the current user's credentials without prompting for them or explicitly assigning them in some other way; otherwise this would present a security risk
#create a credential object for demo purposes.
#Imagine that instead of this line we were saying `$credential = Get-CurrentUserCredential`
#(you have to imagine this, since no such function exists).
$credential = [PSCredential]::new('myUsername', ('superSecretPassword' | ConvertTo-SecureString -AsPlainText -Force))
#we can now see this user's password;
#someone malicious could have this script run under the current user's
#profile & have this information reported back to them.
$credential.GetNetworkCredential().Password
If you want to run something as the current user, you already are (i.e. hence them being the current user); so you don't need to get their credentials.
That said, there are cases where it would be nice to have their credentials; e.g. if accessing a resource which doesn't use the current user context / needs explicit credentials. In such cases you have to either prompt for credentials (Get-Credential $env:username
), or read them from some resource (see https://stackoverflow.com/a/6240319/361842).
There's a really thorough explanation of credentials here: http://duffney.io/AddCredentialsToPowerShellFunctions; definitely worth a read.