Combining Get-ACL results into 1 object - powershell

Please excuse my beginner level powershell.
I want to be able to combine the results of different results of Get-ACL into one object that'll later be exported
At the very basic level all I want is to combine different results of different folders for code below:
$test = (get-acl $path).Access | select -ExpandProperty IdentityReference
This gives me a result of:
Value
-----
NT AUTHORITY\SYSTEM
BUILTIN\Administrators
Etc
Etc
I want an object that will be like some thing like this (plus more columns, about 4-5 total):
Folder1 Folder2
----- -------
NT AUTHORITY\SYSTEM NT AUTHORITY\SYSTEM
BUILTIN\Administrators BUILTIN\Administrators
Etc Etc
Etc Etc
I tried exploring building a custom object, but I couldn't find a way to list the objects values properly like my first results
$Custom = New-Object PSObject
$Custom | Add-Member -type NoteProperty -name Folder1 -value $test.value
Gives me:
Folder1
-------
{NT AUTHORITY\SYSTEM, BUILTIN\Administrators, etc, etc ...}
How can I handle this to give me a result like the first object and then in turn add more to the custom object?
Thanks in advance,
Lou

Based on your description, I think what you need is simply a collection of objects, i.e., $aclObjectList
This script captures a collection where each object is the type of object returned by get-acl. I do this just so I can show you the path property of each object to demonstrate that each object is for one of the three folders involved
Then, the script loops through the array of get-acl objects and outputs the path and IdentityReference of each
If you want to export a single object, then export $aclObjectList
cls
#define and declare an array. A System.Collections.ArrayList can be big and is fast
$aclObjectList = New-Object System.Collections.ArrayList
$aclObjectList.clear()
$path = "C:\Temp\topFolder\Folder 1"
$aclObject = (get-acl $path)
$aclObjectList.Add($aclObject) | Out-Null
$path = "C:\Temp\topFolder\Folder 2"
$aclObject = (get-acl $path)
$aclObjectList.Add($aclObject) | Out-Null
$path = "C:\Temp\topFolder\Folder 3"
$aclObject = (get-acl $path)
$aclObjectList.Add($aclObject) | Out-Null
foreach ($aclObject in $aclObjectList)
{
write-host ($aclObject.Path)
$aclAccessObject = $aclObject.Access | select -ExpandProperty IdentityReference
foreach ($aclAccessItem in $aclAccessObject)
{
write-host ("item=" + $aclAccessItem.Value)
}
write-host
}
Output is:
Microsoft.PowerShell.Core\FileSystem::C:\Temp\topFolder\Folder 1
item=BUILTIN\Administrators
item=NT AUTHORITY\SYSTEM
item=BUILTIN\Users
item=NT AUTHORITY\Authenticated Users
item=NT AUTHORITY\Authenticated Users
Microsoft.PowerShell.Core\FileSystem::C:\Temp\topFolder\Folder 2
item=BUILTIN\Administrators
item=NT AUTHORITY\SYSTEM
item=BUILTIN\Users
item=NT AUTHORITY\Authenticated Users
item=NT AUTHORITY\Authenticated Users
Microsoft.PowerShell.Core\FileSystem::C:\Temp\topFolder\Folder 3
item=BUILTIN\Administrators
item=NT AUTHORITY\SYSTEM
item=BUILTIN\Users
item=NT AUTHORITY\Authenticated Users
item=NT AUTHORITY\Authenticated Users
By the way, the datatype of the object returned by get-acl is a System.Security.AccessControl.DirectorySecurity. You can see this by, e.g., piping one of the $aclObject variables to Get-Member:
$aclObject | Get-Member
TypeName: System.Security.AccessControl.DirectorySecurity
Name MemberType Definition
---- ---------- ----------
Access CodeProperty System.Security.AccessControl.AuthorizationRuleCollection Access{get=GetAccess;}
CentralAccessPolicyId CodeProperty System.Security.Principal.SecurityIdentifier CentralAccessPolicyId{get=GetCentralAccessPolicyId;}
CentralAccessPolicyName CodeProperty System.String CentralAccessPolicyName{get=GetCentralAccessPolicyName;}
Group CodeProperty System.String Group{get=GetGroup;}
Owner CodeProperty System.String Owner{get=GetOwner;}
Path CodeProperty System.String Path{get=GetPath;}
Sddl CodeProperty System.String Sddl{get=GetSddl;}
AccessRuleFactory Method System.Security.AccessControl.AccessRule AccessRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited...
AddAccessRule Method void AddAccessRule(System.Security.AccessControl.FileSystemAccessRule rule)
AddAuditRule Method void AddAuditRule(System.Security.AccessControl.FileSystemAuditRule rule)
AuditRuleFactory Method System.Security.AccessControl.AuditRule AuditRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited, ...
Equals Method bool Equals(System.Object obj)
GetAccessRules Method System.Security.AccessControl.AuthorizationRuleCollection GetAccessRules(bool includeExplicit, bool includeInherited, type targetType)
GetAuditRules Method System.Security.AccessControl.AuthorizationRuleCollection GetAuditRules(bool includeExplicit, bool includeInherited, type targetType)
GetGroup Method System.Security.Principal.IdentityReference GetGroup(type targetType)
GetHashCode Method int GetHashCode()
GetOwner Method System.Security.Principal.IdentityReference GetOwner(type targetType)
GetSecurityDescriptorBinaryForm Method byte[] GetSecurityDescriptorBinaryForm()
GetSecurityDescriptorSddlForm Method string GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections includeSections)
GetType Method type GetType()
ModifyAccessRule Method bool ModifyAccessRule(System.Security.AccessControl.AccessControlModification modification, System.Security.AccessControl.AccessRule rule, [ref] bool modi...
ModifyAuditRule Method bool ModifyAuditRule(System.Security.AccessControl.AccessControlModification modification, System.Security.AccessControl.AuditRule rule, [ref] bool modified)
PurgeAccessRules Method void PurgeAccessRules(System.Security.Principal.IdentityReference identity)
PurgeAuditRules Method void PurgeAuditRules(System.Security.Principal.IdentityReference identity)
RemoveAccessRule Method bool RemoveAccessRule(System.Security.AccessControl.FileSystemAccessRule rule)
RemoveAccessRuleAll Method void RemoveAccessRuleAll(System.Security.AccessControl.FileSystemAccessRule rule)
RemoveAccessRuleSpecific Method void RemoveAccessRuleSpecific(System.Security.AccessControl.FileSystemAccessRule rule)
RemoveAuditRule Method bool RemoveAuditRule(System.Security.AccessControl.FileSystemAuditRule rule)
RemoveAuditRuleAll Method void RemoveAuditRuleAll(System.Security.AccessControl.FileSystemAuditRule rule)
RemoveAuditRuleSpecific Method void RemoveAuditRuleSpecific(System.Security.AccessControl.FileSystemAuditRule rule)
ResetAccessRule Method void ResetAccessRule(System.Security.AccessControl.FileSystemAccessRule rule)
SetAccessRule Method void SetAccessRule(System.Security.AccessControl.FileSystemAccessRule rule)
SetAccessRuleProtection Method void SetAccessRuleProtection(bool isProtected, bool preserveInheritance)
SetAuditRule Method void SetAuditRule(System.Security.AccessControl.FileSystemAuditRule rule)
SetAuditRuleProtection Method void SetAuditRuleProtection(bool isProtected, bool preserveInheritance)
SetGroup Method void SetGroup(System.Security.Principal.IdentityReference identity)
SetOwner Method void SetOwner(System.Security.Principal.IdentityReference identity)
SetSecurityDescriptorBinaryForm Method void SetSecurityDescriptorBinaryForm(byte[] binaryForm), void SetSecurityDescriptorBinaryForm(byte[] binaryForm, System.Security.AccessControl.AccessContr...
SetSecurityDescriptorSddlForm Method void SetSecurityDescriptorSddlForm(string sddlForm), void SetSecurityDescriptorSddlForm(string sddlForm, System.Security.AccessControl.AccessControlSectio...
ToString Method string ToString()
PSChildName NoteProperty string PSChildName=Folder 1
PSDrive NoteProperty PSDriveInfo PSDrive=C
PSParentPath NoteProperty string PSParentPath=Microsoft.PowerShell.Core\FileSystem::C:\Temp\topFolder
PSPath NoteProperty string PSPath=Microsoft.PowerShell.Core\FileSystem::C:\Temp\topFolder\Folder 1
PSProvider NoteProperty ProviderInfo PSProvider=Microsoft.PowerShell.Core\FileSystem
AccessRightType Property type AccessRightType {get;}
AccessRuleType Property type AccessRuleType {get;}
AreAccessRulesCanonical Property bool AreAccessRulesCanonical {get;}
AreAccessRulesProtected Property bool AreAccessRulesProtected {get;}
AreAuditRulesCanonical Property bool AreAuditRulesCanonical {get;}
AreAuditRulesProtected Property bool AreAuditRulesProtected {get;}
AuditRuleType Property type AuditRuleType {get;}
AccessToString ScriptProperty System.Object AccessToString {get=$toString = "";...
AuditToString ScriptProperty System.Object AuditToString {get=$toString = "";...

Related

Powershell Get-EventLog find event with the matching string in its message

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.

How to query Powershell cmdlet parameter values

How can I get a list possible values of cmdlet parameter programmatically?
E.g for New-Item -Type:
File
Directory
SymbolicLink
Junction
HardLink
Get-Help New-Item -Full
Get-Command New-Item | select *
You can also check the online documentation (e.g. New-Item).
Or you can use
(Get-Command -Name new-item).parametersets
as suggested by vonPryz above.
For "Get-" cmdlets I usually create an object and then do a Get-Member to retrieve the definition of the members.
e.g.
$item = Get-Item .\test.csv
$item | Get-Member
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=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] Target{get=GetTarget;}
AppendText Method System.IO.StreamWriter AppendText()
CopyTo Method System.IO.FileInfo CopyTo(string destFileName), System.IO.FileInfo CopyTo(string destFileName, bool overwrite)
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.Security.AccessControl.FileSecurity GetAccessControl(System.Security.AccessControl.AccessControlSections includeSections)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetObjectData Method void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context), void ISerializable.GetObjectData(System.Runtime.Serialization.Se...
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 Open(System.IO.FileMode mode, System.IO.FileAccess access), System.IO.FileStream Open(System.IO.FileMode mode, System.I...
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 destinationBackupFileName), System.IO.FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMe...
SetAccessControl Method void SetAccessControl(System.Security.AccessControl.FileSecurity fileSecurity)
ToString Method string ToString()
PSChildName NoteProperty string PSChildName=test.csv
PSDrive NoteProperty PSDriveInfo PSDrive=C
PSIsContainer NoteProperty bool PSIsContainer=False
PSParentPath NoteProperty string PSParentPath=Microsoft.PowerShell.Core\FileSystem::C:\test
PSPath NoteProperty string PSPath=Microsoft.PowerShell.Core\FileSystem::C:\test\test.csv
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.Remove($this.Name.Length - $this.Extension.Length)}else{$this.Name};}
VersionInfo ScriptProperty System.Object VersionInfo {get=[System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName);}

Get all the names of the applications in a site

I am trying to write a powershell script which gets the names of each application in a website in IIS in order to change the app pool associated with it. I am able to get the website, but I don't see a clear way to fetch each of the names?
Eg. I want to loop through them all: Api, Services, etc.. and then use
Set-ItemProperty "IIS:\Sites\RootSite\$loopedValue" -Name 'applicationPool' -Value $NewPool
I'm trying this:
Get-WebApplication -Site 'ABC'
Name Application pool Protocols Physical Path
---- ---------------- --------- -------------
Api ABC http C:\Api
Services ABC http C:\Services
Director ABC http C:\Director
ReportingServer ABC http C:\ReportingServer
But there is no way to get the Name from the members of Get-WebApplication.
Get-WebApplication | Get-Member
TypeName: Microsoft.IIs.PowerShell.Framework.ConfigurationElement#site#application
Name MemberType Definition
---- ---------- ----------
ClearLocalData Method void ClearLocalData()
Copy Method void Copy(Microsoft.IIs.PowerShell.Framework.ConfigurationElement target, bool recurse)
Delete Method void Delete()
Equals Method bool Equals(System.Object obj), bool IEquatable[ConfigurationElement].Equals(Microsoft.IIs.PowerShell.Framework.Conf...
GetAttribute Method Microsoft.IIs.PowerShell.Framework.ConfigurationAttribute GetAttribute(string attributeName)
GetAttributeValue Method System.Object GetAttributeValue(string attributeName)
GetChildElement Method Microsoft.IIs.PowerShell.Framework.ConfigurationElement GetChildElement(string elementName), Microsoft.IIs.PowerShel...
GetCollection Method Microsoft.IIs.PowerShell.Framework.ConfigurationElementCollection GetCollection(string collectionName), Microsoft.II...
GetHashCode Method int GetHashCode()
GetMetadata Method System.Object GetMetadata(string metadataType)
GetParentElement Method Microsoft.IIs.PowerShell.Framework.ConfigurationElement GetParentElement()
GetType Method type GetType()
LoadProperties Method void LoadProperties(System.Collections.Generic.Dictionary[string,System.Object] propCollection)
SetAttributeValue Method void SetAttributeValue(string attributeName, System.Object value)
SetMetadata Method void SetMetadata(string metadataType, System.Object value)
ToPSObject Method psobject ToPSObject(Microsoft.IIs.PowerShell.Framework.ConfigurationElement parent)
ToString Method string ToString()
Update Method void Update(Microsoft.IIs.PowerShell.Framework.ConfigurationElement source), bool Update(psobject data)
UpdateCollection Method bool UpdateCollection(psobject[] arr)
applicationPool NoteProperty string applicationPool=ABC
Collection NoteProperty psobject[] Collection=System.Management.Automation.PSObject[]
ConfigurationPathType NoteProperty ConfigurationPathNodeType ConfigurationPathType=Location
enabledProtocols NoteProperty string enabledProtocols=http
ItemXPath NoteProperty string ItemXPath=/system.applicationHost/sites/site[#name='ABC' and #id='1']/application[#path='/API']
Location NoteProperty string Location=
path NoteProperty string path=/ApiDoc
preloadEnabled NoteProperty bool preloadEnabled=False
PSPath NoteProperty string PSPath=MACHINE/WEBROOT/APPHOST
serviceAutoStartEnabled NoteProperty bool serviceAutoStartEnabled=False
serviceAutoStartProvider NoteProperty string serviceAutoStartProvider=
virtualDirectoryDefaults NoteProperty Microsoft.IIs.PowerShell.Framework.ConfigurationElement#application#virtualDirectoryDefaults virtualDirectoryDefault...
Item ParameterizedProperty System.Object Item(string attributeName) {get;set;}
Attributes Property Microsoft.IIs.PowerShell.Framework.ConfigurationAttributeCollection Attributes {get;}
ChildElements Property Microsoft.IIs.PowerShell.Framework.ConfigurationChildElementCollection ChildElements {get;}
ElementTagName Property string ElementTagName {get;}
Methods Property Microsoft.IIs.PowerShell.Framework.ConfigurationMethodCollection Methods {get;}
Schema Property Microsoft.IIs.PowerShell.Framework.ConfigurationElementSchema Schema {get;}
PhysicalPath ScriptProperty System.Object PhysicalPath {get=$pquery = $this.ItemXPath + "/virtualDirectory[#path='/']/#physicalPath"...
I don't really want to parse a string value from the path or PhysicalPath to do this. Is there another way?
An alternative way I came up with was to join the two results from Get-WebSite and Get-WebApplication
(get-website | select-object #{n='Site'; e={$_.Name}},#{n='Location'; e={$_.PhysicalPath}}) + (get-webapplication | select-object #{n='Site'; e= {$_.GetParentElement().Attributes['name'].value + $_.path }},#{n='Location'; e= {$_.PhysicalPath}})
Output:
Site WebType Location
---- ------- --------
MEDIA WebSite c:\mir\data
DATA WebSite d:\data
Tu***.M*.A***o.Sa****x.N***e WebSite C:\WebSite\Tu***.M*.A***o.Sa****x.N***e
Tu***.***********on.*****ime WebSite C:\WebSite\Tu***.***********on.*****ime
Tu***.**.*****.***********ion WebSite C:\WebSite\Tu***.**.*****.***********ion
Tu***.********.**.****App WebSite C:\WEB\Tu***.********.**.****App
Tu***.********.**.****App/api WebApplication C:\Web\Tu***.********.**.****vate
The following will provide the application names for all sites:
(Get-ChildItem -Path 'IIS:\Sites' -Recurse | Where-Object {$_.NodeType -eq 'application'}).Name
The following will return the application names for Default Web Site:
(Get-ChildItem -Path 'IIS:\Sites\Default Web Site' | Where-Object {$_.NodeType -eq 'application'}).Name

Select-Object -ExpandProperty vs. Get-ItemPropertyValue

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

Workaround around broken by design Powershell gci -exclude

this will sound like a bad joke, but apparently geniuses from MS arent capable of making uber complicated -exclude gci parameter work. By "genious" design it only works on files, not on entire path. So how to make it work.
For example how to exclude all files whose path contains "Windows" substring?
naive
gci -exclude "*Windows*" -rec
doesnt work
EDIT: googled/figured out this:
| where {$_.DirectoryName -notmatch ".*abcdef.*" }
If somebody knows better solution please share. If not will close question.
The solution is this:
gci ./ |Where{ $_.PSPath -notmatch ".*Windows.*"}
BTW useful thing for guessing solutions to problems like this is to know what methods the current object has, for that I used Get-Member. Example output:
PS C:\Users\jh> gci ./ | Get-Member
TypeName: System.IO.DirectoryInfo
Name MemberType Definition
---- ---------- ----------
Mode CodeProperty System.String Mode{get=Mode;}
Create Method void Create(), void Create(System.Security.AccessControl.DirectorySecurity ...
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateSubdirectory Method System.IO.DirectoryInfo CreateSubdirectory(string path), System.IO.Director...
Delete Method void Delete(), void Delete(bool recursive)
EnumerateDirectories Method System.Collections.Generic.IEnumerable[System.IO.DirectoryInfo] EnumerateDi...
EnumerateFiles Method System.Collections.Generic.IEnumerable[System.IO.FileInfo] EnumerateFiles()...
EnumerateFileSystemInfos Method System.Collections.Generic.IEnumerable[System.IO.FileSystemInfo] EnumerateF...
Equals Method bool Equals(System.Object obj)
GetAccessControl Method System.Security.AccessControl.DirectorySecurity GetAccessControl(), System....
GetDirectories Method System.IO.DirectoryInfo[] GetDirectories(), System.IO.DirectoryInfo[] GetDi...
GetFiles Method System.IO.FileInfo[] GetFiles(string searchPattern), System.IO.FileInfo[] G...
GetFileSystemInfos Method System.IO.FileSystemInfo[] GetFileSystemInfos(string searchPattern), System...
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 destDirName)
Refresh Method void Refresh()
SetAccessControl Method void SetAccessControl(System.Security.AccessControl.DirectorySecurity direc...
ToString Method string ToString()
PSChildName NoteProperty System.String PSChildName=Contacts
PSDrive NoteProperty System.Management.Automation.PSDriveInfo PSDrive=C
PSIsContainer NoteProperty System.Boolean PSIsContainer=True
PSParentPath NoteProperty System.String PSParentPath=Microsoft.PowerShell.Core\FileSystem::C:\Users\jh
PSPath NoteProperty System.String PSPath=Microsoft.PowerShell.Core\FileSystem::C:\Users\jh\Cont...
PSProvider NoteProperty System.Management.Automation.ProviderInfo PSProvider=Microsoft.PowerShell.C...
Attributes Property System.IO.FileAttributes Attributes {get;set;}
CreationTime Property datetime CreationTime {get;set;}
CreationTimeUtc Property datetime CreationTimeUtc {get;set;}
Exists Property bool Exists {get;}
Extension Property string Extension {get;}
FullName Property string FullName {get;}
LastAccessTime Property datetime LastAccessTime {get;set;}
LastAccessTimeUtc Property datetime LastAccessTimeUtc {get;set;}
LastWriteTime Property datetime LastWriteTime {get;set;}
LastWriteTimeUtc Property datetime LastWriteTimeUtc {get;set;}
Name Property string Name {get;}
Parent Property System.IO.DirectoryInfo Parent {get;}
Root Property System.IO.DirectoryInfo Root {get;}
BaseName ScriptProperty System.Object BaseName {get=$this.Name;}