使用电源外壳获取当前用户上下文



我有一个Powershell脚本作为计划任务运行。 出于提升原因,任务以脚本用户身份运行,但我确实需要脚本能够确定脚本运行时登录并处于活动状态的用户(它需要能够从其配置文件中复制文件)。

是否有可用于获取当前用户上下文的命令?

这可能对登录用户有用(抱歉,不知道原始来源)

$owners = @{}
Get-WmiObject win32_process -ComputerName $computer -Filter 'name = "explorer.exe"' | % {$owners[$_.handle] = $_.getowner().user}
Get-Process -ComputerName $computer explorer | % {$owners[$_.id.tostring()]}

如果这没有得到你要找的东西,你可以通过这个Get-LogonHistory函数利用事件日志

https://social.technet.microsoft.com/Forums/office/en-US/4f6815f1-2998-484c-a423-fe6507f1548c/powershell-script-to-fetch-logonlogoff-user-on-particular-server-getwinevent-geteventlog?forum=winserverpowershell

function Get-LogonHistory {
    param (
        [string]$comp = $env:COMPUTERNAME,
        [int]$Days = 7
    )
    $Result = @()
    Write-Host 'Gathering Event Logs, this can take awhile...'
    $ELogs = Get-EventLog System -Source Microsoft-Windows-WinLogon -After (Get-Date).AddDays(-$Days) -ComputerName $comp
    if ($ELogs) {
        Write-Host 'Processing...'
        foreach ($Log in $ELogs) {
            if ($Log.InstanceId -eq 7001) {
                $ET = 'Logon'
            } elseif ($Log.InstanceId -eq 7002) {
                $ET = 'Logoff'
            } else {
                Continue
            }
            $Result += New-Object PSObject -Property @{
                Time = $Log.TimeWritten
                EventType = $ET
                User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])
            }
        }
        $Result | Select Time, EventType, User | Sort Time -Descending | Out-GridView
        Write-Host 'Done.'
    } else {
        Write-Host "Problem with $comp."
        Write-Host 'If you see a "Network Path not found" error, try starting the Remote Registry service on that computer.'
        Write-Host 'Or there are no logon/logoff events (XP requires auditing be turned on)'
    }
}
Get-LogonHistory

*编辑:这是我对Eris提到的qwinsta的发现

<# all give about the same information. the first two might give more
# https://www.reddit.com/r/PowerShell/comments/4dwqlc/crypto_tripwire_-_help_with_script/d1v0jg5?context=3
(quser) -replace 's{2,}', ',' | ConvertFrom-Csv
$server = 'localhost'
# IDENTICAL
query session /server:$server
qwinsta /server:$server
# IDENTICAL
query user /server:$server
quser /server:$server
qprocess explorer.exe /server:$server
#>

最新更新