I need to look through eventLog security ID 4648, and find the last time the user connected to the machine.
Currently this is my code:
$Values = invoke-command -ComputerName $ComputerName {Get-EventLog -LogName Security -InstanceID 4648 | Select-Object -ExpandProperty Message| ForEach-Object {if($_.Log -match "$String2"){
$_
Break }}}
$Values
The aim was to go through each log until a log where the message has the previously defined username is found, and then stop going through EventLog and return that log.
This is working well, except its not matching the correct log with the specified string.
Is there a way to improve how the matching works? So it actually finds the correct log with the specified user?
# Fill in the regex for the userName
$userName = "userName"
$Values = #(invoke-command -ComputerName $ComputerName {
Get-EventLog -LogName Security -InstanceID 4648 | Where-Object { $_.message -match $Using:userName } | Select-Object -First 1)
}
Your above sample won't work since message is of type string, therefore it doesn't have a Log property. Since we want $userName to be avaiable for read access on the remote machine we can use the $Using: syntax. To break the pipeline "iteration" I'm using Select-Object -First 1 which will return the first object passing the Where-Objectclause.
Resulting from that $Values points to a collection of (deserialized) objects (using the #() operator) of type:
TypeName: System.Diagnostics.EventLogEntry#Security/Microsoft-Windows-Security-Auditing/4648
Which means you can change the -First parameter to e.g. 10 and sort the result on the client machine:
$Values | sort TimeGenerated -Descending
If you want to know which properties are available you can use:
> $Values | gm
TypeName: System.Diagnostics.EventLogEntry#Security/Microsoft-Windows-Security-Auditing/4648
Name MemberType Definition
---- ---------- ----------
Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs)
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Diagnostics.EventLogEntry otherEntry), bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetObjectData Method void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
ToString Method string ToString()
Category Property string Category {get;}
CategoryNumber Property int16 CategoryNumber {get;}
Container Property System.ComponentModel.IContainer Container {get;}
Data Property byte[] Data {get;}
EntryType Property System.Diagnostics.EventLogEntryType EntryType {get;}
Index Property int Index {get;}
InstanceId Property long InstanceId {get;}
MachineName Property string MachineName {get;}
Message Property string Message {get;}
ReplacementStrings Property string[] ReplacementStrings {get;}
Site Property System.ComponentModel.ISite Site {get;set;}
Source Property string Source {get;}
TimeGenerated Property datetime TimeGenerated {get;}
TimeWritten Property datetime TimeWritten {get;}
UserName Property string UserName {get;}
EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;}
Hope that helps.
Related
I try to export the XML of a Clustered Scheduled Task.
I search for the function as Export-ScheduledTask has for non Clustered Tasks.
Maybe there is a way via CIM when i execute a Get-ClusteredScheduledTask I get this.
But I have no idea how to query this
CimClass : Root/Microsoft/Windows/TaskScheduler:MSFT_ClusteredScheduledTask
CimInstanceProperties : {ClusterName, CurrentOwner, Resource, TaskDefinition...}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
Edit1:
Get-Member
$task | Get-Member
TypeName: Microsoft.Management.Infrastructure.CimInstance#Root/Microsoft/Windows/TaskScheduler/MSFT_ClusteredScheduledTask
Name MemberType Definition
---- ---------- ----------
Clone Method System.Object ICloneable.Clone()
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Object obj)
GetCimSessionComputerName Method string GetCimSessionComputerName()
GetCimSessionInstanceId Method guid GetCimSessionInstanceId()
GetHashCode Method int GetHashCode()
GetObjectData Method void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context...
GetType Method type GetType()
ToString Method string ToString()
ClusterName Property string ClusterName {get;}
CurrentOwner Property string CurrentOwner {get;}
PSComputerName Property string PSComputerName {get;}
Resource Property string Resource {get;}
TaskDefinition Property CimInstance#Instance TaskDefinition {get;set;}
TaskName Property string TaskName {get;}
TaskType ScriptProperty System.Object TaskType {get=[Microsoft.PowerShell.Cmdletization.GeneratedTypes.ScheduledTask.ClusterTaskTypeEnum]($this.PSBas...
Try This
$TaskName = "Change_NTFS_permissions"
Get-ChildItem -Path ($env:SystemRoot +
'\System32\Tasks\Microsoft\Windows\Failover Clustering')
-File -Recurse | ? {$_.Name -like $TaskName} | Get-Content |
Out-File -FilePath ('C:\scripts\XML_Shedules' + '\' + $TaskName + '.xml')
I guess I just don't know the proper name of whatever I'm looking for, but this was probably asked a thousand times before.
I started PowerShell not long ago, and I'm struggling to understand where I can find the 'sub properties'(if you can call it those) of an object.
For instance, I was using the VMware PowerCLI, and was tried to figure out how I can find the IP address of a VM.
So for example, I was using the Get-VM command, and when I piped it into get member, I got the following:
PS C:\Users\eitan.rapaport> get-vm "*VRA*" | gm
TypeName: VMware.VimAutomation.ViCore.Impl.V1.VM.UniversalVirtualMachineImpl
Name MemberType Definition
---- ---------- ----------
ConvertToVersion Method T VersionedObjectInterop.ConvertToVersion[T]()
Equals Method bool Equals(System.Object obj)
GetClient Method VMware.VimAutomation.ViCore.Interop.V1.VIAutomation VIObjectCoreInterop.GetClient()
GetConnectionParameters Method VMware.VimAutomation.ViCore.Interop.V1.VM.RemoteConsoleVMParams RemoteConsoleVMIn..
GetHashCode Method int GetHashCode()
GetType Method type GetType()
IsConvertableTo Method bool VersionedObjectInterop.IsConvertableTo(type type)
LockUpdates Method void ExtensionData.LockUpdates()
ObtainExportLease Method VMware.Vim.ManagedObjectReference ObtainExportLease.ObtainExportLease()
ToString Method string ToString()
UnlockUpdates Method void ExtensionData.UnlockUpdates()
CoresPerSocket Property int CoresPerSocket {get;}
CustomFields Property System.Collections.Generic.IDictionary[string,string] CustomFields {get;}
DatastoreIdList Property string[] DatastoreIdList {get;}
DrsAutomationLevel Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.Cluster.DrsAutomationLevel] ..
ExtensionData Property System.Object ExtensionData {get;}
Folder Property VMware.VimAutomation.ViCore.Types.V1.Inventory.Folder Folder {get;}
FolderId Property string FolderId {get;}
Guest Property VMware.VimAutomation.ViCore.Types.V1.VM.Guest.VMGuest Guest {get;}
GuestId Property string GuestId {get;}
HAIsolationResponse Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.Cluster.HAIsolationResponse]..
HardwareVersion Property string HardwareVersion {get;}
HARestartPriority Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.Cluster.HARestartPriority] H..
Id Property string Id {get;}
MemoryGB Property decimal MemoryGB {get;}
MemoryMB Property decimal MemoryMB {get;}
Name Property string Name {get;}
Notes Property string Notes {get;}
NumCpu Property int NumCpu {get;}
PersistentId Property string PersistentId {get;}
PowerState Property VMware.VimAutomation.ViCore.Types.V1.Inventory.PowerState PowerState {get;}
ProvisionedSpaceGB Property decimal ProvisionedSpaceGB {get;}
ResourcePool Property VMware.VimAutomation.ViCore.Types.V1.Inventory.ResourcePool ResourcePool {get;}
ResourcePoolId Property string ResourcePoolId {get;}
Uid Property string Uid {get;}
UsedSpaceGB Property decimal UsedSpaceGB {get;}
VApp Property VMware.VimAutomation.ViCore.Types.V1.Inventory.VApp VApp {get;}
Version Property VMware.VimAutomation.ViCore.Types.V1.VM.VMVersion Version {get;}
VMHost Property VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost VMHost {get;}
VMHostId Property string VMHostId {get;}
VMResourceConfiguration Property VMware.VimAutomation.ViCore.Types.V1.VM.VMResourceConfiguration VMResourceConfigu..
VMSwapfilePolicy Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.VMSwapfilePolicy] VMSwapfile..
As you can see, nothing mentions anything about IP.
I was researching this online, and have found that I should run the following command:
Get-VM | Select Name, #{N="IP Address";E={#($_.guest.IPAddress[0])}}
Which leads me to my question. How can I find the properties under a certain member/property of a command? How could I research the 'sub properties' of 'guest' in that example?
Okay, found it.
In that instance it would be get-vm "*VRA*" | select -ExpandProperty guest | gm
I've been dealing with this for the last two days, so I figured I'd share my solution:
First, I'm saving the VM object to a variable to make it easy to access without searching every time.
$vm = Get-vm -Name steve
To get all the properties of the VM Object
$vm | Select-Object *
If you just want to get the Name you can access it like this:
$vm.Name
If you want to get the Properties of the Guest Object (which is a property of the VM object):
$vm.Guest | Select-Object *
You can access the Properties of the Guest Object through the VM Object like this:
$vm.Guest.VmName
Want the IP addresses of the guest?
$vmip = $vm.Guest.IPAddress
And, because this took me a while to figure out, if that returns ipv4 and ipv6, and you want to filter out the ipv6:
$vmip = $vm.Guest.IPAddress | ?{$_ -notmatch ':'}
Another method of introspection in PowerShell is to just get the class name and then look it up in the API.
PS C:\> $Files = Get-ChildItem *.* -File
PS C:\> $Files[0].GetType().FullName
System.IO.FileInfo
You can then search for that class with either C# or PowerShell to find the API listing.
You can do a similar thing with the VMWare PowerCLI doc. The "all types" list on the left is a list of all the classes used by the module.
Most likely there's something fundamental I don't understand about PowerShell. I really don't like when writing even medium sized pipes, where grabbing a property breaks the workflow by having to put parens around the statement up to that point, for eg.
(Get-ChildItem ~\.gitconfig).Length
This is tedious. Because Length looks very much like a property, one would think
Get-ChildItem ~\.gitconfig | Get-ItemPropertyValue -Name Length
would work. However, it does not. Taking a look at the interface of the System.IO.FileSystemInfo object returned by the File System PSDrive provider, one sees that it doesn't have a Length property. It does have a FullName property though, hence
Get-ChildItem ~\.gitconfig | Get-ItemPropertyValue -Name FullName
works as expected. To retrieve the size (Length) of a file using the pipe, one has to use Select-Object with the -ExpandProperty like
Get-ChildItem ~\.gitconfig | Select-Object -ExpandProperty Length
How does one know up front whether placing a . after an object and iterating through the results of tab completion, if the entry is an object or a property? It's very annoying that even common operations are confusing as hell, given for instance that reading environmental variables goes by
Get-Item -Path Env:\USERNAME
returns
Name Value
---- -----
USERNAME mnagy
If it's an item, Get-ItemProperty and Get-ItemPropertyValue must play a role here. Because of the Name:Value structure of the result, newcomers might be intrigued to obtain the actual value saying
Get-Item -Path Env:\USERNAME | Get-ItemPropertyValue
or actually reading how Get-ItemPropertyValue should be used modify the query to
Get-ItemPropertyValue -Path Env:\ -Name USERNAME
which in fact results in
Get-ItemPropertyValue : Cannot use interface. The IPropertyCmdletProvider interface is not supported by this provider.
At line:1 char:1
+ Get-ItemPropertyValue -Path Env:\ -Name USERNAME
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [Get-ItemPropertyValue], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported,Microsoft.PowerShell.Commands.GetItemPropertyValueCommand
This entire construction seems utterly inconsistent to me and most vexing, but hopefully not by design, but because I look at it from the wrong angle.
To your first note: Length, for .hg directoy, worked form me just fine (giving you the number of files within):
Ps C:\> (Get-ChildItem .hg).Length
18
I tend to use get-member to check what is supported and what is not.
If I check it for my directory reports:
(Get-ChildItem reports) | gm
TypeName: System.IO.FileInfo
Name MemberType Definition
---- ---------- ----------
LinkType CodeProperty System.String LinkType{get=GetLinkType;}
Mode CodeProperty System.String Mode{get=Mode;}
Target CodeProperty System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=...
AppendText Method System.IO.StreamWriter AppendText()
CopyTo Method System.IO.FileInfo CopyTo(string destFileName), System.IO.FileInfo CopyTo(s...
Create Method System.IO.FileStream Create()
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateText Method System.IO.StreamWriter CreateText()
Decrypt Method void Decrypt()
Delete Method void Delete()
Encrypt Method void Encrypt()
Equals Method bool Equals(System.Object obj)
GetAccessControl Method System.Security.AccessControl.FileSecurity GetAccessControl(), System.Secur...
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetObjectData Method void GetObjectData(System.Runtime.Serialization.SerializationInfo info, Sys...
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
MoveTo Method void MoveTo(string destFileName)
Open Method System.IO.FileStream Open(System.IO.FileMode mode), System.IO.FileStream Op...
OpenRead Method System.IO.FileStream OpenRead()
OpenText Method System.IO.StreamReader OpenText()
OpenWrite Method System.IO.FileStream OpenWrite()
Refresh Method void Refresh()
Replace Method System.IO.FileInfo Replace(string destinationFileName, string destinationBa...
SetAccessControl Method void SetAccessControl(System.Security.AccessControl.FileSecurity fileSecurity)
ToString Method string ToString()
PSChildName NoteProperty string PSChildName=jv_libgdbs_tests-20180822-Test.xml
PSDrive NoteProperty PSDriveInfo PSDrive=C
PSIsContainer NoteProperty bool PSIsContainer=False
PSParentPath NoteProperty string PSParentPath=Microsoft.PowerShell.Core\FileSystem::C:\prg_sdk\stx8-j...
PSPath NoteProperty string PSPath=Microsoft.PowerShell.Core\FileSystem::C:\prg_sdk\stx8-jv_swin...
PSProvider NoteProperty ProviderInfo PSProvider=Microsoft.PowerShell.Core\FileSystem
Attributes Property System.IO.FileAttributes Attributes {get;set;}
CreationTime Property datetime CreationTime {get;set;}
CreationTimeUtc Property datetime CreationTimeUtc {get;set;}
Directory Property System.IO.DirectoryInfo Directory {get;}
DirectoryName Property string DirectoryName {get;}
Exists Property bool Exists {get;}
Extension Property string Extension {get;}
FullName Property string FullName {get;}
IsReadOnly Property bool IsReadOnly {get;set;}
LastAccessTime Property datetime LastAccessTime {get;set;}
LastAccessTimeUtc Property datetime LastAccessTimeUtc {get;set;}
LastWriteTime Property datetime LastWriteTime {get;set;}
LastWriteTimeUtc Property datetime LastWriteTimeUtc {get;set;}
Length Property long Length {get;}
Name Property string Name {get;}
BaseName ScriptProperty System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Re...
VersionInfo ScriptProperty System.Object VersionInfo {get=[System.Diagnostics.FileVersionInfo]::GetVer...
How does one know up front whether placing a . after an object and
iterating through the results of tab completion, if the entry is an
object or a property?
You check it with with Get-Member.
For the Get-Item -Path Env:\USERNAME you can again check:
PS C:\> Get-Item -Path Env:\USERNAME | gm
TypeName: System.Collections.DictionaryEntry
Name MemberType Definition
---- ---------- ----------
Name AliasProperty Name = Key
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
PSDrive NoteProperty PSDriveInfo PSDrive=Env
PSIsContainer NoteProperty bool PSIsContainer=False
PSPath NoteProperty string PSPath=Microsoft.PowerShell.Core\Environment::USERNAME
PSProvider NoteProperty ProviderInfo PSProvider=Microsoft.PowerShell.Core\Environment
Key Property System.Object Key {get;set;}
Value Property System.Object Value {get;set;}
Now check the USERNAME (you see the key you are asking and its value):
PS C:\> (Get-Item -Path Env:\USERNAME).key
USERNAME
PS C:\> (Get-Item -Path Env:\USERNAME).value # my login
gurun
I'm new to this forum and I apologize if I may have left anything out.
I'm trying to combine two cmdlets(Get-cdmGroupProfile and get-adgroupmember) and get the results(Get-cdmGroupProfile(returns groups from an application called Centrify ) and Get-adgroupmember(which gets group members from the from the cmdlets exported to an excel spreadsheet.
From what I have read ,not all cmdlets can be accept piped input and that is where the need for calculated properties comes in.
I have done this a couple times before( included script at the very bottom of the posting) where I created a calculated property and
was able to get the exported results in an Excel spreadsheet.
However when I tried the code I used before ,it didn't give me the results I was looking for.
After doing some more research I tried to use the calculated properties as such below and then pass it to the select object.
The script just keeps running and doesn't appear to stop. I removed the result variable that I assigned the foreach loop to and removed it the result from being piped into the excel spreadsheet and noticed the results weren't exactly what I wanted.
I was hoping to maybe find a more efficient way of doing this.
I was able to get it exported to an excel spreadsheet ,but it just shows the results from the array which repeats the values ,but doesn't list them like I would like.
I would like the following script to output the following information below
Zonename AD Linux Group Centrify group
PROD ZONE Group1 Group A
PROD ZONE Group2 Group B
TEST ZONE GROUP5 GROUP D
$list = Import-Csv C:\Users\User1\Desktop\Centrify\Inputpega.csv
$result = foreach($item in $list) {
$adgroupmember = Get-ADGroupMember -Identity $item.Group
$centrifygprofile = Get-CdmGroupProfile -Zone $item.DistinguishedName
Get-CdmGroupProfile -Zone $item.DistinguishedName |%{
Get-ADGroupmember -identity $item.Group
$Properties = #(
#{Name='ZoneName';Expression={$centrifygprofile.Zone}},
#{Name=' Centrify Group';Expression={$centrifygprofile.name}},
#{Name='AD Linux GROUP' ;Expression={$adgroupmember.name}},
)
$result | Export-Csv C:\Users\User1\Desktop\Results\results4.csv -
NoTypeInformation
Results that I'm getting -
ZoneName : {OU=TEST ZONE ,OU=TEST Zone
One,OU=Zones,OU=TEST,DC=TEST,DC=com,OU=PROD ZONE,OU=PROD Zone
One,OU=Zones,OU=PROD,DC=PROD,DC=com,
OU=PROD ZONE,OU=PROD Zone
One,OU=Zones,OU=PROD,DC=PROD,DC=com,OU=Unix,DC=PRODk,DC=com, OU=PROD
ZONE,OU=PROD Zone One,OU=Zones,OU=PROD,DC=PROD,DC=com...}
Centrify Group : {group1#prod.com, group2#prod.com, group3#prod.com,
group4#prod.com...}
PROD_GROUPS,OU=Zones,OU=PROD,OU=PROD,OU=PROD,DC=PROD,DC=com
AD Linux Group : {group6, group7, group8, group9...
ZoneName : {OU=TEST ZONE ,OU=TEST Zone
One,OU=Zones,OU=TEST,DC=TEST,DC=com,OU=PROD ZONE,OU=PROD Zone
One,OU=Zones,OU=PROD,DC=PROD,DC=com,
OU=PROD ZONE,OU=PROD Zone
One,OU=Zones,OU=PROD,DC=PROD,DC=com,OU=Unix,DC=PRODk,DC=com, OU=PROD
ZONE,OU=PROD Zone One,OU=Zones,OU=PROD,DC=PROD,DC=com...}
Centrify Group : {group1#prod.com, group2#prod.com, group3#prod.com,
group4#prod.com...}
PROD_GROUPS,OU=Zones,OU=PROD,OU=PROD,OU=PROD,DC=PROD,DC=com
AD Linux Group : {group6, group7, group8, group9...
This is a script I have used multiple before where I was able to combine multiple commands and export the data I wanted to an excel spreadsheet by using calculated properties.
$list = Import-Csv C:\Users\user\Desktop\dn2.csv
$finalzpa = Foreach($item in $list){
$zonezpa = Get-CdmZpaSetting -Zone $item.DistinguishedName
$zoneset = Get-CdmZone -dn $item.DistinguishedName
Get-CdmZone -Dn $item.DistinguishedName | %{
Get-CdmZpaSetting -Zone $item.DistinguishedName |
Select-Object #{Name='Userenabled';Expression={$zonezpa.UserEnabled}},
#{Name='Provisioning Groups enabled';Expression=
{$zonezpa.GroupEnabled}},
#{Name='ZoneName' ;Expression={$zoneset.Name}},
#{Name='User Source';Expression={$zonezpa.UserSource}},
#{Name='Group Source';Expression={$zonezpa.GroupSource}},
#{Name='Distinguished Name';Expression=
{$item.DistinguishedName}}
}}
$finalzpa | Export-Csv -Append -NoTypeInformation
C:\Users\Desktop\zonesautoinfo.csv
$adgroupmember | gm
TypeName: Microsoft.ActiveDirectory.Management.ADPrincipal
Name MemberType Definition
---- ---------- ----------
Contains Method bool Contains(string propertyName)
Equals Method bool Equals(System.Object obj)
GetEnumerator Method System.Collections.IDictionaryEnumerator
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Item ParameterizedProperty
Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Item(string
propertyName) {get;}
distinguishedName Property System.String distinguishedName
{get;set;}
name Property System.String name {get;}
objectClass Property System.String objectClass {get;set;}
objectGUID Property System.Nullable`1[[System.Guid,
mscorlib, Version=4.0.0.0, Culture=neutral,
objectGUID {get;set;}
SamAccountName Property System.String SamAccountName
{get;set;}
SID Property
System.Security.Principal.SecurityIdentifier SID {get;set;}
$centrifygprofile | gm
TypeName: Centrify.DirectControl.PowerShell.Types.CdmGroupProfile
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
CanonicalName Property string CanonicalName {get;}
Computer Property
Centrify.DirectControl.PowerShell.Types.CdmManagedComputer Computer {get;}
Domain Property string Domain {get;}
Gid Property System.Nullable[long] Gid {get;}
Group Property
Centrify.DirectControl.PowerShell.Types.CdmGroup Group {get;}
IsHierarchical Property bool IsHierarchical {get;}
IsMembershipRequired Property System.Nullable[bool] IsMembershipRequired
{get;}
IsOrphan Property bool IsOrphan {get;}
IsSfu Property bool IsSfu {get;}
Name Property string Name {get;}
PreferredServer Property string PreferredServer {get;}
Zone Property
Centrify.DirectControl.PowerShell.Types.CdmZone Zone {get;}
Just trying to find out how do we get the count of running services through powershell script. I know Get-Service will give us list of all the processes on the system and (Get-Service). Count will give the count. But question is how do we find the count of only Running Services in the system? I simplified the filter criteria to get the list of only running services which is Get-Service | Where-Object {$_.Status -eq "Running"} BUT NO LUCK WITH THE COUNT OF THOSE SERVICES.
TL;DR
(Get-Service | Where-Object Status -eq "Running").Count
Have you heard of the Get-Member CmdLet?
If not; get reading up on it here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-member?view=powershell-6
Gets the properties and methods of objects.
I find this one of the most useful commands in situations similar to this. Get used to using it as it will come in very handy!
How does that help you? Well...
Get-Service | Get-Member
Returns:
TypeName: System.ServiceProcess.ServiceController
Name MemberType Definition
---- ---------- ----------
Name AliasProperty Name = ServiceName
RequiredServices AliasProperty RequiredServices = ServicesDependedOn
Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs)
Close Method void Close()
Continue Method void Continue()
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Object obj)
ExecuteCommand Method void ExecuteCommand(int command)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
Pause Method void Pause()
Refresh Method void Refresh()
Start Method void Start(), void Start(string[] args)
Stop Method void Stop()
WaitForStatus Method void WaitForStatus(System.ServiceProcess.ServiceControllerStatus desiredStat...
CanPauseAndContinue Property bool CanPauseAndContinue {get;}
CanShutdown Property bool CanShutdown {get;}
CanStop Property bool CanStop {get;}
Container Property System.ComponentModel.IContainer Container {get;}
DependentServices Property System.ServiceProcess.ServiceController[] DependentServices {get;}
DisplayName Property string DisplayName {get;set;}
MachineName Property string MachineName {get;set;}
ServiceHandle Property System.Runtime.InteropServices.SafeHandle ServiceHandle {get;}
ServiceName Property string ServiceName {get;set;}
ServicesDependedOn Property System.ServiceProcess.ServiceController[] ServicesDependedOn {get;}
ServiceType Property System.ServiceProcess.ServiceType ServiceType {get;}
Site Property System.ComponentModel.ISite Site {get;set;}
StartType Property System.ServiceProcess.ServiceStartMode StartType {get;}
Status Property System.ServiceProcess.ServiceControllerStatus Status {get;}
ToString ScriptMethod System.Object ToString();
Isn't that cool?!
Take a quick look at the properties available (Get-Service | Get-Member -MemberType Property) - spot anything useful?
(Get-Service | Where-Object Status -eq "Running").Count