AD通过计算机名批量查询计算机的当前登录账号

这几天总是在工作中收到安全部门的邮件,好多机器需要重做系统,然后需要知道这些机器的使用人是谁,由于我们公司机器很多而且流动挺大的,没有统计机器的设备表,需要我们去查询到当前用户的使用人。之前也有这种情况,但是都是零零散散的需求,这次因为疫情,好多时间没有上班导致很多电脑在更新过程中出现问题,一下次都是几十个计算机名需要查询,一个一个查询效率太低,所以就想做个脚本出来,下次可以方便点,这点在运维工作中其实很重要,特别是这种重复工作的,第一次消耗点时间,之后的工作会很简单。

我是通过powershell做的脚本,下面我会将脚本分享出来,因为本人也是刚刚开始学习powershell,如果有更好的办法,希望大神朋友可以私信我,让我也学习下,我会发了小红包表示感谢,哈哈。

以下就是我做的脚本:

Import-Module activedirectory

#导入AD模块

$computeraccount= Get-Content D:\\count\\computer.csv

#获取当前需要查询的计算机列表文件

foreach ($currentcomputename in $computeraccount)

#根据计算机对象进行轮询

{

if((Test-Connection -ComputerName $currentcomputename -count 1 -ErrorAction 0))

#测试计算机是否可以ping通,如果可以ping通,则继续执行

{

$currentcomputename+"正测试IP连通性..."

$currentname= Get-ADComputer -Identity $currentcomputename|select -ExpandProperty name

#获取计算机名,后面导出到表格里方便点

$currentuser=(Get-WmiObject Win32_Process -Filter 'Name="explorer.exe"' -ComputerName $currentcomputename).getOwner() | Select -ExpandProperty User

#根据计算机当前计算机名

$computerproperty=New-Object psobject

#定义一个新PS 对象

$computerproperty| Add-Member -MemberType NoteProperty -Name "computerName" -Value $currentname

#给新表格增加一个叫computerName的列

$computerproperty| Add-Member -MemberType NoteProperty -Name "account" -Value "$currentuser"

#给新表格增加一个叫account的列


$computerproperty|Export-Csv -Encoding default -NoTypeInformation -append -Path d:\\count\\loginUser\\online.csv

#将数据导出为csv 文件,我们直接通过CSV 文件来获取希望拿到的信息

$currentuser="暂时未有用户登录过"

#这个是为了防止有的计算机刚刚做个系统还没有登录名,导致表格里会写入上一条用户名

}

else{

$currentcomputename=Get-ADComputer -Identity $currentcomputename|select -ExpandProperty name

$computerproperty=New-Object psobject

$computerproperty| Add-Member -MemberType NoteProperty -Name "offline" -Value $currentcomputename

$computerproperty|export-csv -Encoding Default -NoTypeInformation -Append -Path d:\\count\\loginUser\\offline.csv

}

}

我是将在线和不线的电脑分开导出的,测试过了,能达到我所需要的要求,希望能给到有需要的人。


分享到:


相關文章: