Powershell:将PsCredentials设置为$ Null表示用户名,$ Null表示密码

时间:2011-09-09 10:16:19

标签: powershell

如何创建$ Null用户名和$ Null密码PScredentials对象?

根据这篇文章,null PSCredential使Powershell使用Windows身份验证,这似乎是在域设置中运行脚本的一种更简单的方法。不幸的是,我似乎无法弄清楚他在哪里/如何将它设置为Null: http://blogs.msdn.com/b/dvespa/archive/2010/02/22/how-to-use-windows-authentication-with-the-pscredential-class.aspx

其他资源: 这个答案为密码指定了$ Null,但不允许$ Null用户名。 Create PSCredential without a password

谢谢。

2 个答案:

答案 0 :(得分:0)

为什么需要$ null PSCredential对象?

根据文件

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. 

这意味着如果您不使用此参数,则将使用Windows身份验证。


编辑:

所以在Powershell中,如果你想要一个空凭证,你只需要指定它:

测试:

Get-WmiObject Win32_Process -Credential 

Get-WmiObject Win32_Process -Credential $null

Get-WmiObject Win32_Process -Credential (Get-Credential)

答案 1 :(得分:0)

常量[PSCredential]::Empty(又名[System.Management.Automation.PSCredential]::Empty)为您提供了PSCredential类型的有效对象,但usernamepassword都设置为空。

但是,这不是当前用户的凭据;相反,它意味着&#34;没有凭据&#34;。你要求的函数中可能有一个逻辑是一个没有实际意义的点(即当$credentials -eq [PSCredential]::Empty时函数的逻辑说明使用当前的安全上下文),但在某些情况下此相同值可用于其他目的(例如,您要使用匿名身份验证)。

您无法获取当前用户的凭据而不会提示他们或以其他方式明确指定他们;否则这会带来安全风险

#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

如果您想以当前用户身份运行某些东西,那么您已经是(因此他们是当前用户);所以你不需要获得他们的证书。

那就是说,有些情况下获得他们的证书会很好;例如如果访问不使用当前用户上下文/需要显式凭据的资源。在这种情况下,您必须提示输入凭据(Get-Credential $env:username),或者从某些资源中读取凭据(请参阅https://stackoverflow.com/a/6240319/361842)。

这里有一个非常彻底的凭证解释:http://duffney.io/AddCredentialsToPowerShellFunctions;绝对值得一读。