即使从未登录,WMI也会拉动当前用户

时间:2016-03-22 14:37:22

标签: powershell powershell-v3.0

我是PowerShell的新手,我正在尝试从excel文件创建一个CSV,以便比较查看当前登录到计算机的用户。但是,我遇到了一个奇怪的问题,即使他们从未登录过计算机,有时脚本会多次拉同一个用户。这是我的完整代码。我知道可以做很多优化(需要删除的部分,应注意这些部分)。我假设我误用了Get-WMIObject或类似的东西,任何人都可以看到它为什么会像这样提取信息?

$csvRunFile = "test.csv"
$output = "Results_$(Get-Date -format yyyy.MM.dd).csv"

#Import the created csv. 
$csv = import-csv $CsvRunFile

$results = foreach($csv_line in $csv) {
    $ctag = $csv_line.ctag
    $test_ping = test-connection $ctag -Count 1 -Quiet


    #If the computer is pingable (IE: Online)
    switch ($test_ping) {
        $true {
            #Pull the actual logged in user. 
            $Username = (Get-WmiObject -ComputerName $ctag -Class Win32_ComputerSystem).Username.Split("\\")[1]

            #If the last modified folder is 'public' put an error, otherwise pull the username's information from AD. 
            #This was from when it pulled from the \User folder rather than the last log in, this is probably removeable. 
            if ($Username -eq "Public") {
                $ADName = "No User"
            } else {
                $ADName = Get-ADUser -Identity $Username
                $ADName = $ADName.Name
            } #end If
        }#end Switch:True

    #Show there was an error when pinging the computer. 
        $false {$ADName = "ERROR"}
    }#end Switch

    #write the results the new output CSV. 
    $result = [PSCustomObject]@{
        CTAG = $ctag
        Username = $ADName
    }#end PSCustom Object

    $result
} #end foreach

#Turn the .txt into a CSV so it can be manually compared to the list in the original excel file.
$results | Export-Csv -path $output

1 个答案:

答案 0 :(得分:0)

$UserName由于某些原因可能存在剩余价值,或者$ADName仍然是旧值,因为您在没有用户登录时尝试运行Get-ADUser -Identity $null on(当没有用户登录时,WMI返回$null。)

我还将ping测试从交换机更改为if-test只是为了清理代码。我从未见过Public被退回,但我离开了它,因为它也没有真正受伤。

尝试:

#If the computer is pingable (IE: Online)
if($test_ping) {
    #Clear username var just to be safe
    $Username = $null
    #Pull the actual logged in user. 
    $Username = (Get-WmiObject -ComputerName $ctag -Class Win32_ComputerSystem).Username | ? { $_ } | % { $_.Split("\\")[1] }

    #If the last modified folder is 'public' put an error, otherwise pull the username's information from AD. 
    #This was from when it pulled from the \User folder rather than the last log in, this is probably removeable. 
    if (($Username -eq "Public") -or ($Username -eq $null)) {
        $ADName = "No User"
    } else {
        $ADName = Get-ADUser -Identity $Username
        $ADName = $ADName.Name
    } #end If username public
} else { $ADName = "ERROR"}