The story: I read a json configuration file and somewhere in this, i get conversion challenges.
The json file
"FwRules":[{ "IP" : "222.33.44.00/27", "Comment" : "Santa" },
{ "IP" : "223.44.11.0/24", "Comment" : "Claus" },
Reading this file info a object gives me:
IP Comment
-- -------
222.33.44.00/27, Santa
223.44.11.0/24, Claus
I need to get to:
222.33.44.00/27
223.44.11.0/24
As you might guess, I want to use this in
New-NetFirewallRule -RemoteAddress $HERE
However column headers need to be removed.
The obvious way
$config.smtpservers.fwrules | select-object IP
returns what I want, but with column headers. And I really do not want to go the "foreach way", just because of OCD reasons.
So, is there a bright mind out there who can learn me how to strip of the column headers, because I cannot figure this out.
This should do the trick:
$config.smtpservers.fwrules.ip
With dot syntax, Powershell automatically builds an array from properties that exist for each array element.
Alternatively:
$config.smtpservers.fwrules | select-object -ExpandProperty IP
Related
I am trying to get a report out of Powershell and AD that will show me the list of items on this property page from Active Directory –
From ADUC, right click your Root Domain OU -> properties->Security tab->Advanced->Auditing-> Select/Open one of the auditing entries. It will look Something like this:
On that page you will see the Principal, Type, and Applies To fields at the top and on the bottom section, the Permissions and Properties being audited, checked or unchecked.
I want to list those items and their values via Powershell.
I get to that Auditing page by doing this:
AD:\> $acl = get-acl 'DC=domain,DC=company,DC=com' -Audit
AD:\> $acl.Audit
Then single out one of the entries:
AD:\> $acl.Audit[0]
ActiveDirectoryRights : GenericAll
InheritanceType : All
ObjectType : 00000000-0000-0000-0000-000000000000
InheritedObjectType : 00000000-0000-0000-0000-000000000000
ObjectFlags : None
AuditFlags : Success, Failure
IdentityReference : Everyone
IsInherited : False
InheritanceFlags : ContainerInherit
PropagationFlags : None
But that’s as far as I can get being a n00b. The only thing Ive been able to extract out of that list is the value itself and im not even sure which item if any of these might contain the items/values I want. Am I even in the right place?
Thanks in advance,
Richard
So here's the thing, the PowerShell ACL is only going to show you some of the things in that list. Here's what you can do to figure that bit out:
From what you have it looks like the ActiveDirectoryRights property is what's going to tell you what rights the given rule is affecting. Let's look at what that property's type is to see if we can get a list of what it considers to be valid values. We can run the .GetType() method on the property to see that it is the type [ActiveDirectoryRights], but that's not sufficient to get what we want. We'll want the full name, which we can get like this:
$acl.Audit[0].ActiveDirectoryRights.GetType()|Format-List
So the important things here are the BaseType and FullName properties. The BaseType is System.Enum, and the FullName is System.DirectoryServices.ActiveDirectoryRights. From that we can use the [Enum] base type to get the names associated with our type.
[enum]::GetNames([System.DirectoryServices.ActiveDirectoryRights])
That gets us this list of values:
CreateChild
DeleteChild
ListChildren
Self
ReadProperty
WriteProperty
DeleteTree
ListObject
ExtendedRight
Delete
ReadControl
GenericExecute
GenericWrite
GenericRead
WriteDacl
WriteOwner
GenericAll
Synchronize
AccessSystemSecurity
These can also be found here. That site also tells you what each means, and for things like GenericAll what other rights that groups together.
This is the info you're going to get from PowerShell, so if that's sufficient then awesome, you've got what you're looking for. If you expect to get all of the fine grained permissions for each object type listed I don't think you're going to want to use PowerShell for that. Yes, they're listed, but you're going to have to translate object type GUIDs. The only way I know of to do that is query AD for all of your classes that have a schemaIDGUID, and basically build a hashtable out of them that you can reference later when you're looking up all of these accesses. This bit you only have to do once, then just reference $GUIDHT when you need to lookup a GUID.
For example:
#Connect to ADDS and get a list of all objects with a schemaIDGUID
$root = Get-ADRootDSE
$schemaContext = $root.schemaNamingContext
$schemaObjects = Get-ADObject -SearchBase $schemaContext -Filter 'schemaIDGUID -like "*"' -Properties 'Name', 'schemaIDGUID', 'objectClass'
#Create hashtable with generic 'All' entry for all zero guids
$GUIDHT = #{[System.Guid]'00000000-0000-0000-0000-000000000000'=#{Name='All'}}
#Populate the hashtable with all of the GUIDs we found in AD
$schemaObjects|ForEach-Object{ $GUIDHT[$_.ObjectGUID]=$_ }
#Find the friendly name for a specific audit rule listing
$GUIDHT[$acl.Audit[0].ObjectType].Name
Then things start to get confusing for PropagationFlags vs InheritanceFlags. InheritanceFlags determine what kind of objects can inherit the rule. PropagationFlags determine if the rule applies to only the object, only the children of the object, or both.
I have installed Import-Excel Module for PowerShell by dfinke which has a great functionality but I'm facing some troubles with the headers.
I would like to insert only the text into a string array, but instead, it comes with the header even when -NoHeader is declared. According to the documentation it's not its function not insert the header in the variable but I'm looking for a way to do it. So far I came with a newbie solution of $xlsxArray | Format-Table -HideHeaders | Out-File C:\temp\info.txt and then remove the spaces with .Trim() so the file doesn't get written #{P1=ContentofTheCell}.
Is there a better way to accomplish it?
Thank you so far.
You didn't give enough detail about the desired output, but I'll try to give guidance.
Import-Excel will return objects. Normally the column headers become the property names on the objects. When you use -NoHeader, the property names are simply named P1, P2 etc... An object's properties must have names. If you want the data from those properties you may have to process differently. You can access the properties like any other object collection:
$ExcelData = Import-Excel "C:\Temp\Some.xlsx"
$ExcelData.PropertyName
The PropertyName would be the column header from the file. So let's say I had a colum named Balance in that file, then the example would something like:
$ExcelData = Import-Excel "C:\Temp\Some.xlsx"
$ExcelData.balance
Output:
7254.74
4268.16
3051.32
64.77
323.22
146.62
14798.83
Note: these are pretty simple examples. Obviously things can get more complex.
I am looking to create a rule in Office 365 applied to all of the members in our org.
I would like this rule to append a warning on all incoming email from outside the organization with the same Display Names as our users.
When I attempt to apply it to all of the users in our org I get an error stating that the rule is too long.
In order to solve that I pulled a group, but I am still about 1000 characters over the limit.
I would like to make two variables, that each hold one half of the list, created by this command:
(Get-DistibutionGroupMember -Identity email#contoso.com -ResultSize Unlimited).DisplayName
I have attempted to modify the ResultSize parameter, but what I would need is result 1-100 and then 100-200 from the same list.
Another caveat to this problem is that the list cannot be static. It is something that the script will have to update every time it is run.
There is a sub-string command that you can use on a particular username that I have utilized when I made something for AD, but I am not aware of any way to break up a list like this.
If anyone has any other ways to solve this issue I would be more than open to any suggestion.
Thanks for taking the time to read this!
There are many ways of doing it. I found it very readable.
My favorite one is this one:
$ObjectList = 1..1000
$Step = 100
$counter = [pscustomobject] #{ Value = 0 }
$ObjectListSplitted = $ObjectList | Group-Object -Property { math]::Floor($counter.Value++ / $step) }
Then if you want to show the third subset just use this format :
$ObjectListSplitted[3].Group
Have a look to this solution already explained.
As a note other languages are capable of slicing an array of object with a start, stop and a step, have a look here if you're curious.
I'm trying to do something like this (tried to make it look like a table, but wasn't working with markdown,html or bunch of spaces):
Column1
Location info
Location #
Location name
Location phone
Location address
Column2
[blank]
1
NYC
789-987-1234
12 Some Blvd
Column3
Network info
Location Octet
External IP
Some other IP
More Ips
Column4
[blank]
345
10.89.52.468
10.346.345.1
10.326.345.2
I've tried creating new objects, converting arrays/hash to csv and then back and I'm having no luck. I've read some other threads but they all incorporate the use of cmdlets that create objects already and just working with that. I thought convert from csv did that, and it does I think, but how Im converting it back may be off. The above table is thus 6 columns and 5 rows, the top row having column 2 and 4 being blank.
I'd really like to learn how to do this, since I'll probably be employing it for other tasks as well.
I believe you are trying to achieve something like this? :
$col1=#("Location info","Location #","Location name","Location phone","Location address");
$col2=#("","1","NYC","789-987-1234","12 Some Blvd");
$col3=#("Network info","Location Octet","External IP","Some other IP","More Ips");
$col4=#("","345","10.89.52.468","10.346.345.1","10.326.345.2");
$hash=#{"Column1"=$col1;"Column2"=$col2;"Column3"=$col3;"Column4"=$col4};
$obj = New-Object PSObject -Property $hash
$obj|Format-Table -Wrap -AutoSize
You will get the data as you've specified. You can use -ExpandProperty "Column1" (e.g. if you want to expand on all it's values). You can use ConvertTo-Html if you like to create a html-table of the data.
However, I would consider structuring the data in another fasion. How about keeping this data in seperate objects instead of formatting it in this way?
You could e.g. have a set of objects with the properties representing what you want.
E.g. objects having the representative data :
$obj = new-object PSObject -Property #{"Location info"="My loc"; "Location #"="My location"}
$obj2 = new-object PSObject -Property #{"Location info"="My loc2"; "Location #"="My location2"}
$myLocations = #($obj,$obj2);
That'd be more representative, and you could play and format the $myLocations for the properties you'd want.
For example, looking at a processes threads shows something like this:
PS C:\> (Get-Process)[0] | Format-List -Property Threads
Threads : {1548, 1600, 15940, 13996}
But if you actually grab that property directly, it looks like this:
PS C:\> (Get-Process)[0].Threads
BasePriority : 8
CurrentPriority : 9
Id : 1548
IdealProcessor :
PriorityBoostEnabled :
PriorityLevel :
PrivilegedProcessorTime :
StartAddress : 8790537024736
StartTime :
ThreadState : Wait
TotalProcessorTime :
UserProcessorTime :
WaitReason : UserRequest
ProcessorAffinity :
Site :
Container :
BasePriority : 8
... etc
Format list obviously has a method to summarize objects intelligently. It took a list of objects, pulled out a representative property from each one, and displayed it as a short array. I cannot find a method or cmdlet that allows me to summarize an collection of objects in the same manner.
I want to be able to pass an arbitrary collection of objects to a method and have it summarize. This is used when listing email addresses in Exchange objects, listing groups in AD objects, and many other places... I doubt these are all special cases.
To expand (after learning more from #JoelSmith's comments):
.NET Objects have formatting definitions that are used by Powershell when formatting output. Additional details are available using help about_Format.ps1xml[1]. These definitions are generic and can be accessed by any command, but by default there are no functions in Powershell to directly retrieve the output of an object property directly as it would be displayed in Format-List.
One hackish workaround is to split and strip the output like so:
(Get-Mailbox user | Format-List -Property Languages | Out-String).Split(':')[1].Trim()
# => {en-US,fr-CA}
However this method is extremely fragile, and will fail when the output spans multiple lines or contains a colon in the output:
(Get-Mailbox user | Format-List -Property EmailAddresses | Out-String).Split(':')[1].Trim()
# => {smtp
What is needed is a method that reads the formatting definition defined for the object and retrieves it directly, then use it to output the desired string. I have failed to find any example online.
You can use the
PSStandardMembers.DefaultDisplayProperty
and
PSStandardMembers.DefaultDisplayPropertySet
properties of your objects to determine the default properties that should be displayed for each type. You can read more about it here. We've run into a similar problem recently in our like PowerShell project. You can find this discussion we've had helpful. There are some subtle differences between PS v2 and v3 which we debate on that thread.
Usually .ToString() works but sometimes they forget to implement that method.
(Get-Process)[0] | %{$_.Threads.Id}
EDIT: to answer your comment below
(Get-Process)[0] | Format-List -Property Threads | Out-String
Unfortunately not all cmdlets are the same.
Are you looking for something like this?
(Get-Process)[0].Threads | Format-Table -Property ID -AutoSize
Id
--
13060
13064
13068
13072
13076
13080
13084
This needs to be customized for each cmdlet depending on what the output is and what fields you need. The reason it doesn't work with just (Get-Process)[0] | Format-Table -Property Threads -AutoSize is because Threads returns thread-objects, and an array of objects are displayed like your first sample (string-presentation of your objects in a collection { .. }) .
Here's what I can tell so far:
The Id property is the default display property for a thread object (System.Diagnostics.ProcessThread).
I couldn't find any tracks of this in any of PowerShell's type files but I can change the way Format-* display threads (requires PowerShell 3.0).
By default the format cmdlets prints the Id value of each thread object:
Threads : {1548, 1600, 15940, 13996}
Formatting cmdlets checks the value of the $FormatEnumerationLimit variable (default is 4) to decide how to format the object.
If the result is one object (scalar) only it will print as:
Threads : 1548
If it's a collection of items and the collection count is up to the value of $FormatEnumerationLimit (4) it will display as:
Threads : {1548, 1600, 15940, 13996}
A count greater than $FormatEnumerationLimit will look like (... indicates that there are more objects):
Threads : {1548, 1600, 15940, 13996...}
I can tell Id is the default property in use because I can change it to another property and see its value reflecting in the output.
For example, Here I'm setting the ThreadState as the default display property:
PS> Update-TypeData -TypeName System.Diagnostics.ProcessThread -DefaultDisplayProperty ThreadState -Force
PS> (Get-Process)[0] | Format-List -Property Threads
Threads : {Wait, Wait, Wait, Wait...}
# revert back
PS> Update-TypeData -TypeName System.Diagnostics.ProcessThread -DefaultDisplayProperty Id -Force
Hope that helps