View recent remote powershell connections - powershell

Is there an event log of some kind that is made when a remote pssession is initiated on a computer? I need to be able to see where a remote session has originated from.
Currently I am running
Get-EventLog -LogName "Windows powershell" -newest 100 | Format-List -Property * | where {$_.UserID -eq "username"}
But it is not filtering and/or showing remote connections.

We are here to help you with code issues. This is really not a code issue, but a understanding of how to set up and where correlate such detail. So, it's potentially a question for another forum.
Anyway, to get you close to what you are after, there are extra steps you need to employ to get such information. More on that in a bit.
Now, once you get this all setup and you write your script to pull / look at such info and you are having issues with that, then post that back here for folks to see what can be done
So, that leads us to here:
There are three general areas for logging available:
• Module Logging
• Script Block Logging
• PowerShell Transcription
If you have not done so, I would advise enabling on PS auditing and script logging for more insight into this use case and well as transcript logging (which can capture all commands / code executed on a host machine). If you set all this up properly, you fist look to the transcript log for details and well as the log name you reference in your post for other details.
Set this enterprise wide via GPO or DSC.
There is lot's of guidance on how to set this up.
For Example:
Audit PowerShell Usage using Transcription and Logging
Get-Command -Name '*transcript*'
CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Get-TRSTranscriptionJob 3.3.234.0 AWSPowerShell
Cmdlet Get-TRSTranscriptionJobList 3.3.234.0 AWSPowerShell
Cmdlet Start-Transcript 3.0.0.0 Microsoft.PowerShell.Host
Cmdlet Start-TRSTranscriptionJob 3.3.234.0 AWSPowerShell
Cmdlet Stop-Transcript 3.0.0.0 Microsoft.PowerShell.Host
https://learn.microsoft.com/en-us/powershell/wmf/5.0/audit_overview
Practical PowerShell Security: Enable Auditing and Logging with DSC
https://blogs.technet.microsoft.com/ashleymcglone/2017/03/29/practical-powershell-security-enable-auditing-and-logging-with-dsc
More New Stuff in PowerShell V5: Extra PowerShell Auditing
Get-Module Microsoft.* | Select Name, LogPipelineExecutionDetails
Get-Module Microsoft.* | ForEach { $_.LogPipelineExecutionDetails = $True }
(Import-Module ActiveDirectory).LogPipelineExecutionDetails = $True
Get-WinEvent -FilterHashtable #{LogName='Windows PowerShell';Id ='800'} -MaxEvents 1 | Select -Expand Message
https://learn-powershell.net/2014/08/26/more-new-stuff-in-powershell-v5-extra-powershell-auditing
Investigating PowerShell: Command and Script Logging
https://www.crowdstrike.com/blog/investigating-powershell-command-and-script-logging

Related

How to clear a event log in Powershell 7

in Powershell 5 we can clear a Windows-Event-Log in this way:
Get-EventLog -LogName * | % { Clear-EventLog -LogName $_.log }
how to do this in Powershell 7??? (using powershell only)
Powershell way of handling windows events is now with Get-WinEvent
but it appears no Clear-WinEvent is available
of course we can do this with wevtutil.exe
or even brute-forcing the logs file deletion after stopping the service...
but i'm asking only with native powershell code.
Well this is interesting. Clear-WinEvent indeed is not part of PowerShell 7. There was an issue raised to get it added but doesn't like that's going anywhere without more action.
The Microsoft approved way to do this is:
Import-Module Microsoft.PowerShell.Management -UseWindowsPowerShell
Get-EventLog -LogName * | % { Clear-EventLog -LogName $_.log }
This spins up a Windows PowerShell 5.1 process that runs in the background and invokes the Cmdlet via implicit remoting... not the best.
A better way would be to leverage the .NET EventLogSession.ClearLog method:
Get-WinEvent -ListLog * | foreach {
[System.Diagnostics.Eventing.Reader.EventLogSession]::GlobalSession.ClearLog($_.LogName)
}
Aside - PowerShell 7 module compatibility lists the Microsoft.PowerShell.Management module (that Get-EventLog and Clear-EventLog are part of) as 'Built into PowerShell 7'

Is there a way to find which user run what application on a server using Powershell

I am trying to find a way to find out who has ran an application (for example SQL) on a server, just to get some idea.
I tried Get-Process but this doesn't give me historic information, I want to get historical information
Get-Process -IncludeUserName *
what I want the return resule is "name of application", "user who ran it" and the last datetime it was ran by that user'
As for ...
I am trying to find a way to find out who has ran an application (for
example SQL) on a server, just to get some idea.
What you are asking for here is software metering.
SQL is a service that is always running once it is installed, so, no individual user is ever going to be running it. So, that is a bad example. MS Word for example would be a better example.
Yet there is nothing native in PowerShell that does this, software metering, but of course PowerShell can look at event logs. Yet if your auditing is not setup correctly then it's moot. This is better for a software metering tool, and there are several out there. So, why try and reinvent the wheel.
As for ...
I tried Get-Process but this doesn't give me historic information, I
want to get historical information
That is not what a process is nor what Get-Process is for. It, Get-Process only checks for and lists whatever process is currently running, regardless of what/who launched it.
As for...
what I want the return resule is "name of application", "user who ran
it" and the last datetime it was ran by that user'
As long as the process is running, you can get this, with that cmdlet.
However, what are you trying to accomplish by this?
Again, there are purpose built tools to meter software use.
https://learn.microsoft.com/en-us/sccm/apps/deploy-use/monitor-app-usage-with-software-metering
If you must go down this reinvent the wheel road, using scripting, then you need a task watcher on the target machines, which watches for the WinWord process to appear.
Get-Process -IncludeUserName |
Where ProcessName -EQ 'Winword'
... you then write those results to a file or database or your own event log each time you see that process.
Use PowerShell to Create and to Use a New Event Log
New-EventLog -LogName ScriptingGuys -Source scripts
When the command runs, no output appears to the Windows PowerShell console. To ensure the command actually created a new event log, I use
the Get-EventLog cmdlet with the –List parameter. Here is the command
and the associated output.
Write-EventLog -LogName ScriptingGuys -Source scripts -Message “Dude, it works … COOL!” -EventId 0 -EntryType information
Or just to a file
Get-Process -IncludeUserName |
Where ProcessName -EQ 'Winword' |
Select-Object -Property Name, StartTime, Username |
Export-Csv -Path 'F:\Temp\AppLaunchLog.csv' -Append
Import-Csv -Path 'F:\Temp\AppLaunchLog.csv'
# Results
Name StartTime UserName
---- --------- --------
WINWORD 5/23/2019 9:02:53 PM WS01\LabUser001

How do I use Get-EventLog to get the same result of Get-WinEvent in PowerShell?

I am working on Windows Server 2003 and I need to get something like the following by using this command Get-WinEvent -ListLog Application, Security, System
LogMode MaximumSizeInBytes RecordCount LogName
------- ------------------ ----------- -------
Circular 33554432 15188 Application
Circular 201326592 298459 Security
Circular 33554432 10074 System
I need the result of the property MaximumSizeInBytes but Get-WinEvent is not supported on Server 2003
I see that Get-EventLog has a property called MaximumKilobytes but the result I get is different
I would like to know if there is a command can be ran locally to get the same result
First why are you still on WS2K3? --- ;-}
Before you respond, I know, I know, some orgs... right!? ;-}
Yet, unless someone on this site has WS2K3, there is no way for them to validate stuff.
This cmdlet not supported on WS2K3 is not a bug or missing thing. cmdlets are OS version and PowerShell version specific.
All that being said. Just because a command does not exist on your system, does not mean you cannot try use it.
This is why implicit PSRemoting exists.
Remoting the Implicit Way
Using implicit PowerShell remoting to import remote modules
Mostly you see this used for ADDS, Exchange, O365 cmdlets and the like, but you can do it for any module / cmdlet on a remote host to use on your local session. Using implicit remoting the cmdlet really does not run on your system it is proxied. Just be sure to use the -prefix argument so to not end up with duplicate cmdlets being listed.
Example
$RemoteSession = New-PSSession -ComputerName 'RemoteHost' -Credential (Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME")
Import-PSSession -Session $RemoteSession -Prefix RS
So, no you call the cmdlets using the prefix when you want to use one from that session.
Get-RSWinEvent
Now, as I said, I have no WS2K3 boxes to mess with as I am all WS2K12R2/16/19. Yet, give it a shot.
As no one has provided a satisfying answer yet I will just post the answer I found online here. The following command saved my life:
Get-WmiObject -Class Win32_NTEventLogFile | Select-Object -Property MaxFileSize, LogfileName, Name, NumberOfRecords
I will not choose my own answer as the final answer just yet so if you can think of a better solution please feel free to add it :)
Thank you for viewing my post and tried to help

How to get Log On As account for Windows Service via PowerShell

New to powershell and I'm guessing this exists but I cannot find. I am looking for a powershell command that will show me the account being used to run a Windows Service? I am first as going to check it is running, then make sure it is running using the correct AD account. I have the following so far...
$serviceName = '<my service name>'
If (Get-Service $serviceName -ErrorAction SilentlyContinue) {
If ((Get-Service $serviceName).Status -eq 'Running') {
$status = "$serviceName found and is running."
} Else {
$status = "$serviceName found, but it is not running."
}
#Here is where I should check Log On As name
} Else {
$status = "$serviceName not found."
}
write-host "Status: $status`n"
pause
Most of my searches lead me to Get-WmiObject, but I did not find what I was looking for. Thanks in advance for any help.
(Get-WmiObject Win32_Service -Filter "Name='$serviceName'").StartName. (Yes, the name of this property is rather counter-intuitive, but the docs don't lie).
You could also use the more recent CIM cmdlets. Which is which is really where MS wants and is directing folsk to use.
Get-CimInstance -ClassName CIM_Service | Select-Object Name, StartMode, StartName
What is CIM and Why Should I Use It in PowerShell?
https://blogs.technet.microsoft.com/heyscriptingguy/2014/01/27/what-is-cim-and-why-should-i-use-it-in-powershell
Update for WMI
In Windows PowerShell 4.0 and Windows PowerShell 3.0, Microsoft offered an updated method for interacting with WMI: the CIMCmdlets module for Windows PowerShell. With this new Windows PowerShell module release, Microsoft also released an entirely new Application Programming Interface (API) for Windows called Management Infrastructure (MI).
The new MI API more closely aligns to the DMTF standards, as laid out on MSDN in Why Use MI? MI allows software developers and hardware manufacturers to expose information, and it allows IT professionals to interact with hardware, using standards-based mechanisms. As this technology continues to evolve, I believe that we will see more cross-platform integration between Microsoft Windows and competing platforms.
Should I use CIM or WMI with Windows PowerShell?
https://blogs.technet.microsoft.com/heyscriptingguy/2016/02/08/should-i-use-cim-or-wmi-with-windows-powershell
Get-WmiObject is one of the original PowerShell cmdlets. (As a quick quiz, how many of the 137 original cmdlets can you name?). It was enhanced in PowerShell 2.0 when the other WMI cmdlets were introduced. In PowerShell 1.0, Get-WmiObject was the only cmdlet with the option to access another system.
The big drawback to the WMI cmdlets is that they use DCOM to access remote machines. DCOM isn’t firewall friendly, can be blocked by networking equipment, and gives some arcane errors when things go wrong.
The CIM cmdlets appeared in PowerShell 3.0 as part of the new API for working with CIM classes, which is more standards based. The CIM cmdlets were overshadowed by PowerShell workflows, but they are (to my mind) the most important thing to come out of that release.
The other major CIM-related advance was the introduction of CDXML, which enables a CIM class to be wrapped in some simple XML and published as a PowerShell module. This is how over 60% of the cmdlets in Windows 8 and later are produced.
With Powershell 7, you can retrieve the logon as user like this:
(Get-Service $serviceName).username

Get-WinEvent via Powershell remoting

I have a non-admin access to a server. I'm allowed to connect via RDP, and to use PowerShell remoting. When I invoke the following PowerShell command from an RDP session:
Get-WinEvent -MaxEvents 100 -Provider Microsoft-Windows-TaskScheduler
I get 100 records, as expected.
When I do the same via PowerShell remoting, by invoking the following from my local machine:
invoke-command -ComputerName myserver {Get-WinEvent -MaxEvents 100 -Provider Microsoft-Windows-TaskScheduler }
I get an error:
No events were found that match the specified selection criteria.
CategoryInfo : ObjectNotFound: (:) [Get-WinEvent], Exception
FullyQualifiedErrorId : NoMatchingEventsFound,Microsoft.PowerShell.Commands.GetWinEventCommand
Any idea why? The remote PowerShell session should be running under identical credentials, right?
EDIT: whoami does show a difference in the security context between RDP logon and PowerShell remoting - the group set is different. In the RDP logon session, there are the following groups in the token:
BUILTIN\Remote Desktop Users
NT AUTHORITY\REMOTE INTERACTIVE LOGON
while in the remoted one, there's
CONSOLE LOGON
That could account for the discrepancy in rights...
EDIT: from the registry, it looks like the task scheduler log somehow is a part of the System log. According to MS KB article Q323076, the security descriptor for the System log can be found under HKLM\SYSTEM\CurrentControlSet\Services\EventLog\System, value CustomSD. I can't check the server in question, but on another server where I'm an admin, there's no CustomSD under that key. Under HKLM\SYSTEM\CurrentControlSet\Services\EventLog\System\Microsoft-Windows-TaskScheduler, neither. Only the Security log gets a CustomSD. The next question is, where's the default SD?
Permissions on the actual log file at C:\Windows\System32\winevt\LogsMicrosoft-Windows-TaskScheduler%4Operational.evtx are irrelevant, the access is being mediated by the EventLog service anyway.
If you are not an administrator on the remote computer, and invoke-command -ComputerName myserver {whoami /all} tells you are who you expected to be.
You will need to be part of Event Log Reader group on the remote computer.
As well as Remote Management Users group, which I believe you already are.
If you need to read security logs, you will also need Manage auditing and security log under Local Security Policy -> Security Settings -> Local Policies -> User Rights Assignment
According to Default ACLs on Windows Event Logs # MSDN blog, in Windows Server 2003+, the default ACL for the System log goes:
O:BAG:SYD:
*(D;;0xf0007;;;AN) // (Deny) Anonymous:All Access
*(D;;0xf0007;;;BG) // (Deny) Guests:All Access
(A;;0xf0007;;;SY) // LocalSystem:Full
(A;;0x7;;;BA) // Administrators:Read,Write,Clear
(A;;0x5;;;SO) // Server Operators:Read,Clear
(A;;0x1;;;IU) // INTERACTIVE LOGON:Read <===================
(A;;0x1;;;SU) // SERVICES LOGON:Read
(A;;0x1;;;S-1-5-3) // BATCH LOGON:Read
(A;;0x2;;;LS) // LocalService:Write
(A;;0x2;;;NS) // NetworkService:Write
Does NT AUTHORITY\INTERACTIVE LOGON include RDP logon? I've found a forum message that says so, but I'd better find a doc to that effect...
The article claims this ACE comes "straight from the source code". So it's hard-coded in the service, with a chance to change via the registry.
You need local admin rights to open a powershell session.
But there is a workaround/alterative here:
https://4sysops.com/archives/powershell-remoting-without-administrator-rights/
I had the weirdest variation of this problem, was driving me nuts !
Remoting from a server W2008r2 (logged on as domain admin, inside interactive powershell session) to workstation Win7 to get logon/logoff events :
invoke-command -computername $pc {Get-WinEvent -FilterHashtable #{logname='
Security';Id=#(4624,4634)}}
-> No events were found that match the specified selection criteria.
But it does work when outputting an empty string in the scriptblock before the Get-Winevent :
invoke-command -computername $pc {"";Get-WinEvent -FilterHashtable #{lognam
e='Security';Id=#(4624,4634)}}
TimeCreated ProviderName Id Message PSComputerName
----------- ------------ -- ------- --------------
19/03/2018 11:51:41 Microsoft-Windows-Se... 4624 An account was succe... b25_x64
19/03/2018 11:51:41 Microsoft-Windows-Se... 4624 An account was succe... b25_x64
Stumbled upon this fix after trying everything: Enter-Pssession, New-Pssession, using -credential parameter to pass a predefined credential to invoke-command, to get-winevent, to both. Nothing worked, gave "No events..." in every combination.
Then I inserted a $cred inside the scriptblock to show the passed on credential for debugging, and suddenly I got the events I was looking for...