powershell get-winevent how to get only path and exe file? - powershell

How to get from applocker winevent only path of file and name of file (file.exe), i mean how to filter this info
Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EXE and DLL"

Have a look at the below, to see if this helps your use case. I too, don't have this on a system I can test at this point.
<#
Pull all AppLocker logs from the live AppLocker event log
(requires Applocker)
#>
Get-WinEvent -logname "Microsoft-Windows-AppLocker/EXE and DLL"
<#
Search for live AppLocker EXE/MSI block events: "(EXE) was prevented
from running":
#>
Get-WinEvent -FilterHashtable #{
logname = 'MicrosoftWindows-Applocker/EXE and DLL'
id = 8004
}
<#
Search for live AppLocker EXE/MSI audit events: "(EXE) was allowed
to run but would have been prevented from running if the AppLocker
the policy was enforced":
#>
Get-WinEvent -FilterHashtable #{
logname = 'MicrosoftWindows-Applocker/EXE and DLL'
id = 8003
}
Get-AppLockerEvent - Get event details related to AppLocker
activity
AppLocker events include a number of helpful details that are buried
within the event object or XML. This function will extract helpful
information like the username, rule name, file path, file hash, and
file signature details for easy viewing.
Download: Get-AppLockerEvent.ps1

That log is empty on my machine, but maybe you can do something with the xml from the event:
[xml]$xml = get-winevent application | select -first 1 |
foreach { $_.toxml() }
$xml.event
xmlns System EventData
----- ------ ---------
http://schemas.microsoft.com/win/2004/08/events/event System EventData
Oh I see, you have to restart the appidsvc after setting the group policy. You can use the filepath or fullfilepath properties:
$a = get-winevent "microsoft-windows-applocker/exe and dll" |
select -first 1
[xml]$xml = $a.toxml()
$xml.event.userdata.RuleAndFileData
xmlns : http://schemas.microsoft.com/schemas/event/Microsoft.Windows/1.0.0.0
PolicyNameLength : 3
PolicyName : EXE
RuleId : {fd686d83-a829-4351-8ff4-27c7de5755d2}
RuleNameLength : 24
RuleName : (Default Rule) All files
RuleSddlLength : 53
RuleSddl : D:(XA;;FX;;;S-1-5-32-544;(APPID://PATH Contains "*"))
TargetUser : S-1-5-21-1528843147-373324174-1919417754-1001
TargetProcessId : 3876
FilePathLength : 51
FilePath : %PROGRAMFILES%\GOOGLE\CHROME\APPLICATION\CHROME.EXE
FileHashLength : 0
FileHash :
FqbnLength : 1
Fqbn : -
TargetLogonId : 0x4d253a0
FullFilePathLength : 59
FullFilePath : C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

Related

Obtain display name with spaces from powershell or cmd - AzuredAD only

I am try to pull just the display name (first and last name) from cmd or powershell. (AzureAD - not on-prem AD)
I have gotten a couple of different commands but all of them keep the name together.
Examples:
$env:UserName = jatonjustice
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name = azureAD\jatonjustice
I am trying to find a way where the result has the first and last name separated or maybe just the first and just the last name as an alternate idea.(Like: `Jaton Justice') I can't parse it myself as I don't know what the display name will be upfront. (AzureAD - not on-prem AD)
Any ideas for this?
research:
How do I get the current username in Windows PowerShell?
How to get an Azure Active Directory username in Windows Powershell?
Thanks
$env:UserName should return SamAccountName, rather than user's name.
'Get-ADUser -Property *' should show you all info about the user you are querying, you should be able to find a property called GivenName and Surname.
$search = [adsisearcher]"(SamAccountName=$env:USERNAME)"
$search.PropertiesToLoad.AddRange(#('givenname','sn'))
$adAccount = $search.FindOne()
$firstName = $adAccount.Properties.givenname
$lastName = $adAccount.Properties.sn
$fullname = "$firstName $lastName"
All you are after is explained and detailed by examples in the PowerShell help files. More on that later.
As for ...
'but all of them keep the name together. Examples:'
...and they are supposed to, by design.
Using those, you are asking for the local logged-on username (SamAccountName, which is a short name defined in the user profile on the localhost and in ADDS/AAD - for the UPN, SamAccountName#DomainName.com) with those, not ADDS/AAD name specifics.
If you want First and last from the locally logged-on user, then you have to have that populated in the account, or you have to ask for it from ADDS/AAD. What is your use case?
If you are on PSv5x and higher there is this module:
# Results
<#
Get-Module -Name '*local*'
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Binary 1.0.0.0 Microsoft.PowerShell.LocalAccounts {Add-LocalGroupMember, Disable-LocalUser, Enable-LocalUser, Get-LocalGroup...}
#>
You get local user details this way.
Get-LocalUser | Select-Object -Property '*' -First 1
# Results
<#
AccountExpires :
Description : Built-in account for administering the computer/domain
Enabled : False
FullName :
PasswordChangeableDate :
PasswordExpires :
UserMayChangePassword : True
PasswordRequired : True
PasswordLastSet :
LastLogon :
Name : Administrator
SID : S-1-5-21-2047949552-857980807-821054962-500
PrincipalSource : Local
ObjectClass : User
#>
Note that on his local account, Fullname is not populated. So, obviously, you can't use that, nor can you extrapolate from the name/SamAccoutnName property.
So, you can ask for the locally logged on username in a number of ways,...
# Get loggedon users
$env:UserName
[System.Environment]::UserName
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
(Invoke-CimMethod -InputObject $(
Get-CimInstance Win32_Process -Filter "name = 'explorer.exe'"
) -MethodName GetOwner).User
Get-WmiObject Win32_Process -Filter "name='explorer.exe'" |
Select Name, #{
Name = 'UserName'
Expression = {"$($PSItem.GetOwner().Domain)\$($PSItem.GetOwner().User)"}
} |
Sort-Object UserName, Name
(Get-Process -Name 'explorer' -IncludeUserName).UserName
(
Get-WMIObject -ClassName Win32_ComputerSystem |
Select-Object -Property Username
).username
[adsisearcher]"(SamAccountName=$env:USERNAME)"
whoami
... then use that Name/SamAccountName to ask ADDS/AAD what the user FullName or whatever you wish is.
If you are on an earlier version, you need to install one of these modules from Microsofts' powershelgallery.com...
Find-Module -Name '*local*'
# Results
<#
Version Name Repository Description
------- ---- ---------- -----------
...
1.6 localaccount PSGallery A Simple module to allow the management of local users and groups on a computer
1.0.0.0 Microsoft.PowerShell.LocalAccounts PSGallery Provides cmdlets to work with local users and local groups
3.0 LocalUserManagement PSGallery a module that performs various local user management functions
...
0.1.1 LocalAccountManagement PSGallery Manage local and remote user accounts and profiles
...
#>
... and do the same thing or use WMI, ADSI, etc.
[adsisearcher]"(SamAccountName=$env:USERNAME)"
# Results
<#
CacheResults : True
ClientTimeout : -00:00:01
PropertyNamesOnly : False
Filter : (SamAccountName=TestUser)
PageSize : 0
PropertiesToLoad : {}
ReferralChasing : External
SearchScope : Subtree
ServerPageTimeLimit : -00:00:01
ServerTimeLimit : -00:00:01
SizeLimit : 0
SearchRoot :
Sort : System.DirectoryServices.SortOption
Asynchronous : False
Tombstone : False
AttributeScopeQuery :
DerefAlias : Never
SecurityMasks : None
ExtendedDN : None
DirectorySynchronization :
VirtualListView :
Site :
Container :
#>
Now, back to my 'read the help file comment.'
Get-ADUser | MS DOcs
https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-aduser?view=windowsserver2019-ps
# Example 3: Get all of the properties for a specified user
Get-ADUser -Identity $env:USERNAME -Properties '*'
# Results
<#
Surname : David
Name : Chew David
UserPrincipalName :
GivenName : David
Enabled : False
SamAccountName : ChewDavid
ObjectClass : user
SID : S-1-5-21-2889043008-4136710315-2444824263-3544
ObjectGUID : e1418d64-096c-4cb0-b903-ebb66562d99d
DistinguishedName : CN=Chew David,OU=NorthAmerica,OU=Sales,OU=UserAccounts,DC=FABRIKAM,DC=COM
#>

Close-SMBOpenFile throws error and isn't caught in try-catch

We are using a TeamCity powershell in script execution mode as part of a pipeline with snapshot and artifact dependencies. We have a fairly robust system and have been using this particular process for a couple years, so this isn't brand new code that I'm debugging for the first time. Sadly. It normally works until it randomly doesn't. The TeamCity Agent is different when the error does occur.
This part of our process does some code deploy and some log backups. In order to completely do the backup, we have to ensure the files aren't kept open by QA or Devs at their desk looking at the logs and maybe have them open in read-write mode or the like. Because they would be opening them from their laptop/desktops, they are naturally SMB shares. So we have this function below that is supposed to close the files open on the given server. I say supposed to, because every once in a while it throws this error and I can't seem to either catch it (locally even) or suppress it, so it breaks the TeamCity run. (I've anonymized with ...SNIP anywhere the code is proprietary names or proprietary output)
You can actually test this on your machine by just navigating to \\yourhostname\c$\somefilepath\somefile and see that it will show that the files are open. It shouldn't fail on your machine once you've read through the code and see what it's doing, but if you take out all of the "precautions" you can potentially reproduce the error locally.
function Close-SMBApplicationLocks {
<#
.SYNOPSIS
Closes Active SMB Sessions for Default or User Supplied Paths
.DESCRIPTION
This function is used to prevent interruption to deployments by closing any SMB locks
in application paths. Defaults to closing sessions in folders matching regex
...SNIP
.PARAMETER Paths
[string[]] A string array of paths or path segments to match sessions against.
.EXAMPLE
Close-SMBApplicationLocks
...SNIP
.EXAMPLE
Close-SMBApplicationLocks -Paths #("TEMP")
...SNIP
#>
[CmdletBinding()]
param(
[Alias("SharePaths")]
[Parameter(Mandatory=$false)]
[string[]]$Paths
)
$pathsToUse = Test-IsNull ($Paths -join "|") "...SNIP"
Write-Verbose ("Looking for SMB Sessions Matching Path: {0}" -f $pathsToUse)
$smbSessions = #(Get-SmbOpenFile | Where-Object {$_.Path -match $pathsToUse})
if ((Test-IsCollectionNullOrEmpty $smbSessions)) {
Write-Host ("No Matching SMB Sessions Found")
return
}
Write-Verbose "Found $($smbSessions.Count) Matching SMB Sessions"
$uniqueFileIds = ($smbSessions).FileId | Sort-Object -Unique
foreach ($fileId in $uniqueFileIds) {
$session = #($smbSessions | Where-Object { $_.FileId -eq $fileId })[0]
$sessionId = $session.SessionId
$username = $session.ClientUserName
$path = $session.Path
Write-Verbose "Closing FileId $fileId on SMB Session $sessionId for user $username in path $path"
try {
if ($null -ne (Get-SmbOpenFile -FileId $fileId)) {
## Yes this is FOUR ways to suppress output.
## Microsoft has proven remarkably resilient at showing an error here.
## the ErrorAction Continue still throws an error in TeamCity but not locally
## The try catch doesn't catch
## The Out-Null is because on the off chance the redirect works on the output, it shouldn't show the faux-error
## The output redirection is because this error isn't written to "standard error"
## TeamCity seems to be not honoring this output redirection in the shell it's running under to execute this block
(Close-SmbOpenFile -FileId $fileId -Force -ErrorAction Continue *>&1) | Out-Null
## Run this line instead of the above to actually see the error pretty frequently, by my testing
## Close-SmbOpenFile -FileId $fileId -Force
}
} catch {
$errorMessage = $_.Exception.Message
Write-Warning "An Error Occurred While Trying to Close Session $sessionId : $errorMessage"
}
}
}
We were originally passing the session but I changed to this $fileId version of the code to see if I could clean it up like this with the unique and etc. Those don't seem to have improved things.
We could very well just do Get-SMBOpenFile | Where-Object <pathmatch> | Close-SMBOpenFile (see for example here https://serverfault.com/questions/718875/close-locked-file-in-windows-share-using-powershell-and-openfiles and here https://community.spiceworks.com/topic/2218597-issue-with-close-smbopenfile ) but as you can see we want to log that we are closing it in case we find that something went wrong and this helps us understand what.
Here's the error I have to fight:
[Clearing File Locks] No MSFT_SMBOpenFile objects found with property 'FileId' equal to '825975900669'. Verify the value of the property
[Clearing File Locks] and retry.
[Clearing File Locks] At C:\Program Files\WindowsPowerShell\Modules\...SNIP.psm1:2566 char:34
[Clearing File Locks] + $jobs | ForEach-Object { Receive-Job -Job $_ }
[Clearing File Locks] + ~~~~~~~~~~~~~~~~~~~
[Clearing File Locks] + CategoryInfo : ObjectNotFound: (825975900669:UInt64) [Get-SmbOpenFile], CimJobException
[Clearing File Locks] + FullyQualifiedErrorId : CmdletizationQuery_NotFound_FileId,Get-SmbOpenFile
[Clearing File Locks] + PSComputerName : localhost
[Clearing File Locks]
[Clearing File Locks] Process exited with code 1
But the thing is, just before I do that delete, I check once more to see that the file is open, right? So I say "does this exist? Yes? Close it" and yet, I get this error that makes no sense to me.
I have tried to come up with other ways on the object that's returned to ensure that I need to remove the file or if there's something that says "this should be skipped" but I can't figure anything out there.
Since I seem to be out of options here, is there an alternative method I've not considered? Some sort of CIMInstance command? I've obviously gone snow-blind if there is. This does run locally on the machine, not across a session.
Someone in my org finally noticed that the error does say Get-SmbOpenFile with the FileId parameter is the failure, so that has to be the same redirection error. At this point it looks like I may have an answer.
Snowblindness sucks
Pertinent machine details of note:
PS Z:\git\...SNIP> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.17763.1007
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17763.1007
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
PS Z:\git\...SNIP> Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, ServicePackMajorVersion, OSArchitecture, CSName, WindowsDirectory
Caption : Microsoft Windows 10 Enterprise LTSC
Version : 10.0.17763
ServicePackMajorVersion : 0
OSArchitecture : 64-bit
CSName : ...SNIP
WindowsDirectory : C:\Windows
But this is also running on Windows Server environments. Same version of PowerShell. Latest Windows patches etc on all servers. We haven't yet moved the fleet over to 2019 Datacenter, I know, but we have some odd 800 servers in production/testing across the fleet that I know of, these things take time of course. If 2016 is the problem, then that's the problem.
PS Z:\git\...SNIP> Get-CimInstance Win32_OperatingSystem -ComputerName ...SNIP | Select-Object Caption, Version, ServicePackMajorVersion, OSArchitecture, CSName, WindowsDirectory
Caption : Microsoft Windows Server 2016 Datacenter
Version : 10.0.14393
ServicePackMajorVersion : 0
OSArchitecture : 64-bit
CSName : ...SNIP
WindowsDirectory : C:\Windows
Maybe my solution is to get TeamCity to honor the output redirection? Is it Server 2016 not honoring the output redirection? Is this just a pipedream of trying to close these connections reliably? Is there a filesystem version I'm not thinking to check?
When I try to create a file at \\mymachine\c$\temp\temp.txt and open it, this is what I get (note that I'm only using notepad to open the file, so there's no lock ongoing)
PS Z:\git\devops_powershell> Get-SMBOpenFile
FileId SessionId Path ShareRelativePath ClientComputerName ClientUserName
------ --------- ---- ----------------- ------------------ --------------
1065151889485 1065151889409 C:\ ...SNIP ...SNIP
1065151889489 1065151889409 C:\ ...SNIP ...SNIP
1065151889613 1065151889409 C:\temp temp ...SNIP ...SNIP
1065151889617 1065151889409 C:\temp temp ...SNIP ...SNIP
1065151889833 1065151889409 C:\temp temp ...SNIP ...SNIP
PS Z:\git\...SNIP> Get-SmbOpenFile -FileId 1065151889833 | Select-Object -Property *
SmbInstance : Default
ClientComputerName : ...SNIP
ClientUserName : ...SNIP
ClusterNodeName :
ContinuouslyAvailable : False
Encrypted : False
FileId : 1065151889833
Locks : 0
Path : C:\temp
Permissions : 1048736
ScopeName : *
SessionId : 1065151889409
ShareRelativePath : temp
Signed : True
PSComputerName :
CimClass : ROOT/Microsoft/Windows/SMB:MSFT_SmbOpenFile
CimInstanceProperties : {ClientComputerName, ClientUserName, ClusterNodeName, ContinuouslyAvailable...}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
PS Z:\git\...SNIP> Get-SmbOpenFile -FileId 1065151889617 | Select-Object -Property *
SmbInstance : Default
ClientComputerName : ...SNIP
ClientUserName : ...SNIP
ClusterNodeName :
ContinuouslyAvailable : False
Encrypted : False
FileId : 1065151889617
Locks : 0
Path : C:\temp
Permissions : 1048705
ScopeName : *
SessionId : 1065151889409
ShareRelativePath : temp
Signed : True
PSComputerName :
CimClass : ROOT/Microsoft/Windows/SMB:MSFT_SmbOpenFile
CimInstanceProperties : {ClientComputerName, ClientUserName, ClusterNodeName, ContinuouslyAvailable...}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
Should I be focused only on the case where Locks -gt 0?
It looks like we may have narrowed down the root cause due to the Get-SmbOpenFile -FileId $fileId failing. This is probably related to the multiple 4-apart concurrent file listings, such that when, in the last example above, 1065151889485 is closed, it "closes" 1065151889489 as well, and then when we try to iterate on the loop for this value, it can't find it, and thus errors out.
PS Z:\git\devops_powershell> Get-SMBOpenFile
FileId SessionId Path ShareRelativePath ClientComputerName ClientUserName
------ --------- ---- ----------------- ------------------ --------------
1065151889485 1065151889409 C:\ ...SNIP ...SNIP
1065151889489 1065151889409 C:\ ...SNIP ...SNIP
1065151889613 1065151889409 C:\temp temp ...SNIP ...SNIP
1065151889617 1065151889409 C:\temp temp ...SNIP ...SNIP
1065151889833 1065151889409 C:\temp temp ...SNIP ...SNIP
I'm going to change that Get-SmbOpenFile -FileId $fileId line in the morning and test with the "error bypass" nonsense and see what happens there too. Or just take that check out and try again.
I'm still very very confused how the try-catch doesn't actively catch the error as thrown. If it did I would just have a Write-Warning instead of the end-process I have now.

powershell script - timegenerated in security log

i need some help with this code, as i'm a super-beginner with powershell but trying to get a report to my manager who is looking to see failed external attempts to remote into our system.
trying to pull out 4625 events from the security log and get the following fields into a csv file: Username (if it's an internal user), date of event, origin IP. I have this code so far based on what i could find (a.k.a. leech) online and customized a bit. everything is correct at this point except for the date (timegenerated). and i believe it's because of the replacementstring number listed. it's pulling the SubjectUserSid from the log. i'm not quite sure i understand how to find that replacementstring number, so maybe if someone can explain that to me, that would help.
thanks
$Date = [DateTime]::Now.AddDays(-1)
$Server = "SERVER"
$logName = '{0}{1}_security4625_log.csv' -f "C:\temp\",
$Date.tostring("MM-dd-yyyy_HH,mm,ss")
Get-EventLog -LogName 'Security' -Computer $Server `
-InstanceId 4625 `
-After $Date |
Select-Object #{
Name='TargetUserName'
Expression={$_.ReplacementStrings[5]}
},
#{
Name='WorkstationName'
Expression={$_.ReplacementStrings[1] -replace '\$$'}
},
#{
Name='IpAddress'
Expression={$_.ReplacementStrings[-2]}
},
#{
Name='TimeGenerated'
Expression={$_.ReplacementStrings[0]}
} |
Export-Csv -Path $logName -NoTypeInformation
Change the #{Name='TimeGenerated';Expression={$_.ReplacementStrings[0]} to simply TimeGenerated and you should be all set.
The ReplacementStrings are the variables from the Message field. Such as, the following log entry:
EventID : 4656
MachineName : AmazingLaptop.ChinchillaFarm.com
Data : {}
Index : 23277285
Category : (12804)
CategoryNumber : 12804
EntryType : FailureAudit
Message : A handle to an object was requested.
Subject:
Security ID: S-1-5-21-2127521184-6397854128-1234567890-12345678
Account Name: TMTech
Account Domain: ChinchillaFarm
Logon ID: 0xb8f705b
Object:
Object Server: SC Manager
Object Type: SERVICE OBJECT
Object Name: Schedule
Handle ID: 0x0
Resource Attributes: -
Process Information:
Process ID: 0x2b4
Process Name: C:\Windows\System32\services.exe
Access Request Information:
Transaction ID: {00000000-0000-0000-0000-000000000000}
Accesses: %%7186
%%7188
Access Reasons: -
Access Mask: 0x14
Privileges Used for Access Check: -
Restricted SID Count: 0
Source : Microsoft-Windows-Security-Auditing
ReplacementStrings : {S-1-5-21-2127521184-6397854128-1234567890-12345678, TMTech, ChinchillaFarm, 0xb8f705b...}
InstanceId : 4656
TimeGenerated : 11/20/2015 11:06:39 AM
TimeWritten : 11/20/2015 11:06:39 AM
UserName :
Site :
Container :
The ReplacementStrings are the values for all the fields like 'Security ID', 'Account Name', and 'Account Domain' within the Message property. Instead using one of those for the date/time you can just use the TimeGenerated property and it'll work just as well for your CSV.
Updated script:
$Date = [DateTime]::Now.AddDays(-1)
$Server = "SERVER"
$logName = '{0}{1}_security4625_log.csv' -f "C:\temp\",
$Date.tostring("MM-dd-yyyy_HH,mm,ss")
Get-EventLog -LogName 'Security' -Computer $Server `
-InstanceId 4625 `
-After $Date |
Select-Object #{
Name='TargetUserName'
Expression={$_.ReplacementStrings[5]}
},
#{
Name='WorkstationName'
Expression={$_.ReplacementStrings[1] -replace '\$$'}
},
#{
Name='IpAddress'
Expression={$_.ReplacementStrings[-2]}
},
TimeGenerated |
Export-Csv -Path $logName -NoTypeInformation

how to extract the text from a Microsoft.IIs.PowerShell.Framework.ConfigurationElement object

If I run the command in powershell:
C:\Get-Website
it outputs
Name ID State Physical Path Bindings
---- -- ----- ------------- --------
Default Web Site 1 %SystemDrive%\inetpub\wwwroot http *:80:
net.tcp 808:*
net.pipe *
net.msmq localhost
msmq.formatname
localhost
But if I try to select just the Bindings:
C:\Get-Website | where {$_.Name -eq "Default Web Site"} | select Bindings
It returns:
bindings : Microsoft.IIs.PowerShell.Framework.ConfigurationElement
How do I extract the contents of this object into a useful format?
The bindings property is a collection so you have to use the ExpandProperty parameter:
Get-Website -Name "Default Web Site" | select -ExpandProperty Bindings
To drill down further:
get-website -name "Default Web Site" | select -ExpandProperty Bindings | Select -ExpandProperty Collection
Recently I was working on similar command but for list all Sites and its bindings. In IIS this is what i did :
get-childItem |
select * , #{Name="SiteBindings"; Expression = {($_.Bindings.Collection | %{$_.protocol + " " + $_.BindingInformation} | Out-String).replace("`r","" ) }}
Note the replace("`r","" ). It is needed if you need to export to CSV.
There's also the Get-WebBinding cmdlet that can be used if you don't want to start from Get-Website.
Import-Module WebAdministration
Get-WebBinding
This will display all of the binding info for all websites, and you can filter it down further from there.
Here's sample output of running the above command.
protocol : http
bindingInformation : *:80:
sslFlags : 0
isDsMapperEnabled : False
certificateHash :
certificateStoreName :
ItemXPath : /system.applicationHost/sites/site[#name='Default Web Site' and #id='1']
RunspaceId : b7052f71-a213-437c-a97f-00fb9fa84a7f
Attributes : {Microsoft.IIs.PowerShell.Framework.ConfigurationAttribute,
Microsoft.IIs.PowerShell.Framework.ConfigurationAttribute,
Microsoft.IIs.PowerShell.Framework.ConfigurationAttribute,
Microsoft.IIs.PowerShell.Framework.ConfigurationAttribute…}
ChildElements : {}
ElementTagName : binding
Methods : {Microsoft.IIs.PowerShell.Framework.ConfigurationMethod,
Microsoft.IIs.PowerShell.Framework.ConfigurationMethod,
Microsoft.IIs.PowerShell.Framework.ConfigurationMethod,
Microsoft.IIs.PowerShell.Framework.ConfigurationMethod…}
Schema : Microsoft.IIs.PowerShell.Framework.ConfigurationElementSchema

Getting values from get-eventlog Powershell call

Sorry to ask such a question, but I've spent 1/2 hour on this and no good solution.
I want to get the latest date from the Event Log for a particular app. So far, my code is:
$event = get-eventlog -logname 'Windows PowerShell' -source mpkLogParser -newest 1 | Format-List
echo $event
this yields:
Index : 51
EntryType : Information
InstanceId : 3001
Message : MPKLogParser successfully parsed the log file u_ex100118.log
Category : (1)
CategoryNumber : 1
ReplacementStrings : {MPKLogParser successfully parsed the log file u_ex100118.log}
Source : mpkLogParser
TimeGenerated : 1/28/2010 11:24:08 AM
TimeWritten : 1/28/2010 11:24:08 AM
UserName :
So how do I extract the TimeWritten part from $event?
Any help with this and I can sleep better. :)
Don't use Format-List unless you are displaying to the host. That is, don't use Format-List when assigning to a variable. Try this:
$name = 'Windows PowerShell'
$event = get-eventlog -logname $name -source mpkLogParser -newest 1
$event.TimeWritten