How Does Member Enumeration Work in PowerShell 3? - powershell

In PoweShell 2 we did:
Get-ChildItem | ForEach-Object {$_.LastWriteTime} | Sort-Object
In Powershell 3 we do:
(Get-ChildItem).LastWriteTime | Sort-Object
But how does it work, i read this blog post on MSDN and they say that its faster because the foreach loop isnt running? So how does it enumerate the properties then ?

PowerShell is doing the hard work for us and it loops over the collection internally. I like to call this "implicit foreach". Assuming the member you specified is present on each object, if the member you specified is a property, you get back its value. If it's a method, it invokes the method on the each object.
In v2, to get all process names you had to take care of looping yourself:
Get-Process | Foreach-Object {$_.Name}
In v3, the equivalent would be:
(Get-Process).Name
Same applies to methods. To kill all processes with name starting with note*:
(Get-Process note*).Kill()

The blog says foreach-object cmdlet is not running. Now it is taken care of by the language engine and not a cmdlet, making it faster. How it EXACTLY works is internal implementation detail and I think that is not what you really want to know.

Related

Get serialnumber from asset list

Started in recent weeks in a Junior infrastructure role, and begun playing around with powershell to help save some time here and there.
I am trying to do the following:
1- I'm port a CSV file with a single column names asset
2- Perform a "ForEach" check on each line to find the device's serial number
3- Output results to a CSV with two column "asset" and "serialnumber"
I have dabbled in a few areas, and am currently sitting at something like this:
$file1 = Import-Csv -path "c:\temp\assets.csv" | ForEach-Object {
$asset = $_.asset
}
wmic /node:$asset bios get serialnumber
Export-Csv -Path "c:\temp\assetandserial.csv" -NoTypeInformation
As you may or may not see, I tried to set the column labelled "asset" as the variable, however, not sure if I placed it correctly.
I have tried a few other things, but honestly it's all new to me, so I haven't the foggiest idea where to go from here.
wmic is deprecated, and, for rich type support (OO processing), using PowerShell-native cmdlets is preferable in general.
wmic's immediate PowerShell counterpart is Get-WmiObject, which, however, is equally deprecated, in favor of Get-CimInstance.
Important: The command below uses Get-CimInstance, but note that the CIM cmdlets use a different remoting protocol than the obsolete WMI cmdlets. In short: To use the CIM cmdlets with remote computers, those computers must be set up in the same way that PowerShell remoting requires - see this answer for details.
Get-CimInstance Win32_BIOS -ComputerName (Import-Csv c:\temp\assets.csv).asset |
Select-Object #{ n='Asset'; e='PSComputerName' }, SerialNumber |
Sort-Object Asset |
Export-Csv c:\temp\assetandserial.csv -NoTypeInformation
Note the use of member-access enumeration to extract all .asset values directly from the collection of objects returned from Import-Csv.
All computer (asset) names are passed at once to Get-CimInstance, which queries them in parallel. Since the ordering of the responses from the targeted remote machines isn't guaranteed, Sort-Object is used to sort the results.
A calculated property is used with Select-Object to rename the automatically added .PSComputerName property to Asset.

Equivalent of `ls -t | head`

Intro
On Linux, I'll often use something like this to see the recently changed files in a directory with many files:
ls -t | head
I can do the following in PowerShell which is similar:
Get-ChildItem | Sort-Object -Property LastWriteTime | Select-Object -Last 15
That's a bit long so I then have the following in $PROFILE:
function Recent ()
{
Get-ChildItem | Sort-Object -Property LastWriteTime | Select-Object -Last 15
}
And maybe also:
Set-Alias lst Recent
or
Set-Alias ls-t Recent
as a shorter variant.
Question
Is there a built-in way to list the recently changed files that's more concise than the approach I've shown above?
Is there some other best practice that y'all would recommend?
As already presented in the comments,
You can go from :
Get-ChildItem | Sort-Object -Property LastWriteTime | Select-Object -Last 15
to
gci | Sort-Object LastWriteTime | Select -l 15
What is at play ?
gci is an alias for Get-ChildItem. To view all aliases available, you can type Get-Alias in your current session.
Sort-Object LastWriteTime make use of positional arguments. When an unnamed argument is given to a Powershell cmdlet, it is mapped to the first positional parameter.
Select -l 15 -l stand for -last. This work because when getting a parameter that does not exist, Powershell will attempt to map it to the closest matching parameter. In all the parameter available with the Select-Object cmdlet, only -last can be matched (no other parameter for that cmdlet start with the letter L. Note that in this case, l
is not defined as an alias for last. It is Powershell parameter disambiguation.
Best practices
What you do in your session stay in your session.
You can use aliases, parameter disambiguation as much as you please.
That being said, when developing a script or a module, you should avoid using aliases, disambiguated parameters and positional parameter altogether.
Some kind of problems that might occurs.
Parameter disambiguation might fail if the cmdlet introduce another parameter that could also be a match. For instance Get-Service -inputObject something work well. Get-Service -in "test" will fail as it is ambiguous. -in can match -inputObject but also -include. And while Get-Service -inp "test" would work, it is not very readable compared to simply using the full parameter name.
Aliases might not be available cross-platform. For instance, while sort work as an alias for sort-object in Windows, it does not in Linux (as it is a native command there). This kind of differentiation might produce unexpected results and break your script depending on context. Also, some aliases might be dropped in the future and they do make the script less readable)
Finally, positional parameters should also be avoided in scripts & modules.
Using named parameter will make your scripts more clear and readable for everyone.
To summarize, while working in a session, you can use aliases, parameter disambiguation and positional parameter as you please but when working on scripts or modules, they should be avoided.
References
Select-Object
Select-Object
[-InputObject ]
[[-Property] <Object[]>]
[-ExcludeProperty <String[]>]
[-ExpandProperty ]
[-Unique]
[-Last ]
[-First ]
[-Skip ]
[-Wait]
[]
Types of Cmdlet Parameters
A positional parameter requires only that you type the arguments in
relative order. The system then maps the first unnamed argument to the
first positional parameter. The system maps the second unnamed
argument to the second unnamed parameter, and so on. By default, all
cmdlet parameters are named parameters.
Powershell Parameter Disambiguation and a surprise
For instance, instead of saying Get-ChildItem -Recurse, you can say
Get-ChildItem -R. Get-ChildItem only has one (non-dynamic) parameter
that started with the letter ‘R’.. Since only one parameter matches,
PowerShell figures you must mean that one. As a side note, dynamic
parameters like -ReadOnly are created at run-time and are treated a
bit differently.
I would do:
ls | sort lastw*
or
ls | sort lastw <#press tab#>
The most recent ones appear at the bottom anyway.

Multiple Select-Object as dot-notation

Problem
I want to know if there is a easy way to search multiple objects in a WMI object or CIM instance.
I'm aware it's possible with commands like
Get-CimInstance Win32_BaseBoard | Select-Object Manufacturer,Product
But I want a command with a dot notation where you can set multiple objects for a search like (Get-CimInstance Win32_BaseBoard).Manufacturer with more than one object.
Something like (Get-CimInstance Win32_BaseBoard).Object1.Obejct2.Object3
Ben's solution from the comments will work but note that it calls Get-CimInstance once for each property you want, even though that's unnecessary (could take a while depending on the call you're making).
Let's look at it a few other ways. We'll start by storing the wanted property names in an array.
$properties = 'Manufacturer', 'Product'
Now we can do something similar to what Ben did:
$allValues = $properties |
ForEach-Object -Begin {
$bb = Get-CimInstance Win32_Baseboard
} -Process {
$bb.$_
}
That keeps his approach but does the CIM call once.
If you want to do with dot notation purely, you can use the .ForEach() method and the .PSObject hidden property to get at the properties:
(Get-CimInstance Win32Baseboard).ForEach({$_.PSObject.Properties.Where({$_.Name -in $properties}).Value})
As noted, DotNotation (Intellisense) is 1:1 / single node / collection thing. You can validate this, by pushing the result of the call to XML and walking the nodes.
(Get-CimInstance Win32_BaseBoard | ConvertTo-Xml).Objects.Object.Property
(Get-CimInstance Win32_BaseBoard | ConvertTo-Xml).Objects.Object.Property.name
(Get-CimInstance Win32_BaseBoard | ConvertTo-Xml).Objects.Object.Property.'#text'
The only other option off the top of my head is constructing a proxy that uses enums and switches for all possible properties for the namespace you are using.
That's way more unneeded effort and code to just do what BenH has pointed out, specifically because you'd have to do that for every class.
Now, if you just wanted to shorthand this, maybe do this
$Base = Get-CimInstance Win32_BaseBoard
$Base.Manufacturer;$base.Model;$base.Name;$Base.PartNumber
But that is just unwieldy, especially, since all this really doing is single commands set on a single line with the command break separator, the semi-colon. Which is a wrong thing to do. IMHO.
---small rant ---
If you need the separator, then just put the next thing on a new line and avoid the semi-colon. I mean, I can see that semi-colon use as the PoSH console host, but in a real script, function, module, well, just, no. Again, IMHO
--- small rant ---
Lastly, depending on what your target PoSH version is, DotNotation had issues in v2 - v3 days

Powershell 5.0 / ISE

I have an example code snippet that suggests using
(Get-Process | Where-Object {$_.WorkingSet64 -gt 20mb}).Count
to return the count of all processess using > 20Mb.
It works, but when typing, neither Intellisense or the "Tab" key shows this property, rather they show the properties of an individual process - which I find misleading.
I understand, that specifying an item property will give me the list of that property only, but is there a way to easily see, in general, what ALL the valid propeties are, including list aggregates etc?
Even assigning to a variable
$processes = Get-Process | Where-Object {$_.WorkingSet64 -gt 20mb}
does not show me "Count" as a valid property of $processes until AFTER the assignment has been actually run and the value assigned - when writing the script it still shows the properties for an individual item.
For me, Intellisense / Tab help that does not cover all the options kind of defeats the purpose ... (not having to remember hundreds objects/functions and their properties / parameters).
Is there any way to improve this situation? Some syntax trick have I missed?
The correct way to find out all of the properties of an object is to pipe the output to Get-Member:
Get-Process | Get-Member
Sometimes there are hidden properties and methods that can only be seen if you add the -force switch:
Get-Process | Get-Member -Force
The count property is an automatic property that is always usable on any collection object but that isn't explicitly listed as a property. Another example of an automatic property is length.
Using #() to force an array type is handy when that is what is wanted.
e.g. $processes = #(Get-Process | Where-Object {$_.WorkingSet64 -gt 20mb}). will show you "Count" and the other array properties.
Other than that, let's say the Intellisense has various limitations / shortcomings that I will just have to learn... sigh.

Differences between | and $

Can anyone explain to me the differences I'm seeing in either using a | to pipe one command to another or using $ to 'pipe' it a different way (sorry not sure if the use $ is actually considering piping).
So… this works:
Get-Mailbox -ResultSize Unlimited |
where { $_.RecipientTypeDetails.tostring() -eq "SharedMailbox" } |
Get-MailboxPermission
Which is great, however because I want to place another where command after the Get-MailboxPermission which doesn't work above I then tried to use this:
$Mailbox = Get-Mailbox -ResultSize Unlimited |
where { $_.RecipientTypeDetails.tostring() -eq "SharedMailbox" }
Get-MailboxStatistics -Identity $Mailbox |
where { $_.IsInherited.tostring() -eq "False" }
It causes me to get this error:
Cannot process argument transformation on parameter 'Identity'. Cannot convert the "System.Collections.ArrayList" value of type "System.Collections.ArrayList" to type "Microsoft.Exchange.Configuration.Tasks.GeneralMailboxOrMailUserIdParameter".
Surely using | or $ is the same in the sense that it pipes through the results to the next command or am I completely wrong?
I don't have an exchange shell here to test but I guess I can still explain the basics and point you in the right direction.
The pipe | is used to redirect output from one command to another command. $ in Powershell is the character which defines that the character sequence right behind it is either a variable (e.g. $Mailbox as an example for a normal variable or $_ as an example for a variable that holds data that has been piped through from a previous command) or an expression. An example for an expression one is $(4+5).
Or in a more frequently used example:
PS C:\Users\Administrator> $file = (get-childitem)[0]
PS C:\Users\Administrator> write-output "The fullname of $file is $($file.fullname)"
The fullname of .ssh is C:\Users\Administrator\.ssh
In that example it is actually necessary to use an expression, because variable detection inside a string doesn't recognize dots as separator between variable and a variable member (fullname is a member of $file).
If it's not clear to you why there is a point and what members are, you should probably look into object oriented programming a bit because Powershell is object oriented through and through.
In your 2nd example you just save everything that's returned by your Get-Mailbox command in the $Mailbox variable. The $Mailbox variable is available as long as you don't delete it or leave its scope (in this case, the powershell session). You can actually use the variable as input for multiple commands without losing its data.
When using the pipe, the data returned by your first command is only accessible for the command behind the pipe and after that it's gone.
That's probably the difference you're interested in.
As for your actual problem: Powershell tells you that it's not expecting to be handed a variable of type System.Collections.ArrayList, which is what Get-Mailbox returns. The technet help is unclear as to what Get-Mailbox specificly returns, but I strongly guess it's an ArrayList of Mailbox-Objects. You can check it like this:
$Mailbox.GetType()
$Mailbox[0].GetType() # gets the type of the first object in $Mailbox
To fix your code, you need to loop over what's been returned by Get-Mailbox. Try this:
$Mailboxes = Get-Mailbox -ResultSize Unlimited | where { $_.RecipientTypeDetails.tostring() -eq "SharedMailbox" }
$Mailboxes | ForEach-Object { Get-MailboxStatistics -Identity $_ }
The ForEach-Object cmdlet loops over an array or a list and works on each item individually.
Your first example works so far because Powershell has been made smarter about piped data a few versions ago (See paragraph about 'Member Enumeration'). It's actually ForEach-ing over the passed in data.
Follow up links:
The $_ variable in powershell
Powershell is an object oriented language
Sorry to have to say this, but you're completely wrong. Pipelines and variables are two entirely different things.
The pipe (|) connects the output of one cmdlet to the input of another cmdlet. List output is processed one item at a time, i.e. the second cmdlet receives each list item separately.
If you collect a list of items in a variable ($mailbox) and call a cmdlet with that variable you're passing the list object instead of individual list items. That only works if the cmdlet parameter accepts array input.
The pipe operator | i used to flow the output of one command into the input of another command.
The dollar symbolc, $ is used to denote that the name following it is a variable, and has nothing to do with piping data between cmdlets. The where cmdlet create a $_ variable for use within its expression.