我需要创建一个具有空用户名的PSCredential。
$Password = ConvertTo-SecureString -AsPlainText -Force -String 'a'
$Credential = New-Object -TypeName PSCredential -ArgumentList '', $Password
当我运行上面的代码时,我得到一个异常。
New-Object : Exception calling ".ctor" with "2" argument(s): "Cannot process argument because the value of argument "userName" is not valid. Change the value of the "userName" argument and run the operation again."
如何创建具有空用户名且只有密码的PSCredential?
最佳答案
正如您所发现的(以及对该问题的评论中的Ansgar Wiechers注解),您不能直接向the $null
constructor that accepts username and password separately提供一个空的用户名(空字符串或[System.Management.Automation.PSCredential]
)。
您可以使用the constructor that accepts a [psobject]
instance来解决此问题,方法是传递带有[pscustomobject]
和UserName
属性(PSv3 +)的自定义对象(Password
实例):
$Credential = New-Object PSCredential -ArgumentList ([pscustomobject] @{
UserName = '';
Password = (ConvertTo-SecureString -AsPlainText -Force -String 'a')[0]
})
注意将
[0]
应用于ConvertTo-SecureString
调用的结果,这对于将输出对象正确识别为[securestring]
([System.Security.SecureString]
)实例是必需的(如果使用中间变量,则不需要此技巧,如问题所示)。我不确定为什么需要这样做。也许默认情况下,输出被视为此处的集合;如果您具体知道,请告诉我们。警告:
例如,在没有用户名的情况下,
$Credential.GetNetworkCredential()
失败。 关于powershell - 使用空用户名创建PSCredential,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38678280/