使用powershell获取当前用户上下文

时间:2016-07-06 16:42:35

标签: windows powershell

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

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

1 个答案:

答案 0 :(得分:0)

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

$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

*编辑:以下是我对Ew提到的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
#>