No way to export tables in PowerShell? - 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

Related

If Else Loop not working in Powershell Inventory Script

Note – I am not a coding expert so please be gentle 😊 Any assistance/guidance much appreciated
Issue is that my pieced together Powershell script is not working as correctly. I am guessing it will take a coding guru two seconds to help resolve.
The basics of the script is that it performs a basic audit of a list of servers from a text file and outputs the results to a csv. For each server it will test WMI connection and if successful will collect columns of data i.e Name, IP Address, Uptime etc. If WMI connection fails then it should just log a few columns of data i.e. WMI Result, Ping Result etc All results should be piped to the same single output csv
The script works perfectly if the first server in the list’s WMI connection succeeds. All 16 x columns of csv output file are populated for every server in list.
WorkingExample
If the first server in the list’s WMI connection fails then the output fails. Only 4 x columns of csv output file are populated for every server in list.
FailingExample
Hopefully the screenshots of the output csv's help
Powershell Code below
<#
.DESCRIPTION - Auditing Script - Construction Phase !!!
- Create folder called 'Audit' under C:\Temp
- Create text file called 'Servers.txt' and place in newly created C:\Temp\Audit folder
- Servers.txt should contain a list of server names you wish to audit\target
.Author MCD
#>
########## Output Folder ##########
$outputFolderName = 'Audit ' + $(Get-Date -f dd-MM-yyyy)
$outputpath = "C:\temp\Audit\$outputFolderName"
If(!(test-path $outputpath))
{
New-Item -ItemType Directory -Force -Path $outputpath | out-null
}
########## Prompt 1 ##########
Add-Type -AssemblyName Microsoft.VisualBasic
$ClientName = [Microsoft.VisualBasic.Interaction]::InputBox('Please enter Client\Customer name i.e. Contoso Ltd', 'User')
Start-Sleep -s 2
#Manual Input File Location
$computers = Get-Content -path c:\temp\audit\Servers.txt
########## Create an Empty Array ##########
$report = #()
########## Main Start ##########
Foreach ($Computer in $Computers)
{
########## WMI/Ping Test ##########
$wmi = gwmi win32_bios -ComputerName $computer -ErrorAction SilentlyContinue
$Ping = Test-Connection -ComputerName $computer -Quiet -count 2
########## Main If Else Loop ##########
if ($wmi)
{
$WMIResult = 'Server IS Contactable'
########## HW/Serial No/Bios ##########
$Bios = Get-WmiObject -Class win32_bios -ComputerName $Computer
$systemBios = $Bios.serialnumber
$Hardware = Get-WmiObject -Class Win32_computerSystem -ComputerName $Computer
########## OS Version/Last Reboot ##########
$OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
$lastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
$uptimeDays = ((get-date) - ($os.ConvertToDateTime($os.lastbootuptime))).Days
########## Network Info ##########
$Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $Computer | Where-Object {$_.IPEnabled}
$IPAddress = ($Networks.IpAddress | where {$_ -notmatch ":"}) -join "`n"
$MACAddress = ($Networks.MACAddress) -join "`n"
$IpSubnet = ($Networks.IpSubnet | ? { $_ -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' }) -join "`n"
$DefaultGateway = ($Networks.DefaultIPGateway) -join "`n"
########## LastLogon/Created ##########
$LastLogonDate = Get-ADComputer $computer -Properties * | select -ExpandProperty LastLogonDate
$Created = Get-ADComputer $computer -Properties * | select -ExpandProperty Created
########## OUTPUT ##########
$tempreport = New-Object -TypeName PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$tempreport | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $Hardware.Manufacturer
$tempreport | Add-Member -MemberType NoteProperty -Name Model -Value $Hardware.Model
$tempreport | Add-Member -MemberType NoteProperty -Name Operating_System -Value $OS.Caption
$tempreport | Add-Member -MemberType NoteProperty -Name IP_Address -Value $IPAddress
$tempreport | Add-Member -MemberType NoteProperty -Name Default_Gateway -Value $DefaultGateway
$tempreport | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $MACAddress
$tempreport | Add-Member -MemberType NoteProperty -Name IpSubnet -Value $IpSubnet
$tempreport | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $lastboot
$tempreport | Add-Member -MemberType NoteProperty -Name Uptime_Days -Value $uptimeDays
$tempreport | Add-Member -MemberType NoteProperty -Name Last_Logon -Value $LastLogonDate
$tempreport | Add-Member -MemberType NoteProperty -Name Created -Value $Created
$tempreport | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $systemBios
$report += $tempreport
} else {
$WMIResult = 'Server NOT Contactable'
$tempreport = New-Object PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$report += $tempreport
}
}
########## EXPORT TO CSV ##########
$CSVFileName = $ClientName + ' Server Inventory ' + $(Get-Date -f dd-MM-yyyy) + '.csv'
$report | Export-Csv "$outputpath\$CSVFileName" -NoTypeInformation
<#
.END
#>
The issue is that the two objects you are creating don't contain the same properties. Arrays will report the information based on the properties in the first object. So if the first object fails, then all the others will report back the same four properties when the array is output.
My suggestion for dealing with this in the most simple way is to add the additional properties to the failing object, setting the values as $null. This should see that your CSV receives all the properties as intended.
<#
.DESCRIPTION - Auditing Script - Construction Phase !!!
- Create folder called 'Audit' under C:\Temp
- Create text file called 'Servers.txt' and place in newly created C:\Temp\Audit folder
- Servers.txt should contain a list of server names you wish to audit\target
.Author MCD
#>
########## Output Folder ##########
$outputFolderName = 'Audit ' + $(Get-Date -f dd-MM-yyyy)
$outputpath = "C:\temp\Audit\$outputFolderName"
If(!(test-path $outputpath)) {
New-Item -ItemType Directory -Force -Path $outputpath | out-null
}
########## Prompt 1 ##########
Add-Type -AssemblyName Microsoft.VisualBasic
$ClientName = [Microsoft.VisualBasic.Interaction]::InputBox('Please enter Client\Customer name i.e. Contoso Ltd', 'User')
Start-Sleep -s 2
#Manual Input File Location
$computers = Get-Content -path c:\temp\audit\Servers.txt
########## Create an Empty Array ##########
$report = #()
########## Main Start ##########
Foreach ($Computer in $Computers) {
########## WMI/Ping Test ##########
$wmi = gwmi win32_bios -ComputerName $computer -ErrorAction SilentlyContinue
$Ping = Test-Connection -ComputerName $computer -Quiet -count 2
########## Main If Else Loop ##########
if ($wmi) {
$WMIResult = 'Server IS Contactable'
########## HW/Serial No/Bios ##########
$Bios = Get-WmiObject -Class win32_bios -ComputerName $Computer
$systemBios = $Bios.serialnumber
$Hardware = Get-WmiObject -Class Win32_computerSystem -ComputerName $Computer
########## OS Version/Last Reboot ##########
$OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
$lastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
$uptimeDays = ((get-date) - ($os.ConvertToDateTime($os.lastbootuptime))).Days
########## Network Info ##########
$Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $Computer | Where-Object {$_.IPEnabled}
$IPAddress = ($Networks.IpAddress | where {$_ -notmatch ":"}) -join "`n"
$MACAddress = ($Networks.MACAddress) -join "`n"
$IpSubnet = ($Networks.IpSubnet | ? { $_ -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' }) -join "`n"
$DefaultGateway = ($Networks.DefaultIPGateway) -join "`n"
########## LastLogon/Created ##########
$LastLogonDate = Get-ADComputer $computer -Properties * | select -ExpandProperty LastLogonDate
$Created = Get-ADComputer $computer -Properties * | select -ExpandProperty Created
########## OUTPUT ##########
$tempreport = New-Object -TypeName PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$tempreport | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $Hardware.Manufacturer
$tempreport | Add-Member -MemberType NoteProperty -Name Model -Value $Hardware.Model
$tempreport | Add-Member -MemberType NoteProperty -Name Operating_System -Value $OS.Caption
$tempreport | Add-Member -MemberType NoteProperty -Name IP_Address -Value $IPAddress
$tempreport | Add-Member -MemberType NoteProperty -Name Default_Gateway -Value $DefaultGateway
$tempreport | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $MACAddress
$tempreport | Add-Member -MemberType NoteProperty -Name IpSubnet -Value $IpSubnet
$tempreport | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $lastboot
$tempreport | Add-Member -MemberType NoteProperty -Name Uptime_Days -Value $uptimeDays
$tempreport | Add-Member -MemberType NoteProperty -Name Last_Logon -Value $LastLogonDate
$tempreport | Add-Member -MemberType NoteProperty -Name Created -Value $Created
$tempreport | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $systemBios
$report += $tempreport
}
else {
$WMIResult = 'Server NOT Contactable'
$tempreport = New-Object PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$tempreport | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Model -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Operating_System -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name IP_Address -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Default_Gateway -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name IpSubnet -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Uptime_Days -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Last_Logon -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Created -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $null
$report += $tempreport
}
}
########## EXPORT TO CSV ##########
$CSVFileName = $ClientName + ' Server Inventory ' + $(Get-Date -f dd-MM-yyyy) + '.csv'
$report | Export-Csv "$outputpath\$CSVFileName" -NoTypeInformation

I want this powershell script output in special pop window?

Below code was in powershell that code is successfully executed but i want that output in special 'popup window'
$ComputerName = $s = $(Get-WmiObject Win32_Computersystem).name
foreach ($Computer in $ComputerName) {
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled}
foreach ($Network in $Networks) {
$IPAddress = $Network.IpAddress[0]
$SubnetMask = $Network.IPSubnet[0]
$DefaultGateway = $Network.DefaultIPGateway
$DNSServers = $Network.DNSServerSearchOrder
$OutputObj = New-Object -Type PSObject
$OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress
$OutputObj | Add-Member -MemberType NoteProperty -Name SubnetMask -Value $SubnetMask
$OutputObj | Add-Member -MemberType NoteProperty -Name Gateway -Value $DefaultGateway
$OutputObj | Add-Member -MemberType NoteProperty -Name DNSServers -Value $DNSServers
}
}
}
The most familiar data displayer in powershell is using the Out-gridview method:
You can do this if you want to go easy:
$ComputerName = $s = $(Get-WmiObject Win32_Computersystem).name
$Pop_Window = foreach ($Computer in $ComputerName) {
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled}
foreach ($Network in $Networks) {
$IPAddress = $Network.IpAddress[0]
$SubnetMask = $Network.IPSubnet[0]
$DefaultGateway = $Network.DefaultIPGateway
$DNSServers = $Network.DNSServerSearchOrder
$OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress
$OutputObj | Add-Member -MemberType NoteProperty -Name SubnetMask -Value $SubnetMask
$OutputObj | Add-Member -MemberType NoteProperty -Name Gateway -Value $DefaultGateway
$OutputObj | Add-Member -MemberType NoteProperty -Name DNSServers -Value $DNSServers
#output the object:
$OutputObj
}
}
}
$Pop_Window | Out-GridView
If you want to design it on your way, This would be a difficult and a messy task to do in powershell, since you always will have to call System.Windows.Forms class and its sub classes like Labels,Buttons,Texts and more.

Issue with foreach loop (Combining Commands)

The script below works out great for identifying licensing for each individual host across multiple vCenters. What I am trying to include is the tag for each host as well. When I run the command individually it works fine, however when I run it as part of the code it is not functioning correctly. I highlighted the section if anyone can please take a look thanks. The line of code with the issue is commented out within the script below.
I attempted pushing this into a variable outside and insideof the foreach loop but I am receiving either 0 output, or the same output across each object.
Below is the actual command I put inside the foreach loop which is not functional.
(Get-VMhost | where{$_.Category -like "*Host*"})
$sw = [Diagnostics.Stopwatch]::StartNew()
# Declare our list of vCenters
[array]$vclistall = "vcenter01"
# Ensure were not connected to any vcenters
if ($DefaultVIServer.Count -gt 0) {
Disconnect-VIServer * -Confirm:$false -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Force:$true > $null
}
[array]$report = $null
foreach ($ScriptVCInstance in $vclistall) {
$connection = Connect-VIServer $ScriptVCInstance -ErrorAction SilentlyContinue
if ($connection) {
Write-Host "Collecting License Assets on vCenter $($ScriptVCInstance)"
# Get the license manager assets
$LicenseManager = Get-view LicenseManager
$LicenseAssignmentManager = Get-View $LicenseManager.LicenseAssignmentManager
$licenses = $LicenseAssignmentManager.GetType().GetMethod("QueryAssignedLicenses").Invoke($LicenseAssignmentManager, #($null))
#Format the asset into an object
foreach ($license in $Licenses) {
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name "vCenter" -Value $($connection.name)
$object | Add-Member -MemberType NoteProperty -Name "Entity" -Value $($license.EntityDisplayName)
$object | Add-Member -MemberType NoteProperty -Name "Display Name" -Value $($license.Properties | where{$_.Key -eq 'ProductName'} | select -ExpandProperty Value)
$object | Add-Member -MemberType NoteProperty -Name "Product Version" -Calue $($License.Properties | where{$_.Key -eq 'FileVersion'} | select -ExpandProperty Value)
$object | Add-Member -MemberType NoteProperty -Name "License" -Value $($license.AssignedLicense.LicenseKey)
$object | Add-Member -MemberType NoteProperty -Name "License Name" -Value $($license.AssignedLicense.Name)
$object | Add-Member -MemberType NoteProperty -Name "Cost Unit" -Value $($license.Properties | where{$_.Key -eq 'CostUnit'} | select -ExpandProperty Value)
$object | Add-Member -MemberType NoteProperty -Name "Used License" -Value $($license.Properties | where{$_.Key -eq 'EntityCost'} | select -ExpandProperty Value)
$object | Add-Member -MemberType NoteProperty -Name "Total Licenses" -Value $($license.AssignedLicense.Total)
# Issue--> $object | Add-Member -MemberType NoteProperty -Name "Tag" -Value $(Get-VMhost | where{$_.Category -like "*Host*"})
$report += $object
if ($DefaultVIServer.Count -gt 0) {
Disconnect-VIServer * -Confirm:$false -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Force:$true > $null
}
} #end foreach $license
} else { # Else for if $connection
Write-warning "Not connected to vCenter $($ScriptVCInstance)"
} # endif $connection
} # End foreach $ScriptVCInstance
# write-out as a CSV file
Write-host "Exporting CSV $($env:USERPROFILE)\Licensed-Assets.csv"
$report | Sort-object "vCenter","License","Entity" | Export-csv "$($env:USERPROFILE)\Licensed-Assets.csv" -NoTypeInformation -UseCulture
$sw.Stop()
$sw.Elapsed

powershell script to return all forwarding rules in org

I need to pull all forwarding rules for an exchange online environment, and output them to a csv. this sounds simple, but I have an additional caveat. there are 23,000 mailboxes in the org.
I was able to write the script I needed, it outputted the data, but it timed out.
then I was able to break out only certain mailboxes that were critical (11,000) but I was still timing out in powershell.
so finally, I found an article that detailed breaking up a script into blocks of 1,000, and running numerous sessions. and runs! it runs without timing out.
but it doesn't output to the csv anymore.
since my script has gone through several iterations, I'm pretty sure that my problem is the way I'm storing, or outputting the array, but for all my staring at this, I cant figure it out. short of asking the doc for a prescription of Adderall, I figured id ask here. below is the offending script.
the aliaslist.csv that it mentions is just a csv with a list of aliases for 11,000 mailboxes. if you would like to run your own tests, you can adjust $pagesize down and paste a few mailboxes into a csv called aliaslist, stored in c:\temp
Function New-O365ExchangeSession()
{
param(
[parameter(mandatory=$true)]
$365master)
#close any old remote session
Get-PSSession | Remove-PSSession -Confirm:$false
#start a new office 365 remote session
$365session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $365master -Authentication Basic -AllowRedirection
$office365 = Import-PSSession $365session
}
#set input variables
$path = "C:\temp"
$InputFile = aliaslist.csv"
$UserEmail = "admin#domain.com"
#set variables for csv usage
$Offset = 0;
$PageSize = 1000;
$MbxMax = (Import-Csv "$path/$InputFile").count
#Loop in the list and retrieve the device’s information
$file = “c:\temp\office365-$((get-date).tostring(“yyyy-MM-dd”)).csv”
$365master = get-credential $UserEmail
New-O365ExchangeSession $365master
# call the office365 remote connection function
do{
$mbxlist=#(import-csv "$path/$InputFile"|select-object -skip $Offset -First $PageSize)
"Process entry $($Offset) to $($Offset+$PageSize)"
#end csv input count reference
ForEach($mbx in $MbxList)
{
#Write to Host
"start Processing $($mbx.alias)"
#end Write to host,
#Check rules
$rules = Get-InboxRule -mailbox $_.alias | ? {$_.RedirectTo -ne $null -or $_.ForwardTo -ne $null -or $_.ForwardAsAttachmentTo -ne $null}
If ($rules -ne $null)
{
$rules | % {
#check for forwardAsAttachments
If ($_.ForwardAsAttachmentTo -ne $null)
{
$obj = New-Object system.object
$obj | Add-Member -name "NetID" -Value $_.alias -MemberType NoteProperty
$obj | Add-Member -name "ForwardType" -Value "Forward As Attachment Rule" -MemberType NoteProperty
$obj | Add-Member -name "ForwardAddress" -Value $_.forwardAsAttachmentTo -MemberType NoteProperty
$obj | Add-Member -name "Enabled" -Value $_.Enabled -MemberType NoteProperty
$obj | Add-Member -name "Description" -Value $f -MemberType NoteProperty
If (Test-Path $file)
{
$mbx.alias + ”,” + ($obj | ConvertTo-Csv)[2] | Out-File $file –Append
}
Else
{
$obj | Export-Csv $file -Encoding ASCII -notypeinformation
}
}
$obj = $null
#check for redirects
If ($_.redirectto -ne $null)
{
$obj = New-Object system.object
$obj | Add-Member -name "NetID" -Value $_.alias -MemberType NoteProperty
$obj | Add-Member -name "ForwardType" -Value "Redirct Rule" -MemberType NoteProperty
$obj | Add-Member -name "ForwardAddress" -Value $_.redirectto -MemberType NoteProperty
$obj | Add-Member -name "Enabled" -Value $_.Enabled -MemberType NoteProperty
$obj | Add-Member -name "Description" -Value $c -MemberType NoteProperty
If (Test-Path $file)
{
$mbx.alias + ”,” + ($obj | ConvertTo-Csv)[2] | Out-File $file –Append
}
Else
{
$obj | Export-Csv $file -Encoding ASCII -notypeinformation
}
}
$obj = $null
#check for forwards
If ($_.ForwardTo -ne $null)
{
$obj = New-Object system.object
$obj | Add-Member -name "NetID" -Value $_.alias -MemberType NoteProperty
$obj | Add-Member -name "ForwardType" -Value "Forward Rule" -MemberType NoteProperty
$obj | Add-Member -name "ForwardAddress" -Value $_.forwardto -MemberType NoteProperty
$obj | Add-Member -name "Enabled" -Value $_.Enabled -MemberType NoteProperty
$obj | Add-Member -name "Description" -Value $f -MemberType NoteProperty
If (Test-Path $file)
{
($obj | ConvertTo-Csv)[2] | Out-File $file –Append
}
Else
{
$obj | Export-Csv $file -Encoding ASCII -notypeinformation
}
}
$obj = $null
}
}
}
#increment the start point for the next chunk
$Offset+=$PageSize
#Call the office365 remote session function to close the current one and open a new session
New-O365ExchangeSession $365master
} while($Offset -lt $MbxMax)

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.