I have a PowerShell script that runs a few API request and then export information on the test into an excel.
When I create the table to I adds couple column for the results. However when I export the tables via Excel there are a bunch of extra column I don't want.
$ResultsTable = New-Object System.Data.DataTable "ResultsTable"
$RTC1 = New-Object system.Data.DataColumn "Type",([string])
$RTC2 = New-Object system.Data.DataColumn "Endpoint",([string])
$RTC3 = New-Object system.Data.DataColumn "PassRate",([string])
$RTC4 = New-Object system.Data.DataColumn "AvgTime",([string])
$RTC5 = New-Object system.Data.DataColumn "MaxTime",([string])
$RTC6 = New-Object system.Data.DataColumn "AvgSize",([string])
$RTC7 = New-Object system.Data.DataColumn "MaxSize",([string])
$ResultsTable.Columns.Add($RTC1)
$ResultsTable.Columns.Add($RTC2)
$ResultsTable.Columns.Add($RTC3)
$ResultsTable.Columns.Add($RTC4)
$ResultsTable.Columns.Add($RTC5)
$ResultsTable.Columns.Add($RTC6)
$ResultsTable.Columns.Add($RTC7)
$Row = $ResultsTable.NewRow()
$Row.Type = "Direct"
$Row.Endpoint = $Uri
$Row.PassRate = "$PassRate%"
$Row.AvgTime = $AvgTime
$Row.MaxTime = $MaxTime
$Row.AvgSize = $AvgSize
$Row.MaxTime = $MaxSize
$ResultsTable.Rows.Add($Row)
$ResultsTable | Export-Excel -Path ".\Output\Unit\API.Customer.Unit.Tests - $DateTime.xlsx" `
-AutoSize `
-WorksheetName "Results" `
-Title "Results Table" `
-TitleBold `
-BoldTopRow `
-FreezeTopRow
The output of this export looks like:
I only need the Columns A - G. How do I get rid of the other columns?
Either select the columns you want to keep:
$ResultsTable |
Select-Object Type, Endpoint, PassRate, AvgTime, MaxTime, AvgSize, MaxSize |
Export-Excel ...
or remove the columns you don't want to keep:
$ResultsTable |
Select-Object -Property * -Exclude RowError, RowState, Table, ItemArray, HasErrors |
Export-Excel ...
If you know that you're always going to need exactly the columns defined in the table, you could also reference them directly:
$ResultsTable |
Select-Object -Property $ResultsTable.Columns.ColumnName |
Export-Excel ...
Related
I have multiple files contain a persons Fullname in a single cell. I would like to separate these names into two columns - first name and Surname
the code I have used to separate values worked in a previous iteration of the script I had but now no longer works
I can't pinpoint where the error lies, can anyone advise?
$path = 'C:\MAY2019correct'
#XYZ
$excelOut = Join-Path -Path $path -ChildPath 'XYZ.csv'
$completedFile = Join-Path -Path $path -ChildPath 'Completed-XYZ.csv'
$defaultValue = 'ABC'
$filter = '*XYZ*'
$excelFile = Get-ChildItem -Path $path -Filter $filter -File |
Select-Object -First 1
$allstaff = #()
if ($excelFile) {
$excel = New-Object -ComObject Excel.Application -Property #{Visible =
$false}
# Open the file
$workbook = $excel.Workbooks.Open($excelFile.FullName)
# Activate the first worksheet
$sheet = $workbook.Sheets.Item(1)
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the first row
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the 2 row
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the 3 row
$workbook.SaveAs($excelOut,6)
# Close workbook and save changes
$workbook.Close($true)
# Quit Excel
$excel.Quit()
# clean-up Com objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
$headers = 'Element Name','Surname','EmployeeNo','Amount','YTD'
# import the csv file and select all the above headers plus one that is created using a calculated property
$csv = Import-Csv -Path $excelOut -Header $headers -UseCulture | Select-Object *, #{Name = 'Paycentre'; Expression = {$defaultValue}}|
Write-Host "Creating completed csv file '$completedFile'"
$csv | Export-Csv -Path $completedFile -UseCulture -Force -
NoTypeInformation
}
else {
Write-Warning "Could not find a file using filter '$filter' in path
'$path'"
}
foreach($staff in $completedFile)
{
#Get the values from the CSV for this row
$Surname = $staff.Surname
$Surname = $Surname.Substring(0, $Surname.lastIndexOf(' '))
$Initial = $staff.Surname
$Initial = $Initial.Substring($Initial.lastIndexOf(' ') + 1 )
$Firstname = $staff.Surname
$Firstname = $Firstname.Substring($Initial.lastIndexOf(' ') + 1 )
$EmployeeNo = $staff.EmployeeNo
$NINumber = $staff.NINumber
$Amount = $staff.Amount
$Paycentre = $staff.Paycentre
$staff2 = New-Object System.Object
$staff2 | Add-Member -MemberType NoteProperty -Name "Surname" -Value $Surname
$staff2 | Add-Member -MemberType NoteProperty -Name "FirstName" -Value $Firstname
$staff2 | Add-Member -MemberType NoteProperty -Name "EmployeeNo" -Value $EmployeeNo
$staff2 | Add-Member -MemberType NoteProperty -Name "NINumber" -Value $NINumber
$staff2 | Add-Member -MemberType NoteProperty -Name "Amount" -Value $Amount
$staff2 | Add-Member -MemberType NoteProperty -Name "FirstName" -Value $Initial
$staff2 | Add-Member -MemberType NoteProperty -Name "Paycentre" -Value $Paycentre
#add to array
$allstaff += $staff2
}
$allstaff | Export-Csv -NoTypeInformation -Path $completedFile
The first thing I see is that your foreach loop is iterating over the $completedFile variable which appears to be a file path, not a collection.
Should it be foreach ($staff in $csv) instead?
Also, be very wary of dealing with names in code. It's super easy to make poor assumptions that break things. See Falsehoods Programmers Believe About Names for more info there.
I have a csv file which contains all data in 1 column.
This is the format,
EPOS SKU QTY ReferenceNr
---- --- --- -----------
717 30735002 1 S04-457312
700 30777125 1 S06-457360
700 25671933 1 S06-457389
716 25672169 1 S09-457296
716 25440683 1 S09-457296
I would like to separate those data into 4 columns with these following headers and save/export to csv or xlsx via powershell script.
Thank you for your help
This should work:
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$inputFile = $PSScriptRoot + '\rawtext.txt'
$csvFile = $PSScriptRoot + '\rawtext.csv'
$excelFile = $PSScriptRoot + '\rawtext.xlsx'
# Create datatable
$dt = New-Object system.Data.DataTable
[void]$dt.Columns.Add('EPOS',[string]::empty.GetType() )
[void]$dt.Columns.Add('SKU',[string]::empty.GetType() )
[void]$dt.Columns.Add('QTY',[string]::empty.GetType() )
[void]$dt.Columns.Add('ReferenceNr',[string]::empty.GetType() )
# loop file
foreach($line in [System.IO.File]::ReadLines($inputFile))
{
if( $line -match '^\d+' ) {
$contentArray = $line -split ' +'
$newRow = $dt.NewRow()
$newRow.EPOS = $contentArray[0]
$newRow.SKU = $contentArray[1]
$newRow.QTY = $contentArray[2]
$newRow.ReferenceNr = $contentArray[3]
[void]$dt.Rows.Add( $newRow )
}
}
# create csv
$dt | Export-Csv $outputFile -Encoding UTF8 -Delimiter ';' -NoTypeInformation
#create excel
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
[void]$excel.Workbooks.Open($csvFile).SaveAs($excelFile, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault)
[void]$excel.Workbooks.Close()
[void]$excel.Quit()
# remove csv
Remove-Item -Path $csvFile -Force | Out-Null
With the Export-Csv instead of Format-Table solved.
$ftr = Get-Content -Path $pathfile |
select -Skip 1 |
ConvertFrom-Csv -Delimiter '|' -Header 'Detail', 'LineNr', 'EPOS', 'SKU',
'SKUName', 'QTY', 'StoreName', 'Contact', 'ReferenceNr' |
Select-Object -Property EPOS, SKU, QTY, ReferenceNr |
Export-Csv -Path $target$ArvName.csv -NoTypeInformation
If your question is regarding Excel... (It is not clear for me)
Just rename the file from *.csv to *.txt and open it on Excel.
On the Text Assistant choose "My data has headers" and "Delimited" and it will be correctly imported with each data on one column. As you ask for.
Later on, save as csv or xlsx.
I wanted to read the contents of an excel file and then output them to a text file. Currently, my code only outputs the results to the console.
I tried to write code that gets the applicable columns and then loads them into an array to be written to the console later.
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $False
$PLACE = "C:\Somepath\somename.xlsx"
$OpenFile = $Excel.Workbooks.Open($PLACE)
$Workbook = $OpenFile.Worksheets
$Worksheet = $Workbook.Item(1)
# Get the values for each column
$MNumber = $Worksheet.Cells | where {$_.value2 -eq "Material-Number"} | select -First 1
$MDescription = $Worksheet.Cells | where {$_.value2 -eq "Material-Description"} | select -First 1
# Get the values for each row in Material Number
$NumValues = #()
$NumValues = for($i=2; $MNumber.Cells.Item($i).Value2 -ne $null; $i++ ){
$MNumber.Cells.Item($i)
}
# Get the values for each row in Material Description
$DescValues = #()
$DescValues = for($i=2; $MDescription.Cells.Item($i).Value2 -ne $null; $i++ ){
$MDescription.Cells.Item($i)
}
$NumValues | ForEach-Object {Write-host $_.value2}
$DescValues | ForEach-Object {Write-Host $_.value2}
Nothing output to the console by the end of the process. Even though those are the exact columns and each column contains data.
Try match instead of eq here:
$MNumber = $Worksheet.Cells | where {$_.value2 -match "Material-Number"} | select -First 1
$MDescription = $Worksheet.Cells | where {$_.value2 -match "Material-Description"} | select -First 1
I'm not sure if your cell has other strings within it on $_.value2 but if it does eq will not work. It's trying to find the ENTIRE string it's conditioning against. Therefore, if there's other strings of data within the cell it will not pull the data.
I have a CSV file that has similar products within it and quantities of each product beside it.
Sample from CSV file
Qty Ordered Product/Item Description Top row (header)
7 Product1
3 Product2
5 Product1
3 Product3
I need a method to find all the similar product#s, add up their Quantities, and place the total of each similar product in a new row.
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property
#{
Multiselect = $false # Multiple files can be chosen
Filter = 'Excel (*.csv, *.xlxs)|*.csv;*.xlsx' # Specified file types
}
[void]$FileBrowser.ShowDialog()
$file = $FileBrowser.FileNames;
[Reflection.Assembly]::LoadWithPartialName
("Microsoft.Office.Interop.Excel")|Out-Null
$excel = New-Object Microsoft.Office.Interop.Excel.ApplicationClass
$excel.Visible = $true
$wb = $excel.Workbooks.Open($file)
$ws = $wb.ActiveSheet
$c = $ws.Columns
$c.Item(2).hidden = $true
This code, asks the user to select the csv file, hides useless columns and auto-sizes the important columns as well.
Rather than using Excel as a COM Object you could use Import-CSV and then Group-Object. Then loop through the groups for the information you need.
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property #{
Multiselect = $false # Multiple files can be chosen
Filter = 'Excel (.csv, *.xlxs)|.csv;*.xlsx' # Specified file types
}
[void]$FileBrowser.ShowDialog()
ForEach ($file in $FileBrowser.FileNames) {
$CSV = Import-CSV $file | Add-Member -Name Total -Value 0 -MemberType NoteProperty
$Groups = $CSV | Group-Object "Product/Item Description"
$NewCSV = Foreach ($Group in $Groups) {
$Count = 0
$Group.Group."Qty Ordered" | ForEach-Object {$Count += $_}
Foreach ($value in $CSV) {
If ($value."Product/Item Description" -eq $Group.Name) {
$value.Total = $Count
$value
}
}
}
Export-CSV "$filenew" -NoTypeInformation
}
I wrote a function Get-oracleresultDa which have oracle connection properties.Through which I can query my DB.
But,the problem is which I try to export the data to the excel sheet it only returns the result of the second query i.e)no status
and not no type
$results = Get-OracleResultDa -conString $connectionString -sqlString $query
-Verbose
$results | SELECT no, type| Export-CSV "H:\Book2.csv" -Force
$rows++
$results1 = Get-OracleResultDa -conString $connectionString -sqlString
$created -Verbose
$results1 | SELECT no, status| Export-CSV "H:\Book2.csv" -
NoTypeInformation
The below mentioned block was in the first 10 linesof the script
$file="H:\Book2.csv"
$excel = New-Object -ComObject excel.application
#Makes Excel Visable
$excel.Application.Visible = $true
$excel.DisplayAlerts = $false
#Creates Excel workBook
$book = $excel.Workbooks.Add()
#Adds worksheets
#gets the work sheet and Names it
$sheet = $book.Worksheets.Item(1)
$sheet.name = 'Created'
#Select a worksheet
$sheet.Activate() | Out-Null
I have few more query's which also as to be exported
If you use powershell 3.0 or better, you can use -Append modificator
$results = Get-OracleResultDa -conString $connectionString -sqlString $query
-Verbose
$results | SELECT no, type| Export-CSV "H:\Book2.csv" -Force
$rows++
$results1 = Get-OracleResultDa -conString $connectionString -sqlString
$created -Verbose
$results1 | SELECT no, status| Export-CSV "H:\Book2.csv" -
NoTypeInformation -Append