PowerShell - select number with decimal separator (DB2 SQL) - powershell

Cannot figure out how to contain decimal separator when selecting DB2 data with PowerShell.
DB2 table contains column with item price:
+------+---------+
| Item | Price |
+------+---------+
| A | 99,104 |
| B | 27,05 |
| C | 320,001 |
+------+---------+
This is part from Powershell script which gets this data:
$SQL = "SELECT Item, Price FROM Inventory"
$connection = New-Object System.Data.Odbc.OdbcConnection
$connection.ConnectionString = "DSN=$DNS;UID=$USERNAME;password=$PASSWORD"
$connection.open() | Get-Item -ErrorAction Stop
$cmd = New-object System.Data.Odbc.OdbcCommand($SQL,$connection)
$result = New-Object system.Data.DataSet
(New-Object system.Data.odbc.odbcDataAdapter($cmd)).fill($result) # here comma gets removed from Price
$connection.close()
$result.Tables[0] | Export-Csv -NoTypeInformation -Delimiter -Encoding UTF8 $OutputFile
This somehow selects data without decimals which is incorrect - prices are now enourmously high:
99104
2705
320001
I though that comma is removed during Export-Csv so added -UseCulture, but result is the same. It appears that comma is removed when data is selected:
New-Object system.Data.odbc.odbcDataAdapter($cmd)
My question is how can I fix this? Is there additional parameter or something is missing here?

I cant place a comment yet.
As others asked, what is the datatype for you price column at the database? Per your output it's left justified, so it does not seems to be a numeric type.
Making a simple test here with PRODUCT table from db2sample database:
And, also, you may try to use IBM.Data.Db2 .Net provider instead of using ODBC.
$dbFactory = [System.Data.Common.DbProviderFactories]::GetFactory('IBM.Data.DB2')
$connection = $dbFactory.CreateConnection()
$connection.ConnectionString = "Database=SAMPLE"
$connection.Open()
$da = $dbFactory.CreateDataAdapter()
$ds = new-object "System.Data.DataSet"
$cmd = $dbFactory.CreateCommand()
$cmd.Connection = $connection
$cmd.CommandText = "SELECT PID, PRICE FROM PRODUCT"
$da.SelectCommand = $cmd
$da.Fill($ds)
$ds.Tables[0]
Produces the expected decimal format.
PID PRICE
--- -----
100-100-01 9,99
100-101-01 19,99
100-103-01 49,99
100-201-01 3,99
$ds.Tables[0].Columns[1].DataType
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Decimal System.ValueType

Related

Exporting List nested lists with custom objects to csv not working

I have the following powershell code:
$data = #{};
// code to populate data, sample:
$listData = New-Object System.Collection.Generic.List[object];
$listData.Add([PSCustomObject]#{Id = 1, Name = "Employee1"});
$data.Add("KEY1", $listData);
$data.Values | Export-Csv -Path "path of file"
The result is not as expected, I get information about the the list Capacity, count, if readonly....
There were two typos in the question, but the basic idea works fine:
$data = #{}
$listData = New-Object System.Collections.Generic.List[object]
#^ missing s
$listData.Add([PSCustomObject]#{Id = 1; Name = "Employee1"})
#^ hash tables are semicolon-separated
$data.Add("KEY1", $listData)
$data.Values | Export-Csv -Path "path of file"
# outputs:
Id Name
-- ----
1 Employee1

Format-Table not taking effect (Exchange - powershell)

first of all sorry if my english is not the best. but ill try to explain my issue with as much detail as i can
Im having an issue where i cant get Format-Table to effect the output i give it.
below is the part im having issues with atm.
cls
$TotalSize = $($mailboxes. #{name = ”TotalItemSize (GB)”; expression = { [math]::Round((($_.TotalItemSize.Value.ToString()).Split(“(“)[1].Split(” “)[0].Replace(“,”, ””) / 1GB), 2) } });
$UserN = $($mailboxes.DisplayName)
$itemCount = $($mailboxes.ItemCount)
$LastLogonTime = $($mailboxes.ItemCount)
$allMailboxinfo = #(
#lager dataen som skal inn i et objekt
#{Username= $UserN; ItemCount = $itemCount; LastLogonTime = $($mailboxes.ItemCount); Size = $TotalSize}) | % { New-Object object | Add-Member -NotePropertyMembers $_ -PassThru }
$Table = $allMailboxinfo | Format-Table | Out-String
$Table
the output of this gives me what almost looks like json syntax below each title of the table.
Username LastLogonTime ItemCount Size
-------- ------------- --------- ----
{username1, username2,username3,userna...} {$null, $null, $null, $null...} {$null, $null, $null, $null...} {$null, $null, $null, $null...}
running the commands by themselves seem to work tho. like $mailboxes.DisplayName gives the exact data i want for displayname. even in table-format.
the reason im making the table this way instead of just using select-object, is because im going to merge a few tables later. using the logic from the script below.
cls
$someData = #(
#{Name = "Bill"; email = "email#domain.com"; phone = "12345678"; id = "043546" }) | % { New-Object object | Add-Member -NotePropertyMembers $_ -PassThru }
$moreData = #(
#{Name = "Bill"; company = "company 04"}) | % { New-Object object | Add-Member -NotePropertyMembers $_ -PassThru }
$Merge = #(
#plots the data into a new table
#{Name = $($someData.Name); e_mail = $($someData.email); phone = $($someData.phone); id = $($someData.id); merged = $($moreData.company) }) | % { New-Object object | Add-Member -NotePropertyMembers $_ -PassThru }
#formatting table
$Table = $Merge | Format-Table | Out-String
#print table
$Table
if you are wondering what im doing with this.
My goal, all in all. is a table with using the info from Exchange;
DisplayName, TotalItemSize(GB), ItemCount, LastLogonTime, E-mail adress, archive + Maxquoata, Quoata for mailbox.
You're creating a single object where each property holds an array of property values from the original array of mailbox objects.
Instead, create 1 new object per mailbox:
# construct output objects with Select-Object
$allMailBoxInfo = $mailboxes |Select #{Name='Username';Expression='DisplayName'},ItemCount,#{Name='LastLogonTime';Expression='ItemCount'},#{Name='Size';Expression={[math]::Round((($_.TotalItemSize.Value.ToString()).Split("(")[1].Split(" ")[0].Replace(",", "") / 1GB), 2) }}
# format table
$Table = $allMailBoxInfo | Format-Table | Out-String
# print table
$Table

Combining two commands into one and exporting to csv file in Powershell

Below is the code I'm using get data from the output of two commands, I then put them into two separate array's. When I combine the arrays the output looks how I would expect, but when I do select and try to output, it has gaps and not formatted correct. How get I get this to output nice to a csv file?
Example code:
$a = get-agentserver
$NewCSV = $a | ForEach-Object {
New-Object PSObject -Prop #{
'Client Name' = ($_."Name" -Split '\.(?!\d)')[0]
'Policy Type' = $_."AgentServerType"
'Backup State' = $_."BackupStatus"
'logon' = $_."LogonAccountTestStatus"
'account' = $_."LogonAccount"
}
} | Select "Client Name","Policy Type","Backup State","logon","account"
#$NewCSV
$l = foreach($i in $a.name){
get-definition -agentserver $i}
$l | convertto-csv | out-file t1.csv
$m = import-csv t1.csv | select agentserver,name,selectionsummary
$defcsv = $m | foreach-object{
new-object psobject -prop #{
'Policy Name' = $_.Name
'Backup Selection' = $_.selectionsummary
}
} | select "Policy Name","Backup Selection"
#$defcsv
$hope = $NewCSV + $defcsv
$hope2 = $hope | select "Client Name","Policy Name","Policy Type","Backup Selection"
$hope2
Ex output $hope(that look right to me)
Client Name : Name
Policy Type : Ndmp
Backup State : Unknown
logon : Succeeded
account : ndmp_user
Policy Name : Diff Bakcup
Backup Selection : COMMON, D: (Partial)
Ex output of $hope2(which is killing me how to fix)
Client Name Policy Name Policy Type Backup Selection
----------- ----------- ----------- ----------------
Name Windows
Name Windows
Name Windows
Name Windows
Name Windows
Name Ndmp
Diff Bakcup - Name ,... COMMON, D: (Partial)
ArchiveJob_Backup_to_Tape Name \e$ (Partial), ...
Diff Bakcup - Name ,... COMMON, D: (Partial)
ArchiveJob_Backup_to_Tape Name\e$ (Partial), ...
Diff Bakcup - Name ,... COMMON, D: (Partial)
Name Backup BLR_Pro... /root_vdm/IN-BLR400-FS-C...
I have cleaned up my code and tried to put my command outputs into one variable and iterate through it in one go, which looks much nicer, but the output result in the same as above in my $hope2 output. It is leaving a big gap under two of the header "Policy Name" and "Backup Selection". Is there a way to use regex to remove those particular spaces only under those two columns in Powershell?
This is the new code I am running using
$agentserver = get-agentserver
$agentserver | convertto-csv | select-object -skip 2 | out-file t2.csv
$agentserver = import-csv t2.csv -Header server,id,type,accountstate,logonaccount
$budefinition = foreach($i in $a.name){
get-backupdefinition -agentserver $i}
$budefinition | convertto-csv | out-file t1.csv
$converted_budef = import-csv t1.csv | select agentserver,name,selectionsummary
$a = $agentserver + $converted_budef
$NewCSV = $a | ForEach-Object {
New-Object PSObject -Prop #{
'Client Name' = ($_."server" -Split '\.(?!\d)')[0]
'Policy Type' = $_."type"
'Backup State' = $_."BackupStatus"
'logon' = $_."LogonAccountTestStatus"
'account' = $_."LogonAccount"
'Policy Name' = ($_.Name -replace ","," ")
'Backup Selection' = ($_.selectionsummary -replace ","," ")
}
} | Select "Client Name","Policy Name","Policy Type","Backup Selection"
$NewCSV
Example of what I am trying to accomplish would look like this, that I can then use the export-csv and have a nice csv doc.
Client Name Policy Name Policy Type Backup Selection
----------- ----------- ----------- ----------------
NAME Diff Bakup Windows Common D
NAME Archive Ndmp /root_vdm/
After doing $NewCSV | fl I get a output of two separate list as shown below and I need them to all be in one. Any ideas how to fix it in my code above?
Client Name : Name
Policy Name :
Policy Type : Ndmp
Backup Selection :
Client Name :
Policy Name : Diff Bakcup
Policy Type :
Backup Selection : COMMON D: (Partial)

Convert sql Collection to String in Powershell

I've been trying to pull data from a sql query and get it converted to HTML to finally embed the results in an email body.
My code is as follows;
$SQLCommand = New-Object System.Data.SqlClient.SqlCommand
$SQLCommand.CommandText = "SELECT DISTINCT SYS.Name,LDISK.DeviceID0,LDISK.Size0 AS DiskSizeMB,LDISK.FreeSpace0 AS FreeSpaceMB,SCCM.dbo.v_GS_WORKSTATION_STATUS.LastHWScan,SCCM.dbo.v_GS_LastSoftwareScan.LastScanDate
FROM v_FullCollectionMembership_Valid SYS
JOIN v_GS_LOGICAL_DISK LDISK ON SYS.ResourceID = LDISK.ResourceID
INNER JOIN SCCM.dbo.v_GS_WORKSTATION_STATUS
ON LDISK.ResourceID = SCCM.dbo.v_GS_WORKSTATION_STATUS.ResourceID
INNER JOIN SCCM.dbo.v_GS_LastSoftwareScan
ON SCCM.dbo.v_GS_LastSoftwareScan.ResourceID =
SCCM.dbo.v_GS_WORKSTATION_STATUS.ResourceID
WHERE
LDISK.DeviceID0 = 'C:' AND
LDISK.DriveType0 = 3 AND
((LDISK.FreeSpace0 <= ((LDISK.Size0 * 10) / 100)) OR
(LDISK.FreeSpace0 <= 1024)) AND
SYS.CollectionID = 'SMS00001'
ORDER BY
SYS.Name"
$SQLCommand.Connection = $SQLConnection
$SQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SQLCommand
$SQLDataset = New-Object System.Data.DataSet
$SqlAdapter.fill($SQLDataset) | out-null
$FileInfo = $SQLDataset.tables | FT -AutoSize
The resulting format of the data stored in $FileInfo looks good;
Name DeviceID0 DiskSizeMB FreeSpaceMB LastHWScan LastScanDate
---- --------- ---------- ----------- ---------- ------------
Server01 C: 53244 2010 7/28/2017 3:18:01 PM 7/28/2017 5:25:51 AM
...however when I pipe this to ConvertTo-HTML ($FileInfo | ConvertTo-HTML) the resulting format comes out like this;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML TABLE</title>
</head><body>
<table>
<colgroup><col/><col/><col/><col/><col/><col/></colgroup>
<tr><th>ClassId2e4f51ef21dd47e99d3c952918aff9cd</th><th>pageHeaderEntry</th><th>pageFooterEntry</th><th>autosizeInfo</th><th>shapeInfo</th><th>groupingEntry</th></tr>
<tr><td>033ecb2bc07a4d43b5ef94ed5a35d280</td><td></td><td></td><td>Microsoft.PowerShell.Commands.Internal.Format.AutosizeInfo</td><td>Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo</td><td></td></tr>
<tr><td>9e210fe47d09416682b841769c78b8a3</td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td>27c87ef9bbda4f709f6b4002fa4af63c</td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td>27c87ef9bbda4f709f6b4002fa4af63c</td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td>27c87ef9bbda4f709f6b4002fa4af63c</td><td></td><td></td><td></td><td></td><td></td></tr>
When I look at the type of my $FileInfo I get this;
$FileInfo.GetType();
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
...so I suspect that the ConvertTo-HTML module is looking for input in string format however I can't seem to get this to work properly - even after trying options like $FileInfo | Out-String -Stream
I want to believe that this can be done easily - I just can't find the right approach. Thanks in advance!
Remove format-table, use select with exlude not necessary option with first table, try this
$SQLDataset.tables[0] |
select * -ExcludeProperty RowError, RowState, HasErrors, Name, Table, ItemArray |
ConvertTo-Html

Formatting Powershell output from stored procedure

I'm running into a small issue trying to get the output from a stored procedure into a text file via. Powershell.
#Connection Object
$cn = New-Object System.Data.SqlClient.SqlConnection(
"Data Source=localhost; Database=test;User ID=test;Password=xyzzy;"
)
$q = "exec usp_Users"
#Data Adapter which will gather the data using our query
$da = New-Object System.Data.SqlClient.SqlDataAdapter($q, $cn)
#DataSet which will hold the data we have gathered
$ds = New-Object System.Data.DataSet
#Out-Null is used so the number of affected rows isn't printed
$da.Fill($ds) >$null| Out-Null
#Close the database connection
$cn.Close()
if($ds.Tables[0].Rows.Count -eq 0){
write-host '0:No Data found'
exit 2
}
$file = "C:\temp\" + "users" + $(Get-Date -Format 'MM_dd_yyyy') + ".txt"
$ds.Tables[0] | out-File $file -encoding ASCII -width 255
Here is the output:
Column1
-----
USER_NAME,USER_TYPE
test#spamex.com,MasterAdministrator
foo#hotmail.com,UserAdministrator
test4#test.com,Users
How can I get rid of the 'Column1' and the underline?
select-object with expanded property might help:
ds.Tables[0] | Select-Object -expand Column1 | out-file..
You can export a datatable directly into a csv file by using export-csv:
$ds.Tables[0] | export-csv tofile.csv -notypeinformation