远程脚本中的局部变量

时间:2014-04-24 15:18:36

标签: powershell arguments invoke-command

我已经创建了一个脚本来循环显示包含两列的电子表格。我遇到的问题是当我运行invoke-command时局部变量不起作用。我添加了-ArgumentList参数,但我仍然收到有关$null参数的错误消息。谁知道我在这里做错了什么?

foreach ($list in (Import-Csv C:\Users\joerod\Desktop\remove_users.csv)) {
    Write-Output "Connecting to $($list.computer)..."
    $myses = New-PSSession -ComputerName $list.computer
    Invoke-Command -Session $myses -ScriptBlock {
        Write-Output "Searching for software..."
        Write-Output $list.user

        $find_java = gwmi Win32_Product -Filter "Name LIKE '%Java'" | select -ExpandProperty IdentifyingNumber
        if ($find_java -ne $null) {
            Write-Output "Software found... Uninstalling..."
            foreach ($i in $find_mktx) {
                msiexec.exe /x $i /qn /passive /l*v! c:\uninst.log 
            }
            Write-Output "Adding $($list.user) to security group"
            $group = "CN=Java_removed,OU=Groups,OU=Resources,DC=Contoso,DC=LOCAL"
            Add-ADGroupMember $group -Identity $list.user
        }
        else {
            Write-Output "Could not find Java software installed"
        } 
    } -ArgumentList $list
}    

1 个答案:

答案 0 :(得分:1)

问题是您试图将参数列表传递到else。如果您正确格式化代码,很容易看到。

foreach($list in (Import-Csv C:\Users\joerod\Desktop\remove_users.csv)){
    Write-Output "Connecting to $($list.computer)..."
    $myses = New-PSSession -ComputerName $list.computer
    Invoke-Command -Session $myses -ScriptBlock {
    Param($list)
        Write-Output "Searching for software..."
        Write-Output $list.user

        $find_java = gwmi win32_product -filter "Name LIKE '%Java'" | select -ExpandProperty     IdentifyingNumber
        if($find_java -ne $null){
            Write-Output "Software found... Uninstalling..."
            foreach($i in $find_mktx){
                msiexec.exe /x $i /qn /passive /l*v! c:\uninst.log 
            }
            Write-Output "Adding $($list.user) to security group"
            $group = "CN=Java_removed,OU=Groups,OU=Resources,DC=Contoso,DC=LOCAL"
            Add-ADGroupMember $group -Identity $list.user
        }
        else{
            Write-Output "Could not find Java software installed"
        } 
    } -ArgumentList $list

}