shortened output of property values in recursive function - powershell

I want to recursively enumerated all WMI namespaces.I have this function:
function Get-WmiNamespace {
Param(
[parameter()]
[string]$Namespace = 'root',
[parameter()]
[string]$Locale = 'MS_409',
[parameter()]
[switch]$Recurse
)
Begin {
$WMIParams = #{
Namespace = $Namespace
Class = '__NAMESPACE'
Locale = $Locale
ErrorAction = 'SilentlyContinue'
}
}
Process {
Get-WmiObject #WMIParams |
Sort-Object -Property Name -CaseSensitive -Culture "en-US" |
ForEach-Object {
$WMIParams.Namespace = "{0}\{1}" -f $_.__NAMESPACE, $_.Name
$object = [PSCustomObject] #{
Namespace = $WMIParams.Namespace
}
$object.PSTypeNames.Insert(0,'Wmi.Namespace.Name')
$object
if ($recurse) {
$PSBoundParameters.Namespace = $WMIParams.Namespace
Get-WMINamespace #PSBoundParameters
}
}
}
}
Inspired here:
[https://learn-powershell.net/2014/05/09/quick-hits-list-all-available-wmi-namespaces-using-powershell/]
I get this output:
Namespace
---------
ROOT\Appv
ROOT\CIMV2
ROOT\CIMV2\mdm
ROOT\CIMV2\mdm\dmmap
ROOT\CIMV2\mdm\MS_405
ROOT\CIMV2\ms_405
ROOT\CIMV2\ms_409
ROOT\CIMV2\power
ROOT\CIMV2\power\m...
ROOT\CIMV2\power\m...
ROOT\CIMV2\Security
ROOT\CIMV2\Securit...
ROOT\CIMV2\Securit...
ROOT\CIMV2\Termina...
ROOT\CIMV2\Termina...
ROOT\Cli
ROOT\Cli\MS_405
ROOT\Cli\MS_409
ROOT\DEFAULT
ROOT\DEFAULT\ms_405
ROOT\DEFAULT\ms_409
ROOT\directory
ROOT\directory\LDAP
ROOT\directory\LDA...
ROOT\directory\LDA...
ROOT\Hardware
ROOT\Hardware\ms_405
ROOT\Hardware\ms_409
ROOT\Intel_ME
ROOT\IntelNCS2
ROOT\IntelNCS2\ms_409
ROOT\Interop
ROOT\Interop\ms_405
ROOT\Interop\ms_409
ROOT\Microsoft
ROOT\Microsoft\Hom...
ROOT\Microsoft\pro...
ROOT\Microsoft\Sec...
ROOT\Microsoft\Uev
ROOT\Microsoft\Win...
...
ROOT\Microsoft\Win...
ROOT\msdtc
ROOT\PEH
ROOT\Policy
ROOT\Policy\ms_405
ROOT\Policy\ms_409
ROOT\RSOP
ROOT\RSOP\Computer
ROOT\RSOP\User
ROOT\SECURITY
ROOT\SecurityCenter
ROOT\SecurityCenter2
ROOT\ServiceModel
ROOT\StandardCimv2
ROOT\StandardCimv2...
ROOT\StandardCimv2...
ROOT\StandardCimv2...
ROOT\StandardCimv2...
ROOT\subscription
ROOT\subscription\...
ROOT\subscription\...
ROOT\WMI
ROOT\WMI\ms_405
ROOT\WMI\ms_409
Namespaces names are truncated.
I guess the reason is the width of Name column is set in first iteration of function Get-WmiNamespace according longest value (ROOT\SecurityCenter2).
It can be fixed by piping output to Format-Table with -AutoSize parameter:
Namespace
---------
ROOT\Appv
ROOT\CIMV2
ROOT\CIMV2\mdm
ROOT\CIMV2\mdm\dmmap
ROOT\CIMV2\mdm\MS_405
ROOT\CIMV2\ms_405
ROOT\CIMV2\ms_409
ROOT\CIMV2\power
ROOT\CIMV2\power\ms_405
ROOT\CIMV2\power\ms_409
ROOT\CIMV2\Security
ROOT\CIMV2\Security\MicrosoftTpm
ROOT\CIMV2\Security\MicrosoftVolumeEncryption
ROOT\CIMV2\TerminalServices
ROOT\CIMV2\TerminalServices\ms_405
ROOT\Cli
ROOT\Cli\MS_405
ROOT\Cli\MS_409
...
What would be the best way to solve this behavior?

The entire name is stored in the namespace property. If you just want to see it in the command output, you could use -ExpandProperty from Select-Object
Get-WmiNamespace -Recurse | select -ExpandProperty namespace
Also, just adding Sort shows the full name
Get-WmiNamespace -Recurse | Sort

Without using Expand and Doug is points out, you can just dot it and avoid the format stuff or futzing with trying to change the function itself, etc. Well, at least for a single column.
(Get-WmiNamespace -Recurse).Namespace
# Results
<#
(Get-WmiNamespace -Recurse).Namespace
ROOT\Appv
...
ROOT\CIMV2\Security\MicrosoftTpm
ROOT\CIMV2\Security\MicrosoftVolumeEncryption
ROOT\CIMV2\TerminalServices
ROOT\CIMV2\TerminalServices\ms_409
...
ROOT\Microsoft\SqlServer\ComputerManagement15
ROOT\Microsoft\SqlServer\ComputerManagement15\MS_409
ROOT\Microsoft\SqlServer\ServerEvents
ROOT\Microsoft\SqlServer\ServerEvents\MSSQLSERVER
...
ROOT\Microsoft\Windows\DesiredStateConfigurationProxy
ROOT\Microsoft\Windows\DesiredStateConfigurationProxy\MS_409
...
#>
If you saying you want, like a Linux column file list of these then other steps are needed You can do this Linux like multi-column using the Format-Wide cmdlet.
For Example:
Get-ChildItem -Path 'C:\Program Files' -Recurse |
Format-Wide -Property Name
Get-ChildItem -Path 'C:\Program Files' -Recurse |
Format-Wide -Property Name -Column 5
So, for this list to get a table-like view, do the same thing.
Get-WmiNamespace -Recurse |
Format-Wide -Property namespace -Column 3
# Results
<#
ROOT\Appv ROOT\aspnet ROOT\CIMV2
ROOT\CIMV2\mdm ROOT\CIMV2\mdm\dmmap ROOT\CIMV2\mdm\MS_409
ROOT\CIMV2\ms_409 ROOT\CIMV2\NV ROOT\CIMV2\NV\Events
....
#>
Use whatever column count that fits your screen. No, you cannot use columns and autosize together as they are mutually exclusive.
So, as Doug points out you can make your own formatter, or as per your comment...
'My point was whether there is a way to modify function itself to get
table formated '
...you can doctor the function to use aforementioned for the results you are after.

Related

PowerShell Export-CSV - Missing Columns [duplicate]

This question already has an answer here:
Not all properties displayed
(1 answer)
Closed 1 year ago.
This is a follow-up question from PowerShell | EVTX | Compare Message with Array (Like)
I changed the tactic slightly, now I am collecting all the services installed,
$7045 = Get-WinEvent -FilterHashtable #{ Path="1system.evtx"; Id = 7045 } | select
#{N=’Timestamp’; E={$_.TimeCreated.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')}},
Id,
#{N=’Machine Name’; E={$_.MachineName}},
#{N=’Service Name’; E={$_.Properties[0].Value}},#{N=’Image Path’;E=$_.Properties[1].Value}},
#{N=’RunAsUser’; E={$_.Properties[4].Value}},#{N=’Installed By’; E={$_.UserId}}
Now I match each object for any suspicious traits and if found, I add a column 'Suspicious' with the value 'Yes'. This is because I want to leave the decision upto the analyst and pretty sure the bad guys might use something we've not seen before.
foreach ($Evt in $7045)
{
if ($Evt.'Image Path' -match $sus)
{
$Evt | Add-Member -MemberType NoteProperty -Name 'Suspicious' -Value 'Yes'
}
}
Now, I'm unable to get PowerShell to display all columns unless I specifically Select them
$7045 | Format-Table
Same goes for CSV Export. The first two don't include the Suspicious Column but the third one does but that's because I'm explicitly asking it to.
$7045 | select * | Export-Csv -Path test.csv -NoTypeInformation
$7045 | Export-Csv -Path test.csv -NoTypeInformation
$7045 | Select-Object Timestamp, Id, 'Machine Name', 'Service Name', 'Image Path', 'RunAsUser', 'Installed By', Suspicious | Export-Csv -Path test.csv -NoTypeInformation
I read the Export-CSV documentation on MS. Searched StackOverFlow for some tips, I think it has something to do with PS checking the first Row and then compares if the property exists for the second row and so on.
Thank you
The issue you're experiencing is partially because of how objects are displayed to the console, the first object's Properties determines the displayed Properties (Columns) to the console.
The bigger problem though, is that Export-Csv will not export those properties that do not match with first object's properties unless they're explicitly added to the remaining objects or the objects are reconstructed, for this one easy way is to use Select-Object as you have pointed out in the question.
Given the following example:
$test = #(
[pscustomobject]#{
A = 'ValA'
}
[pscustomobject]#{
A = 'ValA'
B = 'ValB'
}
[pscustomobject]#{
C = 'ValC'
D = 'ValD'
E = 'ValE'
}
)
Format-Table will not display the properties B to E:
$test | Format-Table
A
-
ValA
ValA
Format-List can display the objects properly, this is because each property with it's corresponding value has it's own console line in the display:
PS /> $test | Format-List
A : ValA
A : ValA
B : ValB
C : ValC
D : ValD
E : ValE
Export-Csv and ConvertTo-Csv will also miss properties B to E:
$test | ConvertTo-Csv
"A"
"ValA"
"ValA"
You have different options as a workaround for this, you could either add the Suspicious property to all objects and for those events that are not suspicious you could add $null as Value.
Another workaround is to use Select-Object explicitly calling the Suspicious property (this works because you know the property is there and you know it's Name).
If you did not know how many properties your objects had, a dynamic way to solve this would be to discover their properties using the PSObject intrinsic member.
using namespace System.Collections.Generic
function ConvertTo-NormalizedObject {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline, Mandatory)]
[object[]] $InputObject
)
begin {
$list = [List[object]]::new()
$props = [HashSet[string]]::new([StringComparer]::InvariantCultureIgnoreCase)
}
process {
foreach($object in $InputObject) {
$list.Add($object)
foreach($property in $object.PSObject.Properties) {
$null = $props.Add($property.Name)
}
}
}
end {
$list | Select-Object ([object[]] $props)
}
}
Usage:
# From Pipeline
$test | ConvertTo-NormalizedObject | Format-Table
# From Positional / Named parameter binding
ConvertTo-NormalizedObject $test | Format-Table
Lastly, a pretty easy way of doing it thanks to Select-Object -Unique:
$prop = $test.ForEach{ $_.PSObject.Properties.Name } | Select-Object -Unique
$test | Select-Object $prop
Using $test for this example, the result would become:
A B C D E
- - - - -
ValA
ValA ValB
ValC ValD ValE
Continuing from my previous answer, you can add a column Suspicious straight away if you take out the Where-Object filter and simply add another calculated property to the Select-Object cmdlet:
# create a regex for the suspicious executables:
$sus = '(powershell|cmd|psexesvc)\.exe'
# alternatively you can join the array items like this:
# $sus = ('powershell.exe','cmd.exe','psexesvc.exe' | ForEach-Object {[regex]::Escape($_)}) -join '|'
$7045 = Get-WinEvent -FilterHashtable #{ LogName = 'System';Id = 7045 } |
Select-Object Id,
#{N='Timestamp';E={$_.TimeCreated.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')}},
#{N='Machine Name';E={$_.MachineName}},
#{N='Service Name'; E={$_.Properties[0].Value}},
#{N='Image Path'; E={$_.Properties[1].Value}},
#{N='RunAsUser'; E={$_.Properties[4].Value}},
#{N='Installed By'; E={$_.UserId}},
#{N='Suspicious'; E={
if ($_.Properties[1].Value -match $sus) { 'Yes' } else {'No'}
}}
$7045 | Export-Csv -Path 'X:\Services.csv' -UseCulture -NoTypeInformation
Because you have many columns, this will not fit the console width anymore if you do $7045 | Format-Table, but the CSV file will hold all columns you wanted.
I added switch -UseCulture to the Export-Csv cmdlet, which makes sure you can simply double-click the csv file so it opens correctly in your Excel.
As sidenote: Please do not use those curly so-called 'smart-quotes' in code as they may lead to unforeseen errors. Straighten these ’ thingies and use normal double or single quotes (" and ')

Get mapped network drives labels

Is there a way to get mapped network drives labels?
I know it's possible to get multiple properties through the
Get-Object Win32_MappedLogicalDisk
But none of them are labels (please do not misunderstand, I do not want Name i.e. K:, I want labels i.e. My Network drive)
You could use the Com Shell.Application object for this:
$shell = New-Object -ComObject Shell.Application
(Get-WmiObject -Class Win32_MappedLogicalDisk).DeviceID |
# or (Get-CimInstance -ClassName Win32_MappedLogicalDisk).DeviceID |
# or ([System.IO.DriveInfo]::GetDrives() | Where-Object { $_.DriveType -eq 'Network' }).Name |
Select-Object #{Name = 'Drive'; Expression = {$_}},
#{Name = 'Label'; Expression = {$shell.NameSpace("$_").Self.Name.Split("(")[0].Trim()}}
# when done, clear the com object from memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Output:
Drive Label
----- -----
X: MyCode
Some explanation for the above:
Using the COM object Shell.Application, you can drill down through its properties and methods.
.NameSpace create and return a Folder object for the specified folder
.Self gets a Read-Only duplicate System.Shell.Folder object
.Name from that we take the Name property like 'MyCode (X:)'
.Split this name we split on the opening bracket '(',
[0] take the first part of the splitted name and
.Trim() get rid of any extraneous whitespace characters
Another way is to go into the registry, but remember that after a mapped network folder is unmapped, the old registry value remains.
This is why below code still uses one of two methods to find active network mappings first:
# the registry key to search in
$regKey = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2'
# list the mapped network drives and loop through
# you can also use Get-CimInstance -ClassName Win32_MappedLogicalDisk
Get-WmiObject -Class Win32_MappedLogicalDisk | ForEach-Object {
# create the full registry key by replacing the backslashes in the network path with hash-symbols
$key = Join-Path -Path $regKey -ChildPath ($_.ProviderName -replace '\\', '#')
# return an object with the drive name (like 'X:') and the Label the user gave it
[PsCustomObject]#{
Drive = $_.DeviceID
Label = Get-ItemPropertyValue -Path $key -Name '_LabelFromReg' -ErrorAction SilentlyContinue
}
}
Output here also:
Drive Label
----- -----
X: MyCode
I am not aware of a cmdlet that will give you that info. I believe you can find it by looking at the registry with gci, but you would need to cleanup the output.
get-childitem "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2"

Selecting the TypeName of an Object in Powershell

I am working on putting together a report for monitoring the ACLs for a series of data shares and when I run my script I get the results seen below in my screenshot. As you can see, Path: \\rest_of_path is displayed above each object.
This looks like when I use Get-Member, TypeName: is shown in that position. I want to be able to take that Path value and add it to my report so that I can produce something that looks like the output within the PowerShell console. How can I do that?
Here is the code: (I'm using the NTFSSecurity module as seen here, https://blogs.technet.microsoft.com/heyscriptingguy/2014/11/23/weekend-scripter-manage-ntfs-inheritance-and-use-privileges/)
import-module -Name \\storagesrvr\it\!scripts\ntfssecurity -verbose
$shares = get-content \\testserver\c$\tmp\share.list.txt
$results = #()
foreach($share in $shares){
$ntfs = Get-NTFSAccess $share
$results += $ntfs
}
Looks like Path is the formatted combination from FullName and InheritanceEnabled
$results | ForEach-Object {
$_ | Select-Object #{
Name="Path"
Expression={"$($_.Fullname) $(if(!($_.InheritanceEnabled)) {'(Inheritance Disabled)'})"}
}
}
Or to put that calculated property directly into $results
import-module -Name \\storagesrvr\it\!scripts\ntfssecurity -verbose
$shares = get-content \\testserver\c$\tmp\share.list.txt
$results = foreach($share in $shares){
$ntfs = Get-NTFSAccess $share |
select *,#{n="Path";e={"$($_.Fullname) $(if(($_.InheritanceEnabled)) {'(Inheritance Disabled)'})"}}
}

Out-file format

I am writing a script that after each iteration through a loop (array of selected services) it will gather the 4 values for each service that are: server name, service name, service state, and service start name
So for each iteration, I would like to output the 4 mentioned values to an external file (txt, svc, or html) such that each value will be arranged in its own column. Currently I use tab `t to arrange the values in each column but it doesn't work quite well because some service name is a lot longer or a lot shorter so it screws up the column alignment. What other approach do you suggest so all columns are aligned properly
Below is a snippet of my script on how I currently format the output to a txt file
ForEach($service in services)
$startname = $service.startname
$state = $service.state
$servicename = $service.name
write-output "$server `t $servicename `t $state `t $startname is current" | out-file -append $ScriptDirectory
If you just want to dump the results to text in a nicely-formatted way (i.e. you don't have requirements for making this CSV, or tab-delimited, or anything else besides "easy for a person to read"), then just use Format-Table -AutoSize.
AutoSize does exactly what you want - it inspects the length of all properties you are outputting, then dynamically adjusts the column width so that as much as possible is shown.
You don't explain where $server comes from, I will assume that is defined somewhere else...
$services `
| Format-Table -AutoSize #{N='Server';E={$server}},StartName,State,Name `
| Out-String `
| Out-File results.txt
Instead of using several variables, use a Powershell object to store your output. Something like this:
ForEach($service in $services) {
New-Object PSObject -Property #{
StartName = $service.startname
State = $service.state
ServiceName = $service.name
}
} | Out-File $ScriptDirectory
You may need to add a Select-Object in the chain to ensure the columns are in the correct order that you want for your final output.
If you want to keep the variables, You could try the following String formatting to space out the variable in the string evenly. In the example below the spacing is 20 characters between each value:
ForEach($service in services){
$startname = $service.startname
$state = $service.state
$servicename = $service.name
"{0,-20} | {1,-20} | {2,-20} | {3,-20}" -f $server,$servicename,$state,$startname `
| Out-File -append $ScriptDirectory
}
It's a little unclear what you're looking for as some of the properties of the object Get-Service returns don't exist as written and the code seems incomplete. Taking a guess at your intent though:
$servers = #("server1","server2");
$services = get-service -computername $servers;
$svcCollection = #();
ForEach($service in $services) {
$svccollection+=New-Object PSObject -Property #{
Servername = $service.MachineName;
StartName = $service.servicename;
State = $service.Status;
ServiceName = $service.DisplayName;
}
}
# Various output formats
$svccollection|ConvertTo-Html|Out-File -path Services.html; # Create a full HTML file
$svcCollection|Export-Csv -NoTypeInformation -Path Services.csv; # Create a "traditional" CSV file
$svcCollection|Export-Csv -Delimiter "`t" -Path Services-tab.csv; # Create a tab-delimited CSV file
$svcCollection|ConvertTo-Xml|Out-File -path Services.xml; # Create an XML file
$svcCollection|ConvertTo-Json|Out-File -path Services.js; # Create a JSON object (v3 only)

Convert GUID string to octetBytes using PowerShell

I have a powershell script which outputs all Exchange 2003 mailboxes by size.
$computers = "vexch01","vexch02"
foreach ($computer in $computers) {
Get-Wmiobject -namespace root\MicrosoftExchangeV2 -class Exchange_Mailbox -computer $computer | sort-object -desc Size | select-object MailboxDisplayName,StoreName,#{Name="Size/Mb";Expression={[math]::round(($_.Size / 1024),2)}}, MailboxGUID | Export-Csv -notype -Path $computer.csv
}
Currently this outputs the MailboxGUID as a string type GUID (e.g. {21EC2020-3AEA-1069-A2DD-08002B30309D}). I want to look up users in AD by this, but AD stores them in octetBytes format.
I have found some powershell functions which will do the conversion but only when the curly braces are removed. The Guid.ToString method should supply this, but I can't get it to work in the above.
However, if I could figure out how to do that, the Guid.ToByteArray method might get me even closer.
Has anyone cracked this?
Update: the answers so far helped me write a function that converts the mailboxguid into the correct format for searching via LDAP. However, I now cannot get this working in the script. This is my updated script:
function ConvertGuidToLdapSearchString(
[parameter(mandatory=$true, position=0)]$Guid
)
{
$guid_object = [System.Guid]$Guid
($guid_object.ToByteArray() | foreach { '\' + $_.ToString('x2') }) -join ''
}
# Gets data through WMI from specified Exchange mailbox servers
$servers = "vexch01","vexch02"
foreach ($server in $servers) {
Get-Wmiobject -namespace root\MicrosoftExchangeV2 -class Exchange_Mailbox -computer $computer | sort-object -desc Size | select-object MailboxDisplayName,StoreName,#{Name="Size/Mb";Expression={[math]::round(($_.Size / 1024),2)}}, #{Name="LDAP Guid";Expression={ConvertGuidToLdapSearchString(MailboxGUID)}} | Export-Csv -notype -Path $server.csv
}
I'm not sure why using the function in the select-object with #{Name="LDAP Guid";Expression={ConvertGuidToLdapSearchString(MailboxGUID)}} doesn't work.
Is there another way of using this function in select-object that will give the string?
In conjunction with Andy Schneider's answer, you may find this function useful:
function Convert-GuidToLdapSearchString(
[parameter(mandatory=$true, position=0)][guid]$Guid
)
{
($Guid.ToByteArray() | foreach { '\' + $_.ToString('x2') }) -join ''
}
(I thought I had a more clever way to do this by adding a ScriptProperty to System.Guid, but I seem to have learned that you can't effectively add members to structs.)
I'm not sure I understand what you are trying to accomplish based on your comment, but I think you may have just left out a $_. Here is a somewhat contrived example that creates an object with a property that is a GUID, then uses select and Convert-GuidToLdapSearchString to convert the format. I hope it helps.
$o = New-Object PSObject -Property #{ GUID = $([Guid]::NewGuid()) }
$o
$o | select #{ Name='SearchString'; Expression={ Convert-GuidToLdapSearchString $_.GUID } }
This is not at all how I had imagined the function being used. I expected you would use it to create an LDAP search clause such as:
$searchString = Convert-GuidToLdapSearchString '{9e76c48b-e764-4f0c-8857-77659108a41e}'
$searcher = [adsisearcher]"(msExchMailboxGuid=$searchString)"
$searcher.FindAll()
Are you casting the string to a GUID ?
$guid = [System.Guid]"{21EC2020-3AEA-1069-A2DD-08002B30309D}"
$guid.ToString()
$guid.ToByteArray()