How to call multiple properties in powershell - powershell

$loadbalancer = Get-AzureRmLoadBalancer | select Name,ResourceGroupName
$loadbalancer has two value ILB name and its resource group.
I want call both value in single PS command, Like when I call ILB name its respective resource group should be called.

The problem isn't entirely clear, can you please give an example of the function being used in the next step. I used "get-command" for the examples rather than get-azurermloadbalancer to avoid being package dependent.
To get the propety from $loadbalancer you use a dot and the name.
To get the current row from pipeline you can use $_
$loadbalancer = Get-Command get-* | Select-Object -Property CommandType,Name
#get a particular property
$loadbalancer.CommandType
#Use both properties in one function
$loadbalancer | Where-Object{($_.CommandType -eq "function") -and ($_.Name -match "Token")}

Related

Use a variable returned by Get-Variable

Hopefully this answer isn't above me. I've created a custom object with properties and methods. I create several of them on the fly, depending on what the user selects at the beginning.
So for this example, the script might create $PRD1, $PRD2, $TST1 and $TST4.
$PRD1, $PRD2, $TST1 and $TST4 will have some properties like DebugMode, DisableAppsStartTime, DisableAppsStopTime. They'll have some methods like DisableApps(), EnableApps().
How can I find out which variables the script ended up creating? I can use Get-Variable to know the ones it created (plus I DO still have the initial list of names to create). My issue is that I'm having trouble figuring out to call the ones I've created, in a manner that allows me to use the methods and properties, without a ridiculous mash up of nested foreach/if/switch commands.
I certainly hope that made sense.
Thanks in advance,
SS
I DO still have the initial list of names to create
Assuming that $list contains this list, the following creates an (ordered) hash table of those variables that were actually created from that list:
$variableMap = [ordered] #{}
(Get-Variable -ErrorAction Ignore -Scope Local $list).
ForEach({ $variableMap[$_.Name] = $_.Value })
Note: -Scope Local limits the lookup to the current scope[1]; omit it to target all variables visible in the current scope, which includes those from ancestral (parent) scopes.
You can then loop over $variableMap.Keys to process them all, or access one by name selectively, e.g., $variableMap.PRD1 (or $variableMap['PRD1']).
You then use regular dot notation to access properties and methods of these entries; e.g., $variableMap.PRD1.DisableApps().
[1] This includes variables created with the AllScope option, e.g., $HOME, because they are copied to every scope, as the name suggests. You can find all such variables with
Get-Variable | Where-Object Options -match 'AllScope'
I just did this with the where-object cmdlet and the -like operator with an foreach loop.
foreach($var in (get-variable | Where-object {$_.name -like '*PRD*' -or $_.name -like '*TST*'})){
$var
}

Using Where-Object with an object in PowerShell

I can't seem to get my brain around something and I am hoping someone can help
I have an array of objects called $SnapVMsAll that looks like this:
VMName Name SnapshotType CreationTime ParentSnapshotName
------ ---- ---------- ------------ ------------------
SHARED-server.host.com SHARED-server.host.com - (02/10/2017 - 13:02:44) Standard 02/10/2017 13:05:58
I need to display all the records in this array of objects that have string "Veeam" in the name column, but I think I am having problems isolating a specific attribute of the object to compare.
My attempts have been as follows:
echo $SnapVMsAll | Where-Object (Foreach-Object -MemberName name) -Like "Veeam Replica"
This returned the error:
Where-Object : Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
I have also tried
echo $SnapVMsAll | Where-Object $SnapVMsAll.name -Like "Veeam Replica"
But again I get the same error.
$SnapVMsAll does not exist inside the pipeline, it is the object you pass to the pipeline. Within a pipeline, objects can be accessed using the automatic variable $_.
Also note that -Like is usually used with wildcards to match a string. If the name is Veeam Replica you should use -eq, if the name contains Veeam Replica, you should change to -Like "*Veeam Replica*"
So changing your code to the following should work:
$SnapVMsAll | Where-Object { $_.name -Like "*Veeam Replica*" }

Using PowerShell how to I split the string of a selected property

I am very new to PowerShell and I can't seem to find a solution to the the question about splitting my selected properties value in powershell which works for me.
My current code without the split is:
((get-Acl 'c:\temp').Access | where {$_.IdentityReference -like '*\*'} | Select IdentityReference
The purpose is to get a list of users who have access to a folder.
the results give me the domain and the user.
Domain\username
and I just want the username as it will be used in a further SQL query to look up details.
so I figured the best way to do it was to split the returned string on the '\' and take the 2nd value of the array it creates.
so far I am not getting any results back.
You can create custom results with Select-Object:
(get-Acl 'c:\temp').Access | where {$_.IdentityReference -like '*\*'} | Select #{n='User'; e={$_.IdentityReference.Split('\')[1]}}
In PSv3+ you can take further advantage of member-access enumeration, combined with Split-Path -Leaf (which, as in WayneA's answer, is repurposed to extract the last \-separated component from a <realm>\<username> token):
(Get-Acl c:\temp).Access.IdentityReference | Split-Path -Leaf
Note that I've omitted the where {$_.IdentityReference -like '*\*'} filter, because - as far as I can tell - all .IdentifyReference match this pattern (with the first \-based token either being a domain name, a machine name, or a literal such as NT AUTHORITY or BUILTIN).
Also, this outputs an array of strings containing usernames only - whereas a Select-Object call without -ExpandProperty would output custom objects with the specified (possibly calculated) property/ies instead.
In PSv4+, you can make the command slightly more efficient by using the .ForEach() collection method:
(Get-Acl c:\temp).Access.IdentityReference.ForEach({ ($_ -split '\\')[-1] })
EBGreens answer is spot on, but I like to use split-path
You can do something like:
(get-Acl 'c:\temp').Access | where {$_.IdentityReference -like '*\*'} | Select #{name="UserName";Expression={$_.IdentityReference | split-path -leaf}}

using powershell and pipeing output od Select-Object to access selected columns

I have the power shell below that selectes certain fields
dir -Path E:\scripts\br\test | Get-FileMetaData | Select-Object name, Comments, Path, Rating
what i want to do is utilize Name,Comments,Path,Rating in further Pipes $_.name etc dosnt work
If I understand your question correctly, you want to do something with the output of Select-Object, but you want to do it in a pipeline.
To do this, you need to pass the output down the pipeline into a Cmdlet that accepts pipeline input (such as ForEach-Object). If the next operation in the pipeline does not accept pipeline input, you will have to set the output to a variable and access the information through the variable,
Using ForEach-Object
In this method, you will be processing each object individually. This will be similar to the first option in Method 1 (that is, dealing with individual items in the collection of items returned by Select-Object).
dir | Get-FileMetaData | Select-Object Name,Comments,Path,Rating | ForEach-Object {
# Do stuff with $_
# Note that $_ is a single item in the collection returned by Select-Object
}
The variable method is included in case your next Cmdlet does not accept pipeline input.
Using Variable
In this method, you will treat $tempVariable as an array and you can operate on each item. If need be, you can actually access each column individually, getting everything at once.
$tempVariable = dir | Get-FileMetaData | Select-Object Name,Comments,Path,Rating
# Do stuff with each Name by using $tempVariable[i].Name, etc.
# Or do stuff with all Names by using $tempVariable.Name, etc.

Combining Group-Object and ForEach-Object?

I'm developing a cmdlet called Merge-Xsd that can merge similar XML schemas. It takes a list of paths, loads the schemas, merges them, and produces an XMLDocument as output.
All schemas of a particular file name are considered "similar", and so what I'm doing is getting all of the child items in a particular directory structure, grouping them according to the file name, and then trying to pass them to my custom cmdlet.
Grouping them is easy:
$grouping = Get-ChildItem -Recurse -Filter *.xsd |
Group-Object -Property Name -AsHashTable -AsString
However, processing them as part of the same pipeline is not. I've gotten as close as this:
$grouping.Keys |
ForEach-Object { ($grouping[$_] |
Select-Object -ExpandProperty FullName | Merge-Xsd).Save("C:\Out\$_") }
But what I'd really like to be able to do is use ForEach-Object directly after Group-Object to iterate over each group item, thus eliminating the need for the separate $grouping variable.
How can I use ForEach-Object to get the key/value pair while keeping each invocation of Merge-Xsd scoped to that particular key/value pair?
20150224 UPDATE:
The Merge-Xsd option set is extremely basic:
NAME
Merge-Xsd
SYNTAX
Merge-Xsd [-Path] <string[]> [<CommonParameters>]
It is really just intended for throwing a bunch of files at it in one go and having them merged into a single output, which is an XmlDocument. (I modeled the output off of ConvertTo-Xml.)
I think you could just nest it like this:
Get-ChildItem -Recurse -Filter *.xsd |
Group-Object -Property Name |
ForEach-Object {
($_.Group.FullName | Merge-Xsd).Save("C:\Out\$($_.Name)")
}
I don't have your cmdlet or files but in my limited testing this would work.
Some Explanation
I took out the -AsHash and -AsString parameters so we could deal directly with the group objects returned by Group-Object.
The $_.Group.FullName is more complex than it seems on first glance. $_ here refers to a single group object, since we're in a ForEach-Object. The group object contains a property called Name which is the name of the group, and a property called Group which is actually a collection of the the individual items within the group, so $_.Group is a collection.
From here, it would make sense to pipe that to ForEach-Object again, since each of the items in that collection will be a FileInfo object, and you want to get the FullName property to pass to Merge-Xsd.
Here we take advantage of some powershell magic. When you refer to $c.Property where $c is a collection of objects with a Property property, you get back a collection that consists of the property objects.
So $props = $c.Property is the same as:
$props = $c | ForEach-Object { $_.Property }
Knowing that, we can pipe $_.Group.FullName directly into Merge-Xsd to pass along all of the fullnames from all of the files in the group.
In that context, $_.Name still refers to the group object, so it's the name of the group, not the name of the file.