powershell - 如何从用户列表中找到 PC
问题描述
我需要帮助。我不太确定这是否可能。
我有文件列表,samAccountName
我.csv
需要从中获取他们的 PC 名称和 IP。
我不太确定如何构建这样的脚本。
解决方案
执行此操作的一种方法是遍历环境中的所有计算机并测试每一台计算机。这当然会很慢
问题中没有您的 CSV 文件是什么样子的示例,但如果它看起来像这样:
"SamAccountName","职务" "jdoe","testuser" "rboizov","系统管理员"
你可以做:
# get an aray if SamAccountNames from the Csv
$userNames = Import-Csv -Path 'PathToYOurCsvFile' | Select-Object -ExpandProperty SamAccountName
# get all computer objects from AD and loop through
# this of course can take a LONG time to finish..
$result = Get-ADComputer -Filter * | ForEach-Object {
Write-Host "Testing computer $($_.Name)"
if (Test-Connection -ComputerName $_.Name -Count 1 -Quiet) {
$pc = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $_.Name
# or use: $pc = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $_.Name
$user = ($pc.UserName -split '\\')[-1]
if ($userNames -contains $user) {
[PSCustomObject]@{
'SamAccountName' = $user
'ComputerName' = $pc.Name
'IP' = (Test-Connection -ComputerName $pc.Name -Count 1).IPV4Address.IPAddressToString
}
}
}
else {
Write-Warning "Computer $($_.Name) could not be reached"
}
}
#output in console
$result
# output to Csv
$result | Export-Csv -Path 'UsersOnComputers.csv' -NoTypeInformation
可能有一种更快的方法,但只有当您的用户的所有主目录都已重定向到中央服务器\共享时才能工作。如果您的环境是这种情况,请告诉我
实验性的
以下方法用于Win32_ServerConnection
查找到用户 HomeDrive 文件夹的所有会话。
仅当您的用户的所有主目录都已重定向到中央\\server\share
时,这才有效,当然,如果您的权限允许它
# the UNC \\Server\Share name of the network share where all user homedirectories are
$usersHomePath = '\\HomesServer\HomesShare$'
# get an aray if SamAccountNames from the Csv
$userNames = Import-Csv -Path 'PathToYOurCsvFile' | Select-Object -ExpandProperty SamAccountName
# split the UNC path to get the server name and share name separate
$svr = $usersHomePath.TrimStart("\") -split '\\' #"# fix syntax highlighting for SO..
$server = $svr[0]
$share = $svr[-1]
$result = Get-CimInstance -ClassName Win32_ServerConnection -ComputerName $server | # or use: Get-WmiObject -Class Win32_ServerConnection
Where-Object { $_.ShareName -eq $share -and $userNames -contains $_.UserName } |
Select-Object @{Name = "SamAccountName"; Expression = { $_.UserName }},
@{Name = "ComputerName"; Expression = {(([System.Net.Dns]::GetHostEntry($_.ComputerName).HostName) -split "\.")[0]}},
@{Name = "IP"; Expression = { (Test-Connection -ComputerName $_.ComputerName -Count 1).IPV4Address.IPAddressToString }} |
Sort-Object SamAccountName
#output in console
$result
# output to Csv
$result | Export-Csv -Path 'UsersOnComputers.csv' -NoTypeInformation
推荐阅读
- javascript - 采样器立方体引用的纹理不可渲染
- javascript - Javascript生成字符串时如何忽略输入
- python - 我们可以使用任何 Python 工具验证 USDZ 模型吗?
- excel - 链接到 EXCEL DDE 的 MATLAB 代码不会暂停。我应该怎么办?
- vue.js - 启用 Tailwind 即时 (JIT) 可防止构建
- 3d - 在 python 底图或 cartopy 中访问底层投影函数
- python - tf.Keras 学习率计划——传递给优化器还是回调?
- java - 如何将网页视图退出到最后一个片段?
- java - spring framework - 传递rental_id来制作费用对象
- python - 类型错误:einsatznummer_generator() 缺少 1 个必需的位置参数:'self'