How to change the background color of an Excel report - excel

Basically, I am using this script to run through all the .csv files in a specific folder and merge them all together. But after the merge, I still want to change the background color of each .csv file.
The script that I got so far does not do that, can't figure out how to do it as I am really new in PowerShell.
# Get all the information from .csv files that are in the $IN_FILE_PATH skipping the first line:
$getFirstLine = $true
get-childItem "$IN_FILE_PATH\*.csv" | ForEach {
$filePath = $_
$lines = $lines = Get-Content $filePath
$linesToWrite = switch ($getFirstLine) {
$true { $lines }
$false { $lines | Select -Skip 1 }
}
# Import all the information... and tranfer to the new workbook.
$Report_name = $((get-date).ToString("yyyy.MM.dd-hh.mm"))
$getFirstLine = $false
Add-Content "$OUT_FILE_PATH\Report $Report_Name.csv" $linesToWrite
}
e.g. The .csv file has this pattern:
Name Age
Richard 18
Carlos 20
Jonathan 43
Mathew 25
Making sure to understand that Richard (18 years old) and Carlos (20 years old) are from filenumber1.csv - Jonathan (43 years old) and Mathew (25 years old) are from filenumber2.csv
I want Carlos' and Richard's rows to be with a white background, whereas Jonathan's and Mathew's rows to be grey. So that repeats in white-grey-white-grey dividing it by each file.
I am trying to make it more friendly to observe the report in the end - to make sure that you can this separation from file to file more clear.
Any ideas?

As Vivek Kumar Singh mentioned in comments, .csv doesn't contain any formatting options. It's recommended to work with Excel file instead. And for that purpose, the best module I know and use is ImportExcel.
The code to set formatting is as below (inspired by this thread):
$IN_FILE_PATH = "C:\SO\56870016"
# mkdir $IN_FILE_PATH
# cd $IN_FILE_PATH
# rm out.xlsx
# Define colors
$colors = "White", "Gray"
# Initialization
$colorsTable = #()
$data = #()
$n = 0
Get-ChildItem "$IN_FILE_PATH\*.csv" | % {
$part = Import-Csv $_
$data += $part
for ($i = 0; $i -lt ($part).Count; $i++) {
$colorsTable += $colors[$n%2]
}
$n++
}
$j = 0
$data | Export-Excel .\out.xlsx -WorksheetName "Output" -Append -CellStyleSB {
param(
$workSheet,
$totalRows,
$lastColumn
)
foreach($row in (2..$totalRows )) {
# The magic happens here
# We set colors based on the list which was created while importing
Set-CellStyle $workSheet $row $LastColumn Solid $colorsTable[$j]
$j++
}
}
Hopefully the comments in the code help you to better understanding of what's going on in the code.

Related

How to modify excel data and export to text file using PowerShell script?

First time poster here. Apologies if I am not following best practices for posting this question.
I am very new to scripting and PowerShell.
Problem:
I have data in an excel sheet in this format.
Excel Data Image Link
I want to modify and export this data into a text file. In this format.
Required Output Image Link
Till now I have tried to modify the excel data by accessing each cell. To access each cell I am using a similar code mentioned below.
for (($i = 1); $i -lt 4; $i++)
{
$column=$ExcelWorkSheet.Columns.Item(1).Rows.Item($i).Text
$dataType=$ExcelWorkSheet.Columns.Item(2).Rows.Item($i).Text
$c1=("`"" + "$column" + "`""+":")
$c2=("`"" + "$dataType" + "`"" + ",")
$ExcelWorkSheet.Columns.Item(1).Rows.Item($i).Value=$c1
$ExcelWorkSheet.Columns.Item(2).Rows.Item($i).Value=$c2
}
I am still not sure if this is the correct way to go.
what would be the best way to solve this?
Just want to understand what I should do to solve this problem. I am not looking for the exact code.
Step by step instructions or some resources would be helpful.
Thanks!
This might help... maybe...
# Import Stuff
$Data = Import-Csv -Path .\Desktop\data.csv
# New Array
$Output = #()
# Run through Unique Owners
foreach ($Owner in ($Data | Select-Object OWNER -Unique)) {
$Lines = $Data | Where-Object {$_.OWNER -eq $Owner.OWNER}
# Lazy way to do a bit of checking, if same then use it or Break
if ($Lines[0].TABLE_NAME -eq $Lines[1].TABLE_NAME) {
$Out_TableName = $Lines[0].TABLE_NAME
# ID and NAME data
$Out_ID = $Lines | Where-Object {$_.COLUMN_NAME -eq "ID"} | Select-Object COLUMN_NAME, DATA_TYPE, DATA_LENGTH
$Out_NAME = $Lines | Where-Object {$_.COLUMN_NAME -eq "NAME"} | Select-Object COLUMN_NAME, DATA_TYPE, DATA_LENGTH
} else {
# Show the user that something
Write-Host "Problem with Owner ""$($Owner.OWNER)"" Data?!" -ForegroundColor Red
Break
}
# Output into the array in format
$Output += #"
"$($Owner.OWNER).$($Out_TableName)":{
"$($Out_ID.COLUMN_NAME)": "$($Out_ID.DATA_TYPE) ($($Out_ID.DATA_LENGTH))",
"$($Out_NAME.COLUMN_NAME)": "$($Out_NAME.DATA_TYPE) ($($Out_NAME.DATA_LENGTH))"
}
"#
}
# Put Output in a text file
$Output | Set-Content .\Desktop\output.txt -Force
I should add, that I had your data in a CSV like this...
OWNER,TABLE_NAME,COLUMN_NAME,DATA_TYPE,DATA_LENGTH
A,Employee,ID,NUMBER,22
A,Employee,NAME,VARCHAR2,22
B,Department,ID,NUMBER,23
B,Department,NAME,VARCHAR2,24

Read csv stream line by line to create an array for Excel Range

This is my first post - I will be happy to make any corrections required for any mistakes made in the post.
I have been looking through the forums here for a few months and have learned a lot but I cannot seem to accomplish my goal with what I have found.
I need to read a CSV file (Read-Only) when it changes and place the resulting array into and active and open Excel 2016 Tab. I can do this using com and system.io.watcherchangetypes but this is too slow and requires copy paste.
I need to read the csv as fast as possible (under a second) and convert the lines into a usable array for Excel. This whole process has to take under 2 seconds MAX. Some of the CSV's will exceed 180,000 lines as the day goes on.
I work for a Trading Company.
I would be happy with a single column, Tab delimited and multiple Rows. I cant get the multiple rows.
I have to write the range line by line and that takes too long.
I was looking at this one but I am not clear on how to make the whole thing dynamic. There is no set amount of headers and the rows will change as well. I cannot work with any static data at all.
This is the post which prompted me to ask for help: How to use powershell to reorder CSV columns
$export = "\\UNC\to\file\Name.csv"
#$excel = New-Object -ComObject Excel.Application
#$excel.visible = $true
#$workbook = $excel.Workbooks.Add()
$reader = [System.IO.File]::OpenText($export)
$writer = New-Object System.IO.StreamWriter "data2.csv"
for(;;) {
$line = $reader.ReadLine()
if ($null -eq $line) {
break
}
$i=1
$data = $line.Split(",") | %{
if($_ -ne $null)
{
Write-Host $_ $i
++$i
}
}
[void]$data.Length
# $data.GetValue()
#$writer.WriteLine('{0},{1},{2}', $data[0], $data[1], $data[2])
}
$reader.Close()
#$writer.Close()
Any help will be greatly appreciated!
UPDATE:
I figured it out. The result is probably not the most efficient but it gets me what I need for now while i explore how to better accomplish it with what I have learned.
(Measure-Command { $data = [System.io.File]::Open($export, 'Open', 'Read', 'ReadWrite')
$reader = New-Object System.IO.StreamReader($data)
$count = 0
While($text = $reader.Readline())
{
If($text -eq $null)
{
$reader.Close()
$data.close()
}
++$count
}
}).TotalSeconds
$array2 = New-Object 'object[,]' $count,1
$end = ++$count
$file = New-Object System.IO.StreamReader -ArgumentList $export
$stringBuilder = New-Object System.Text.StringBuilder
$list = New-Object System.Collections.Generic.List[System.String]
$a = 0
Measure-Command {
While ($i = $file.ReadLine() -Replace ",","`t")
{
if ($i -eq $null)
{
$file.close()
break loop
}
$null = $stringBuilder.Append($i)
$list.Add($i)
$array2[$a,0] = $i
++$a
}
$outputString = $stringBuilder.ToString()
$array = $list.ToArray()
}
You can do something like this
data = pd.read_csv("data1.csv", sep='\s+',header=None)
dataarraynew13phse = np.array(data)
dataarraynew13phse=dataarraynew13phse.flatten()
sep = '\s+' can be useful to decode tabs, in multiple lines
And then flatten() can make it in a single row or array

Delete extra rows in an excel file with powershell?

I have been tasked to automate part of the logging process on a SPLA server owned by the company. My task is to date, archive, and remove the old files, then move onto a generating a report to be emailed to the department. This task is supposed to be ran at the end of every week.
I figured powershell would be the best option to complete this task. This is my first time working with powershell so I had a bit of learning to do.
My question:
Is it possible to loop through an excel worksheet and delete unused rows using this script?
My condition would be if there are two empty rows -> delete one row and keep going
I am taking info from the log and splitting it into a CSV then converting the CSV to an excel for formatting.
Sample of the Excel spreadsheet, others vary in excess rows between information
Get-ChildItem C:\ScriptsDirectory1\*.log | foreach{
$input = Get-Content $_.FullName #Initialize input
$a = Get-Date #Save the current date (for if/else wrapper)
#=============================================#
# File Name Changer #
#=============================================#
$x = $_.LastWriteTime.ToShortDateString() #Save a temp variable with the LastWriteTime and send it to a string
$new_folder_name = Get-Date $x -Format yyyy.MM.dd #Create a new folder that contains the string information
$des_path = "C:\Archive\ArchivedLogs\$new_folder_name" #Send the new folder to the archive directory
#=============================================#
$data = $input[1..($input.Length - 1)] #Initialize Array and set it to the length of the input file.
$maxLength = 0
$objects = ForEach($record in $data) { #Loop through each object within the array
$split = $record -split ": " #Split objects within array at the ": " string
If($split.Length -gt $maxLength){
$maxLength = $split.Length
}
$properties = #{}
For($i=0; $i -lt $split.Length; $i++) { #Adds the split information to the strings array
$properties.Add([String]($i+1),$split[$i])
}
New-Object -TypeName PSObject -Property $properties
}
$objects | format-table
$headers = [String[]](1..$maxLength)
$objects |
Select-Object $headers |
Export-Csv -NoTypeInformation -Path "C:\Archive\CSVReports\$new_folder_name.csv"#Export CSV path using the new folder name to prevent overwrite
if (test-path $des_path){ #Test if the path exists, and fill the directory with the file to be archived
move-item $_.fullname $des_path
} else {
new-item -ItemType directory -Path $des_path
move-item $_.fullname $des_path
}
} #End of Parser
#===============================================================================#
#======================================#========================================#
#===============================================================================#
# File Archiver and Zipper (After Parse/CSV) #
#===============================================================================#
#======================================#========================================#
#===============================================================================#
$files = Get-ChildItem C:\Archive\ArchivedLogs #Fill the $files variable with the new files in the Archive directory
#********************************#
#Loop Through and Compress/Delete#
#********************************#
foreach ($file in $files) {
Write-Zip $file "C:\Archive\ArchivedLogs\$file.zip" -Level 9 #Write compressed file
} #End of Archiver
Remove-Item C:\Archive\ArchivedLogs\* -exclude *.zip -recurse #Remove the un-needed files within the archive folder
#Run the Formatting and Conversion script for the CSV-to-XLSX
#C:\ScriptsDirectory1\Script\TestRunner1.ps1 #<---Can be Ran using a Invoke call
#===============================================================================#
#======================================#========================================#
#===============================================================================#
# CSV to XLSX Format/Conversion #
#===============================================================================#
#======================================#========================================#
#===============================================================================#
Get-ChildItem C:\Archive\CSVReports | foreach{
$excel_file_path = $_.FullName #Create the file path variable to initialize for formating
$Excel = New-Object -ComObject Excel.Application #Start a new excel application
$Excel.Visible = $True
$Excel.DisplayAlerts=$False
$Excel_Workbook = $Excel.Workbooks.Open($excel_file_path) #Create workbook variable and open a workbook in the path
$FileName = $_.BaseName #Save the base file name of the current value
$Excel.ActiveSheet.ListObjects.add(1,$Excel_Workbook.ActiveSheet.UsedRange,0,1)
$Excel_Workbook.ActiveSheet.UsedRange.EntireColumn.AutoFit()
$SPLA1wksht = $Excel_Workbook.Worksheets.Item(1) #Create the new Sheet (SPLA1wksht)
#*******************************************************#
# Formating for Title Cell #
#*******************************************************#
$SPLA1wksht.Name = 'SPLA Info Report' #Change worksheet name
$SPLA1wksht.Cells.Item(1,1) = $FileName #Title (Date of log) in cell A1
$SPLA1wksht.Cells.Item(1,2) = 'SPLA Weekly Report' #Title for all Excel reports
$SPLA1wksht.Cells.Item(1.2).Font.Size = 18
$SPLA1wksht.Cells.Item(1.2).Font.Bold=$True
$SPLA1wksht.Cells.Item(1.2).Font.Name="Cambria"
$SPLA1wksht.Cells.Item(1.2).Font.ThemeFont = 1
$SPLA1wksht.Cells.Item(1.2).Font.ThemeColor = 5
$SPLA1wksht.Cells.Item(1.2).Font.Color = 8210719
#*******************************************************#
#************************************#
# Adjust and Merge Cell B1 #
#************************************#
$range = $SPLA1wksht.Range("b1","h2")
$range.Style = 'Title'
$range = $SPLA1wksht.Range("b1","g2")
$range.VerticalAlignment = -4108 #Center align vertically (Value -4108 is center)
#************************************#
#***********************************************************************#
# Horizontal Centering for all cells #
#***********************************************************************#
$ColumnRange = $SPLA1wksht.Range("a1","a500").horizontalAlignment =-4108 #Center all cells in this range as -4108
$ColumnRange = $SPLA1wksht.Range("b1","b500").horizontalAlignment =-4108
#**********************************************#
# Delete Blank Rows Inneffective- Logs that have different
#data end up with a different amount of rows and offsets this deletion
# # This method deletes the first row then
#moves onto
#**********************************************# # the next-in-line blank lines and deletes the one
#$SPLA1wksht.Cells.Item(2,1).EntireRow.Delete() # # line until the blank spots are in perfect format
#
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() #
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() #
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() #
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() #
#
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()#
#
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()#
#
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()#
#**********************************************#
#*****************************************************************#
# Final Export as a CSV-to-XLSX file #
#*****************************************************************#
$Excel_Workbook.SaveAs("C:\Archive\ExcelReports\$FileName.xlsx",51) #Save the file in the proper location
$Excel_Workbook.Saved = $True
$Excel.Quit()
# Find a way to optimize this process
#Potential optimization places:
# 1.) Don't open and close excel file and instead just write changes and save
# 2.) Change way empty rows are formatted instead of seperate calls each time
} #End of Format/Converter
#******End******#
#---------------#--#--------------#
#---------------------------------#
# What to Add to the Script #
#---------------------------------#
#---------------#--#--------------#
# -[/] <-Complete -[] <- Incomplete
# -[] Archive or delete CSV Files
# -[] Add a If/Else statement that checks if files are >7 days old
# -[] Compile a weekender report that indicates any SPLA programs changed to keep compliance
# -[] Filter for only SPLA files (Need a list)
# -[] Loop through CSV/Excel file and delete empty rows
The following code worked to run through the program:
for($i = 350 ; $i -ge 0 ; $i--) {
If ($SPLA1wksht.Cells.Item($i, 1).Text-eq "") {
$Range = $SPLA1wksht.Cells.Item($i, 1).EntireRow
[void]$Range.Delete()
echo $i
}
If ($SPLA1wksht.Cells.Item($i, 2).Text-eq "") {
$Range = $SPLA1wksht.Cells.Item($i, 2).EntireRow
[void]$Range.Delete()
echo $i
}
If($i -eq 2){ break;}
}
This should be relatively straight forward
$file = C:\path\to\file.csv
$csv = Import-Csv $file
foreach($row in $csv) {
# logic to delete row
# $csv is an array, so you can could make the row = null to delete it
}
# spit out updated excel sheet
Export-Csv | $csv -NoTypeInformation

PowerShell script to monitor IIS logs for 500 errors every 10 minutes

I'm trying to set up a script to monitor IIS 7.5 logs fro 500 errors. Now I can get it to do that OK but I would like it to check every 30 minutes. Quite naturally I don't want it to warn me about the previous 500 errors it has already reported.
As you can see from the script below I have added a $time variable to take this into account, however I can't seem to find a way to use this variable. Any help would be appreciated.
#Set Time Variable -30
$time = (Get-Date -Format hh:mm:ss (Get-Date).addminutes(-30))
# Location of IIS LogFile
$File = "C:\Users\here\Documents\IIS-log\"+"u_ex"+(get-date).ToString("yyMMdd")+".log"
# Get-Content gets the file, pipe to Where-Object and skip the first 3 lines.
$Log = Get-Content $File | where {$_ -notLike "#[D,S-V]*" }
# Replace unwanted text in the line containing the columns.
$Columns = (($Log[0].TrimEnd()) -replace "#Fields: ", "" -replace "-","" -replace "\(","" -replace "\)","").Split(" ")
# Count available Columns, used later
$Count = $Columns.Length
# Strip out the other rows that contain the header (happens on iisreset)
$Rows = $Log | where {$_ -like "*500 0 0*"}
# Create an instance of a System.Data.DataTable
#Set-Variable -Name IISLog -Scope Global
$IISLog = New-Object System.Data.DataTable "IISLog"
# Loop through each Column, create a new column through Data.DataColumn and add it to the DataTable
foreach ($Column in $Columns) {
$NewColumn = New-Object System.Data.DataColumn $Column, ([string])
$IISLog.Columns.Add($NewColumn)
}
# Loop Through each Row and add the Rows.
foreach ($Row in $Rows) {
$Row = $Row.Split(" ")
$AddRow = $IISLog.newrow()
for($i=0;$i -lt $Count; $i++) {
$ColumnName = $Columns[$i]
$AddRow.$ColumnName = $Row[$i]
}
$IISLog.Rows.Add($AddRow)
}
$IISLog | select time,csuristem,scstatus
OK With KevinD's help and PowerGUI with a fair bit of trial and error, I got it working as I expected. Here's the finished product.
#Set Time Variable -30
$time = (Get-Date -Format "HH:mm:ss"(Get-Date).addminutes(-30))
# Location of IIS LogFile
$File = "C:\Users\here\Documents\IIS-log\"+"u_ex"+(get-date).ToString("yyMMdd")+".log"
# Get-Content gets the file, pipe to Where-Object and skip the first 3 lines.
$Log = Get-Content $File | where {$_ -notLike "#[D,S-V]*" }
# Replace unwanted text in the line containing the columns.
$Columns = (($Log[0].TrimEnd()) -replace "#Fields: ", "" -replace "-","" -replace "\(","" -replace "\)","").Split(" ")
# Count available Columns, used later
$Count = $Columns.Length
# Strip out the other rows that contain the header (happens on iisreset)
$Rows = $Log | where {$_ -like "*500 0 0*"}
# Create an instance of a System.Data.DataTable
#Set-Variable -Name IISLog -Scope Global
$IISLog = New-Object System.Data.DataTable "IISLog"
# Loop through each Column, create a new column through Data.DataColumn and add it to the DataTable
foreach ($Column in $Columns) {
$NewColumn = New-Object System.Data.DataColumn $Column, ([string])
$IISLog.Columns.Add($NewColumn)
}
# Loop Through each Row and add the Rows.
foreach ($Row in $Rows) {
$Row = $Row.Split(" ")
$AddRow = $IISLog.newrow()
for($i=0;$i -lt $Count; $i++) {
$ColumnName = $Columns[$i]
$AddRow.$ColumnName = $Row[$i]
}
$IISLog.Rows.Add($AddRow)
}
$IISLog | select #{n="Time"; e={Get-Date -Format "HH:mm:ss"("$($_.time)")}},csuristem,scstatus | ? { $_.time -ge $time }
Thanks again Kev you're a good man. Hope this code helps someone else out there.
Here's
Try changing your last line to:
$IISLog | select #{n="DateTime"; e={Get-Date ("$($_.date) $($_.time)")}},csuristem,scstatus | ? { $_.DateTime -ge $time }
In the select, we're concatenating the date and time fields, and converting them to a date object, then selecting rows where this field is greater than your $time variable.
You'll also need to change your $time variable:
$time = (Get-Date).AddMinutes(-30)
You want a DateTime object here, not a string.

PowerShell - paste data into Excel

Today I have just thrown together this PowerShell script which
takes a tab-delimited text file,
reads it into memory,
makes a variable number of filter queries based on distinct values of a certain column
creates a new empty Excel workbook
adds each of the subsets of filtered data to
a new Excel worksheet
The last step is where I am stuck. Currently my code puts a few lines of data into a range in the worksheet, in the form of unrolled/transposed "key: value" entries, resulting in a horizontal data layout. The same range of data is always overwritten.
I want data in the form of a vertical layout, i.e., data in columns, just the same way as if the CSV file was imported with the import-file-wizard of MS Excel.
Is there a simpler way to do it than below?
I admit, some of the PowerShell features are pasted in here in a cargo-cult mode of programming. Please note that I have no PowerShell experience whatsoever. I did some batchfile, VBScript, and VBA coding a few years back. So, other criticisms are also welcome.
PARAM (
[Parameter(ValueFromPipeline = $true)]
$infile = ".\04-2011\110404-13.txt"
)
PROCESS {
echo " $infile"
Write-Host "Num Args:" $args.Length;
$xl = New-Object -comobject Excel.Application;
$xl.Visible = $true;
$Workbook = $xl.Workbooks.Add();
$content = Import-Csv -delimiter "`t" $infile;
$ports = $content | Select-Object Port# | Sort-Object Port# -Unique -Descending;
$ports | ForEach-Object {
$p = $_;
Write-Host $p.{Port#};
$Worksheet = $Workbook.Worksheets.Add();
$workSheet.Name = [string]::Format("{0} {1}", "PortNo", $p.{Port#});
$filtered = $content | Where-Object {$_.{Port#} -eq $p.{Port#} };
$filtered | ForEach-Object {
Write-Host $_.{ObsDateTime}, $_.{Port#}
}
$filtered | clip.exe;
$range = $Workbook.ActiveSheet.Range("a2", "a$($filtered.count)");
$Workbook.ActiveSheet.Paste($range, $false);
}
$xl.Quit()
}
Data Output Example
Wrong
Port# : 1
Obs# : 1
Exp_Flux : 0,99
IV Cdry : 406.96
IV Tcham : 16.19
IV Pressure : 100.7
IV H2O : 9.748
IV V3 : 11.395
IV V4 : 0.759
IV RH : 53.12
Right
Port# Obs# Exp_Flux IV Cdry IV Tcham IV Pressure IV H2O IV V3 IV V4 IV RH
1 1 0,99 406.96 16.19 100.7 9.748 11.395 0.759 53.12
Try Export-Xls, it looks very nice. Never had the chance to use it, but (virtually) knowing the person who worked on it, I'm sure you will be very happy to use it. If you'll go with it, please provide a feedback here will be appreciated.
POSSIBLE WORKAROUND FOR UNORDERED PROPERTIES IN Export-Xls
The function Add-Array2Clipboard could be changed so that it accepts a new input parameter: an array providing the name of the properties ordered as required.
Then the you can change the section where get-member is used. Silly example:
"z", "a", "c" | %{ get-member -name $_ -inputobject $thecurrentobject }
This is just an example on how you can achieve ordered properties from get-member.
I've used the $Workbook.ActiveSheet.Cells.Item($row, $col).Value2 function to more be able to pinpoint more precisely where to put the data when exporting to Excel.
Something like
$row = 1
Get-Content $file | Foreach-Object {
$cols = $_.split("`t")
for ($i = 0; $i < $cols.count; $i++)
{
$Workbook.ActiveSheet.Cells.Item($row, $i+1).Value2 = $cols[$i]
}
$row++
}
Warning: dry-coded! You'll probably need some try..catch as well.
I used a modified Export-Xls function, a bit different as User empo suggested.
This is my call to it
Export-Xls $filtered -Path $outfile -WorksheetName "$wn" -SheetPosition "end" | Out-Null # -SheetPosition "end";
However, the current release of Export-Xls re-orders the columns of the in-memory representation of the csv-text -file. I want the data columns of the text file in their original order, so I had to hack and simplify the original code as follows:
function Add-Array2Clipboard {
param (
[PSObject[]]$ConvertObject,
[switch]$Header
)
process{
$array = #();
$line =""
if ($Header) {
$line = #()
$row = $ConvertObject | Select -First 1
$row.psobject.properties | Foreach {$line += "$($_.Name)" }
$array += [String]::Join("`t", $line)
}
else {
foreach($row in $ConvertObject){
$line =""
$vals = #()
$row.psobject.properties | Foreach {$vals += $_.Value}
$array += [String]::Join("`t", $vals)
}
}
$array | clip.exe;
}
}

Resources