Members of CimClass is different through pipeline - powershell

I would have expected to get the same "type" from both of the following commands. The second prepends the type name with "Selected."
>(Get-CimInstance CIM_LogicalDisk).CimClass | gm
TypeName: Microsoft.Management.Infrastructure.CimClass
Name MemberType Definition
---- ---------- ----------
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
CimClassMethods Property Microsoft.Management.Infrastructure.Generic.CimReadOnlyKeyedCollection[Microsoft.M
CimClassProperties Property Microsoft.Management.Infrastructure.Generic.CimReadOnlyKeyedCollection[Microsoft.M
CimClassQualifiers Property Microsoft.Management.Infrastructure.Generic.CimReadOnlyKeyedCollection[Microsoft.M
CimSuperClass Property cimclass CimSuperClass {get;}
CimSuperClassName Property string CimSuperClassName {get;}
CimSystemProperties Property Microsoft.Management.Infrastructure.CimSystemProperties CimSystemProperties {get;}
CimClassName ScriptProperty System.String CimClassName {get=[OutputType([string])]...
The second reveals a different type.
>Get-CimInstance CIM_LogicalDisk | Select-Object -Property CimClass | gm
TypeName: Selected.Microsoft.Management.Infrastructure.CimInstance
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
CimClass NoteProperty cimclass CimClass=root/cimv2:Win32_MappedLogicalDisk
>$PSVersionTable.PSVersion.ToString()
5.1.14409.1018

Using Select-Object with the -Property parameter outputs an object with the selected properties.
To get a "bare" property value, use the -ExpandProperty parameter instead.
Get-CimInstance CIM_LogicalDisk | Select-Object -ExpandProperty CimClass | gm

Related

How to Export Clustered Scheduled Task

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')

How to display the count of running processes through powershell script

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

Sort-Object produces different objects when using -Descending

Why does Sort-Object produce different objects when -Descending is used? The NoteProperty members are not the same.
Also, when writing to the console, the Name property does not appear unless -Descending is used. Why is that?
C:>Get-Type | Select-Object -Property BaseType,Name | gm
TypeName: Selected.System.RuntimeType
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
BaseType NoteProperty RuntimeType BaseType=System.Object
Name NoteProperty string Name=Registry
C:>Get-Type | Select-Object -Property BaseType,Name | Sort-Object -Property BaseType,Name | gm
TypeName: Selected.System.RuntimeType
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
BaseType NoteProperty object BaseType=null
Name NoteProperty string Name=_Activator
C:>Get-Type | Select-Object -Property BaseType,Name | Sort-Object -Property BaseType,Name -Descending | gm
TypeName: Selected.System.RuntimeType
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
BaseType NoteProperty RuntimeType BaseType=System.Xml.Xsl.XsltException
Name NoteProperty string Name=XsltCompileException
My apologies for not including information about Get-Type. https://gallery.technet.microsoft.com/scriptcenter/Get-Type-Get-exported-fee19cf7
This is not a cmdlet that is natively part of PoSH. It's either something the OP wrote or got from another source. If from another source than the OP should reach out to that author to ask what is to be expected.
If you do this same things using a built-in cmdlet, say Get-Date, we see all members are the same.
Get-Date |
Select-Object -Property BaseType,Name |
Sort-Object -Property BaseType, Name |
Get-Member
TypeName: Selected.System.DateTime
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
BaseType NoteProperty object BaseType=null
Name NoteProperty object Name=null
Get-Date | Select-Object -Property BaseType,Name |
Sort-Object -Property BaseType, Name -Descending |
Get-Member
TypeName: Selected.System.DateTime
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
BaseType NoteProperty object BaseType=null
Name NoteProperty object Name=null
So, would seem to point specifically to the implementation of this cmdlet the OP is looking for clarity on.
It is possible that your GetType invocation results in an array starting with $null as it has a try-catch block providing an error value of $null. Then, should any parameters be passed to the Get-Type, that null would be filtered out, but you pass none, so null is still present in the output. Then, as the result is piped to Select-Object, only the first object in the pipe is parsed to check if all the columns are present to display, and should the null be the first object, it has no properties thus nothing gets displayed.
To fix, add the | Where-Object {$_ -ne $null} into the Get-Type.ps1 script right before | Where-Object -FilterScript $WhereBlock in the last significant line. This will filter out any nulls produced by previous try-catch block, and you will only get an array of objects that have values.

Store just the value of an object in a variable

I want to store just the value of a PowerShell object in a variable.
Example
If we run:
$time = Get-Process System | select TotalProcessorTime
$time
This is the current output:
TotalProcessorTime
------------------
00:03:22.8281250
This is the output I would like:
00:03:22.8281250
Discussion
How do we store just the value? If we run $time | Get-Member, we see that PowerShell has stored a Selected.System.Diagnostics.Process that has the following properties:
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
TotalProcessorTime NoteProperty System.TimeSpan TotalProcessorTime=00:03:22.8281250
I have tried getting the value by running both $time.TotalProcessorTime and $time.ToString() without success.
The Object which produces that string "00:03:22.8281250":
(Get-Process System).TotalProcessorTime
The string itself:
(Get-Process System).TotalProcessorTime.ToString()

powershell missing member methods in array

I have (yet another) powershell query. I have an array in powershell which i need to use the remove() and split commands on.
Normally you set an array (or variable) and the above methods exist. On the below $csv2 array both methods are missing, i have checked using the get-member cmd.
How can i go about using remove to get rid of lines with nan. Also how do i split the columns into two different variables. at the moment each element of the array displays one line, for each line i need to convert it into two variables, one for each column.
timestamp Utilization
--------- -----------
1276505880 2.0763250000e+00
1276505890 1.7487730000e+00
1276505900 1.6906890000e+00
1276505910 1.7972880000e+00
1276505920 1.8141900000e+00
1276505930 nan
1276505940 nan
1276505950 0.0000000000e+00
$SystemStats = (Get-F5.iControl).SystemStatistics
$report = "c:\snmp\data" + $gObj + ".csv"
### Allocate a new Query Object and add the inputs needed
$Query = New-Object -TypeName iControl.SystemStatisticsPerformanceStatisticQuery
$Query.object_name = $i
$Query.start_time = $startTime
$Query.end_time = 0
$Query.interval = $interval
$Query.maximum_rows = 0
### Make method call passing in an array of size one with the specified query
$ReportData = $SystemStats.get_performance_graph_csv_statistics( (,$Query) )
### Allocate a new encoder and turn the byte array into a string
$ASCII = New-Object -TypeName System.Text.ASCIIEncoding
$csvdata = $ASCII.GetString($ReportData[0].statistic_data)
$csv2 = convertFrom-CSV $csvdata
$csv2
There is no Remove or Split method on .NET's Array type, or added by the PowerShell wrapper around an Array instance. This is quite easy to show:
PS[64bit] E:\> $a = 1,2,3,4,5
PS[64bit] E:\> $a.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS[64bit] E:\> Get-Member -InputObject $a
TypeName: System.Object[]
Name MemberType Definition
---- ---------- ----------
Count AliasProperty Count = Length
Address Method System.Object&, mscorlib, Version=2.0.0.0, Culture=neutral, PublicK...
Clone Method System.Object Clone()
CopyTo Method System.Void CopyTo(array array, int index), System.Void CopyTo(arra...
Equals Method bool Equals(System.Object obj)
Get Method System.Object Get(int )
GetEnumerator Method System.Collections.IEnumerator GetEnumerator()
GetHashCode Method int GetHashCode()
GetLength Method int GetLength(int dimension)
GetLongLength Method long GetLongLength(int dimension)
GetLowerBound Method int GetLowerBound(int dimension)
GetType Method type GetType()
GetUpperBound Method int GetUpperBound(int dimension)
GetValue Method System.Object GetValue(Params int[] indices), System.Object GetValu...
Initialize Method System.Void Initialize()
Set Method System.Void Set(int , System.Object )
SetValue Method System.Void SetValue(System.Object value, int index), System.Void S...
ToString Method string ToString()
IsFixedSize Property System.Boolean IsFixedSize {get;}
IsReadOnly Property System.Boolean IsReadOnly {get;}
IsSynchronized Property System.Boolean IsSynchronized {get;}
Length Property System.Int32 Length {get;}
LongLength Property System.Int64 LongLength {get;}
Rank Property System.Int32 Rank {get;}
Arrays in .NET, and PowerShell, are fixed size. To remove an element you need to copy all but the element to be removed, in PSH this can be done with Where-Object:
$newArray = $oldArray | Where-Object {some-condition-on-$_}
Similarly Select-Object with -First and -Skip parameters can be used to select elements before or after (resp3ectively) an index.
NB System.Array does implement System.Collections.ILst but the explicit implementation of IList.Remove just throws a NotImplementedException.