如何传递凭据重命名命令?

时间:2012-12-12 15:07:59

标签: powershell

我在PowerShell脚本中运行以下命令来简单地重命名计算机。该脚本将由计算机启动脚本GPO执行,因此我需要在命令中传递凭据。因为我无法看到脚本发生了什么,如果它在启动时执行我正在通过以普通用户身份登录时运行脚本来测试它

(Get-WmiObject win32_computersystem).Rename( $NewName,'Password','domain\username')

该命令返回ReturnValue为'5' - 拒绝访问。我怎样才能传递用户名和密码? (我理解脚本中密码的安全风险)

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     : 
__DYNASTY        : __PARAMETERS
__RELPATH        : 
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         : 
__NAMESPACE      : 
__PATH           : 
ReturnValue      : 5
PSComputerName   : 

2 个答案:

答案 0 :(得分:5)

如果您总是在同一台计算机上运行此程序或相关帐户漫游,那么IIRC您可以依赖DPAPI来存储密钥,如下所示:

# Capture once and store to file
$passwd = Read-Host "Enter password" -AsSecureString
$encpwd = ConvertFrom-SecureString $passwd
$encpwd
$encpwd > $path\password.bin

# Later pull this in and restore to a secure string
$encpwd = Get-Content $path\password.bin
$passwd = ConvertTo-SecureString $encpwd

# Extract a plain text password from secure string
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwd)
$str =  [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
$str

如果这不起作用,您可以使用此方法,但它不如上述方法安全:

$key = 1..32 | ForEach-Object { Get-Random -Maximum 256 }
$passwd = Read-Host "Enter password" -AsSecureString
$encpwd = ConvertFrom-SecureString $passwd -Key $key
$encpwd

# Could easily modify this to store username also
$record = new-object psobject -Property @{Key = $key; EncryptedPassword = $encpwd}
$record
$record | Export-Clixml $path\portablePassword.bin

# Later pull this in and restore to a secure string
$record = Import-Clixml $path\portablePassword.bin
$passwd = ConvertTo-SecureString $record.EncryptedPassword -Key $record.Key

# Extract a plain text password from secure string
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwd)
$str =  [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
$str

答案 1 :(得分:0)

找到以下here

$credential = Get-Credential
Get-WmiObject Win32_ComputerSystem -ComputerName OLDNAME -Authentication 6 |
ForEach-Object {$_.Rename("NEWNAME",$credential.GetNetworkCredential().Password,$credential.Username)}

您似乎需要将身份验证级别设置为能够传递凭据(可选择使用Get-Credential CMDLet)。我担心目前还没有可用于测试此功能的盒子。