我是powershell的新手,并且有一个脚本可以从数据库服务器ping每台计算机。 我正在使用MySQL(是的,我知道大多数人使用MSSQL和PowerShell,但在我的情况下,我必须使用MySQL)。
ping运行得很好,如何为每台成功ping的计算机检索USERNAME?
提前致谢!
以下是我的代码:
#ping the computers from the database to verify if it is online/offline
#Create a command object
$command = New-Object MySql.Data.MySqlClient.MySqlCommand;
$command.Connection = $connection
# $command = $connection.CreateCommand() #ERROR
#call procedure to execute the command
$command.CommandText = "SELECT w.ws FROM
sandbox_maesc4.coordinates c
INNER JOIN
softphone_materials_updater.workstations w
ON c.station_number = w.pod";
#Execute the Command by reading each row
$reader = $command.ExecuteReader();
#Read values from database
$workstation_list = $( while ($reader.Read() ){
$reader.GetValue(0)
})
#close reader
$reader.Close()
#ping each computer if online, obtain username logged in only
foreach($pc_db in $workstation_list){
if(Test-Connection -ComputerName $pc_db -Count 1 -ErrorAction SilentlyContinue){
#HERE IS THE CODE, I JUST WANT TO RETRIEVE USERNAME THAT'S LOGGED ON!
Get-WMIObject -ComputerName $pc_db -Class Win32_ComputerSystem | Select-Object -ExpandProperty Username
}
else{
Write-Host "$pc_db is Offline" -ForegroundColor Red
}
}#end for each loop
$connection.Close()
}#end ping_test function
db_conn #execute function
答案 0 :(得分:1)
如果您正在查找当前登录用户的用户名,则可以引用Win32_ComputerSystem
WMI对象,该对象具有包含当前登录用户的username
参数:
Get-WMIObject -ComputerName $pc_db -Class Win32_ComputerSystem | Select-Object -ExpandProperty Username
答案 1 :(得分:1)
您可以使用
Get-CimInstance -ComputerName $pc_db -class Win32_ComputerSystem | select username
这应该返回当前活动的用户