我在Windows Server 2008 R2上使用Powershell,我需要任何常规用户获取AD名称和姓氏的流程所有者。
这里的剧本是在 Mathias R. Jessen的帮助下写的
Import-Module ActiveDirectory
$ProcessWithOwners = Get-WmiObject Win32_Process -Filter 'Name LIKE "vr[0-9]%"' |Select *,@{Name="Owner";Expression={$_.GetOwner().User}}
foreach($Process in $ProcessWithOwners)
{
$Username = $Process.Owner
$ADUser = Get-ADUser -Filter "SamAccountName -eq '$Username'" -properties *
$a = new-object -comobject wscript.shell
$b = $a.popup(“Process name $($Process.Name) is run by user $($ADUser.DisplayName)“,0,“Warning”,1)
}
但普通用户无法访问进程的所有者。
有什么办法可以解决吗?
*最终更新*
为了以普通用户身份运行此脚本,我做了一些更改:
Import-Module ActiveDirectory
Add-Type -Name win -MemberDefinition '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);' -Namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle,0)
$ConsProcess = Get-WmiObject Win32_Process -Filter 'Name LIKE "vr[0-9]%"' | Select *,@{Name="Owner";Expression={$_.GetOwner().User}}
if ($ConsProcess -ne $null) {
foreach($Process in $ConsProcess)
{
$QueryProcess = query process $Process.ProcessName
$Id = ($QueryProcess[1] -replace ' +',' ').Trim().Split(' ')[2]
$QueryUser = query session $Id
$User = ($QueryUser[1] -replace ' +',' ').Trim().Split(' ')[1]
$ADUser = (Get-ADUser -Identity $User -Properties *).DisplayName
$a = new-object -comobject wscript.shell
$b = $a.popup(“Консультант запущен с именем $($Process.Name) пользователем $($ADUser)“,0,“Внимание”,1)
}
}
else
{
& 'D:\consultantplus\cons.exe' /adm /inet
}

答案 0 :(得分:0)
当您只需要所有者时,没有理由同时拨打Get-Process
和 $CmdProcessWithOwners = Get-WmiObject Win32_Process -Filter 'Name LIKE "cmd%"' |Select *,@{Name="Owner";Expression={$_.GetOwner()}}
。
你可以只做:
foreach($Process in $CmdProcessWithOwners)
{
# Grab the user name we added earlier
$Username = $Process.Owner.User
$Domain = $Process.Owner.Domain
$DisplayName = switch($Domain)
{
'DOMAINNAME' {
# Process owned by AD User, grab name from AD
Get-ADUser -Filter "SamAccountName -eq '$Username'" -Properties DisplayName |Select-Object -ExpandProperty DisplayName
}
$env:ComputerName {
# Process owned by local user, look up local account full name
[adsi]"WinNT://$($env:ComputerName)/$Username,user" |Select-Object -ExpandProperty FullName
}
default {
# Likely system or virtual account, default to DOMAIN\Username
"$Domain\$Username"
}
}
# Print it
Write-Host "Process $($Process.Name) with ID $($Process.Id) belongs to $DisplayName"
}
由于您可能会找到多个符合条件的流程,因此您可能希望在循环中迭代流程:
{{1}}