Get PSObject array size or count - powershell

I create an array like this:
$Array = #()
$Item = New-Object PSObject
$Item | Add-Member -Type NoteProperty -Name item1 -Value test
$Item | Add-Member -Type NoteProperty -Name item2 -Value test
$Array += $Item
Now I want to add a check to determine if $Item is empty before adding it in $Array. How can I get the member count of $Item ?
I tried stuff like :
$Item.count
$Item.length
#($Item).count
($Item | Measure).count
($Item | Get-Member).count
$Item.psobject.members.count
But none of them gives me the actual member count.

You can use the hidden .PsObject.Properties to either check for
$Item.PSobject.Properties.Value.count or
$Item.PSobject.Properties.Names.count
$Item = New-Object PSObject
$Item.Psobject.Properties.value.count
0
$Item | Add-Member -Type NoteProperty -Name item1 -Value test
$Item.Psobject.Properties.value.count
1
$Item | Add-Member -Type NoteProperty -Name item2 -Value test
$Item.Psobject.Properties.value.count
2

The correct way is:
($Item|Get-Member -Type NoteProperty).count

The following Get_ItemCount function could help:
Function Get_ItemCount {
$aux = $($item | Get-Member -MemberType NoteProperty)
if ( $aux -eq $null ) {
0
} elseif ( $aux -is [PSCustomObject] ) {
1
} else {
$aux.Count
}
}
$Item = New-Object PSObject
Get_ItemCount # 0
$Item | Add-Member -Type NoteProperty -Name item1 -Value test
Get_ItemCount # 1
$Item | Add-Member -Type NoteProperty -Name item2 -Value test
Get_ItemCount # 2
Output
PS D:\PShell> .\SO\55064810.ps1
0
1
2
PS D:\PShell>

Related

Summing an array of Objects in Powershell

I have an array of objects that are holding integer values.
$row = new-Object PSObject # create a new object to hold its data
$row | Add-Member -Name "sheet_number" -MemberType NoteProperty -Value 1
$row | Add-Member -Name "frame_number" -MemberType NoteProperty -Value 2
$row | Add-Member -Name "sheet_height" -MemberType NoteProperty -Value 1200
$row | Add-Member -Name "frame_height" -MemberType NoteProperty -Value 1200
$row | Add-Member -Name "frame_width" -MemberType NoteProperty -Value 3300
$row | Add-Member -Name "orientation" -MemberType NoteProperty -Value 0
$frames += $row
this is in a for loop intended to iterate through several times. But the sheet_number property should only have a couple values. what I need is to sum up the values in frame_width where the sheet_number is the same.
Pseudo Code:
sheet_width = sum of frame_width where sheet number = 1
Use a combination of Where-Object, ForEach-Object, and Measure-Object:
$sum = (
$frames |
Where-Object sheet_number -eq 1 |
ForEach-Object frame_width |
Measure-Object -Sum
).Sum
To do it for all sheet numbers, additionally use Group-Object:
$arrayOfSums =
$frames |
Group-Object sheet_number |
ForEach-Object {
($_.Group.frame_width | Measure-Object -Sum).Sum
}

Export list/array to CSV in Powershell

done some googling but answers I have found seem to be more complex than what I need. I have a simple script to fetch DNS cache entries, and I'd like to export the results to a CSV in the most "powershell" manner. Code looks like this:
function Get-Dns
{
$domains = #()
$cmdOutput = Invoke-Command -ScriptBlock {ipconfig /displaydns}
ForEach ($line in $($cmdOutput -split "`r`n"))
{
if ($line -like '*Record Name*'){
$domain = $line -split ":"
$domains += $domain[1]
}
}
so I have an array, $domains, which I would like to use Export-CSV to essentially output a one column CSV with one domain per line. Using Export-CSV seems to just output the length of each element rather than the contents itself. Any help is appreciated!
The most PowerShell way:
(ipconfig /displaydns|where{$_-match'Record Name'})|%{$_.split(":")[1].Trim()}>dnscache.txt
"ipconfig /displaydns" is going to give you back a big'ol string array, which is going to be harder to work with. Try the native commandlets for DNS manipulation:
Get-DnsClientCache | Export-Csv -Path .\stuff.csv
If you're using Windows 7 or earlier, try this...
$dns_client_cache = #()
$raw_dns_data = ipconfig /displaydns
for ($element = 3; $element -le $raw_dns_data.length - 3; $element++) {
if ( $raw_dns_data[$element].IndexOf('Record Name') -gt 0 ) {
if ( $dns_entry ) { $dns_client_cache += $dns_entry }
$dns_entry = New-Object -TypeName PSObject
Add-Member -InputObject $dns_entry -MemberType NoteProperty -Name 'RecordName' -Value $raw_dns_data[$element].Split(':')[1].Trim()
} elseif ( $raw_dns_data[$element].IndexOf('Record Type') -gt 0 ) {
Add-Member -InputObject $dns_entry -MemberType NoteProperty -Name 'RecordType' -Value $raw_dns_data[$element].Split(':')[1].Trim()
} elseif ( $raw_dns_data[$element].IndexOf('Time To Live') -gt 0 ) {
Add-Member -InputObject $dns_entry -MemberType NoteProperty -Name 'TimeToLive' -Value $raw_dns_data[$element].Split(':')[1].Trim()
} elseif ( $raw_dns_data[$element].IndexOf('Data Length') -gt 0 ) {
Add-Member -InputObject $dns_entry -MemberType NoteProperty -Name 'DataLength' -Value $raw_dns_data[$element].Split(':')[1].Trim()
} elseif ( $raw_dns_data[$element].IndexOf('Section') -gt 0 ) {
Add-Member -InputObject $dns_entry -MemberType NoteProperty -Name 'Section' -Value $raw_dns_data[$element].Split(':')[1].Trim()
} elseif ( $raw_dns_data[$element].IndexOf('CNAME Record') -gt 0 ) {
Add-Member -InputObject $dns_entry -MemberType NoteProperty -Name 'CNAMERecord' -Value $raw_dns_data[$element].Split(':')[1].Trim()
}
}
$dns_client_cache | Export-Csv -Path .\dns_stuff.csv -Force -NoTypeInformation
Sorry! I know it's messy.
I ended up going with to export multiple value array to csv
$Data | %{$_} | export-csv -nti -Path C:\

Copy entire list using Powershell CSOM sharepoint

I need to export an entire list as a .csv file. I actually have this code which works great but I need to write each column I want to export:
$listTitle = "Example"
$list = $ctx.get_web().get_lists().getByTitle($listTitle);
$query = New-Object Microsoft.SharePoint.Client.CamlQuery;
$query.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID' /><Value Type='Counter'>1</Value></Geq></Where></Query></View>"
$listItems = $list.GetItems($query);
$ctx.Load($listItems);
$ctx.ExecuteQuery();
$tableau =#();
foreach ($listItem in $listItems)
{
$result = new-object psobject
$result | Add-Member -MemberType noteproperty -Name Title -value $listItem['Title'];
$result | Add-Member -MemberType noteproperty -Name Description -value $listItem['Description'];
$result | Add-Member -MemberType noteproperty -Name Age -value $listItem['Age'];
$result | Add-Member -MemberType noteproperty -Name Sexe -value $listItem['Sexe'];
$tableau += $result;
}
$CsvName2 = "Export_"+$ListTitle.replace(' ','_')+".csv"
$tableau | export-csv $CsvName2 -notype;
The part I want to improve is the foreach loop:
foreach ($listItem in $listItems)
{
$result = new-object psobject
$result | Add-Member -MemberType noteproperty -Name Title -value $listItem['Title'];
$result | Add-Member -MemberType noteproperty -Name Description -value $listItem['Description'];
$result | Add-Member -MemberType noteproperty -Name Age -value $listItem['Age'];
$result | Add-Member -MemberType noteproperty -Name Sexe -value $listItem['Sexe'];
$tableau += $result;
}
I want the script collects all columns but I don't know how to do it...
I got this advice: Replace my loop with:
foreach ($listItem in $listItems)
{
$result = new-object psobject
foreach ($field in $listItem.Fields)
{
if ($field.Hidden -eq $false)
{
$result | Add-Member -MemberType noteproperty -Name $field.Title -value $listItem[$field.InternalName];
}
}
$tableau += $result;
}
But all I got is a blank file. I don't really understand structure of list/filed items.
Thanks for your help.

PSObject & sorting

the file ip.txt a list of IP adress
function CreateObj
{
param([string]$IP,[string]$class,[int]$number)
$Obj=New-Object PSObject
$Obj | Add-Member -Name IP -MemberType NoteProperty -Value $IP
$Obj | Add-Member -Name CLASS -MemberType NoteProperty -Value $Class
$Obj | Add-Member -Name NUMBER -MemberType NoteProperty -Value $number
return $Obj
}
$allip = get-content ip.txt
$tab=#()
foreach ($item in $allip)
{
$class = $item.substring(0,$item.lastindexof("."))
$number = [int]($item.substring($item.lastindexof(".")+1))
$tab += createobj $item $Class $number
}
$tab | sort |get-unique # <-- this fail problem of type i think ?
$tab | sort |get-unique # <-- this fail... problem of type ?
thanks
you should use the -unique parameter of sort-object cmdlet :
$tab | sort IP -unique

No way to export tables in PowerShell?

OK, everything about PowerShell has been fantastic so far, but for something that is so great they sure made exporting results to files complicated as hell. Anyway, how can I get the Export $Results variable to a deliminated file so it can be imported to Excel?
Final script
[cmdletbinding()]
[cmdletbinding()]
param(
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName = "HellBombs-PC"
)
begin {
$UninstallRegKey="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
}
process {
foreach($Computer in $ComputerName) {
Write-Verbose "Working on $Computer"
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$HKLM = [microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine',$computer)
$UninstallRef = $HKLM.OpenSubKey($UninstallRegKey)
$Applications = $UninstallRef.GetSubKeyNames()
foreach ($App in $Applications) {
$AppRegistryKey = $UninstallRegKey + "\\" + $App
$AppDetails = $HKLM.OpenSubKey($AppRegistryKey)
$AppGUID = $App
$AppDisplayName = $($AppDetails.GetValue("DisplayName"))
$AppVersion = $($AppDetails.GetValue("DisplayVersion"))
$AppPublisher = $($AppDetails.GetValue("Publisher"))
$AppInstalledDate = $($AppDetails.GetValue("InstallDate"))
$AppUninstall = $($AppDetails.GetValue("UninstallString"))
if(!$AppDisplayName) {
continue
}
$OutputObj = New-Object -TypeName PSobject
$OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
$OutputObj | Add-Member -MemberType NoteProperty -Name AppName -Value $AppDisplayName
$OutputObj | Add-Member -MemberType NoteProperty -Name AppVersion -Value $AppVersion
$OutputObj | Add-Member -MemberType NoteProperty -Name AppVendor -Value $AppPublisher
$OutputObj | Add-Member -MemberType NoteProperty -Name InstalledDate -Value $AppInstalledDate
$OutputObj | Add-Member -MemberType NoteProperty -Name UninstallKey -Value $AppUninstall
$OutputObj | Add-Member -MemberType NoteProperty -Name AppGUID -Value $AppGUID
$Result += #($OutputObj)
}
}
}
$Result | select -Property * | export-csv -notypeinformation -path Info.txt
}
end {}
Use export-csv.
Try:
$Result | select -Property * | export-csv -notypeinformation -append -path .\test.txt