在Invoke-Command中解析远程变量

时间:2019-05-07 18:53:13

标签: powershell

需要帮助解析CSV中的变量。

我正在尝试在下面创建脚本。我要完成的工作是基于CSV文件重置服务帐户的密码,然后我需要它使用Invoke-Command来使用密码来编辑注册表。这是用于自动登录。

我可以获取脚本来重置密码,并在注册表中放置一个变量,但是它将整行而不是密码放置在目录中。我需要弄清楚如何解析它以便仅传递密码。

有问题的部分是Invoke-Command脚本块中的代码。

我本来是使用$account.password来尝试此命令的,但是并没有推送该变量,有人提到了$using命令,该命令至少推送了该变量,但它推送了所有变量,计算机名,帐户名和密码。

Import-Module ActiveDirectory

$Resetpassword = Import-Csv "c:\UserList.csv"

foreach ($Account in $Resetpassword) {
    $Account.sAMAccountName
    $Account.Password
    $Account.computer
    Set-ADAccountPassword -Identity $Account.sAMAccountName -NewPassword (ConvertTo-SecureString $Account.Password -AsPlainText -force) -Reset

    Invoke-Command -computername $Account.computer -UseSSL -Scriptblock {
        Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" "Test" -Value "$using:Account.Password" -Type string
    }
}

1 个答案:

答案 0 :(得分:0)

在变量周围使用引号会引起问题。只需使用不带引号的$using:Account.Password。 PowerShell试图对$ Account对象进行字符串化。当您尝试访问对象的属性时,此问题会更加复杂,因为变量将被扩展,然后.propertyname将被连接到输出。如果在控制台上键入Write-Host $account.password,则会看到此行为。

将您的Invoke-Command更新为以下内容:

Invoke-Command -computername $Account.computer -UseSSL -scriptblock {
   Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" "Test" -Value $using:Account.Password -type string
}

以下是该问题的一个示例:

$a = [pscustomobject]@{name = "strings everywhere"}
"$a"
@{name=strings everywhere}

Write-Host "$a.name"
@{name=strings everywhere}.name

要解决此症状,您需要使用变量语法($a)或使用子表达式运算符($()),这允许变量运算符在潜在字符串之前进行扩展。转换适用。访问变量的属性也是如此。

$a.name
strings everywhere
$($a.name)
strings everywhere
Write-Host "$($a.name)"
strings everywhere
相关问题