Powershell Issues Comparing two Arrays using Nested Foreach loop - powershell

I'am not able to have this script to working as expected. Please see below
i have two arrays $newusers and $oldusers with below data in each
$newusers = fadbd34|Alan Simon|Jones,ken A
fadbk45|Alice Lund|Dave,John h
fadoo78|Nathan Hugh|Trot,Carol M
fadt359|Jon Hart|Jones,Karen D
fafyl38|Miley Mcghee|Main,Josh D
abbrt86|Andrew Hayden|Mary,Martin G
frt5096|Andrew Cork|Kain,Martha E
ikka155|Andrew Mullen|Raymond, Gavin G
Note: Please observe the last 3 users from $newusers are not there in $oldusers
$oldusers = fadbd34|Alan Simon|11754
fadbk45|Alice Lund|11755
fadoo78|Nathan Hugh|11755
fadt359|Jon Hart|11755
fafyl38|Miley Mcghee|11732
Now, i'am trying to write a script that checks if the first field(Userid) from $newusers is traced in $oldusers
then join fields $newusers[0],$newusers[1],$oldusers[2], $newusers[2]into $Activeusers array and for the new userid's not found in $oldusers join $newusers[0], $newusers[1], $newusers[2] into $Inactiveusers array. I'am getting incorrect results. Below is so far i can came up with.
$Activeusers = #()
$Inactiveusers = #()
foreach ($nrow in $newusers) {
foreach ($orow in $oldusers){
($idNew,$newusrname,$mgr) = $newrow.split('|')
($idOld,$oldusrname,$costcntr) = $oldrow.split('|')
if ( $idOld[0] -ieq $idOld[0]){
$Activeusers += [string]::join('|',($idNew[0],$nusrname[1],$cstcntr[2],$mgr[2]))
} else {
$Inactiveusers += [string]::join('|',($idNew[0],$nusrname[1],$mgr[2]))
}
}
}

The issue is with how you are looping through the records. You are comparing the first record in the new users list with all of the list of users in the second list. This basic if/else statement causes you to get the following result. for ex.:
Loop 1: compare:
fadbd34 = fadbd34 -> Active User
Loop 2: compare:
fadbd34 = fadbk45 -> Inactive User
Loop 3: compare:
fadbd34 = fadoo78 -> Inactive User
...
This causes you to get 1 correct active user, and a list of 5 inactive users. Every time the user does not match a user in the old list, it stores it as an inactive user.
The code that I got working (After cleaning it up, removing the unnecessary array references (If you split the string, and store it in a variable, you don't need an array reference), fixing variable names, and changing the if statement to compare $idOld to $idNew) is this:
$newusers =
"fadbd34|Alan Simon|Jones,ken A",
"fadbk45|Alice Lund|Dave,John h",
"fadoo78|Nathan Hugh|Trot,Carol M",
"fadt359|Jon Hart|Jones,Karen D",
"fafyl38|Miley Mcghee|Main,Josh D",
"abbrt86|Andrew Hayden|Mary,Martin G",
"frt5096|Andrew Cork|Kain,Martha E",
"ikka155|Andrew Mullen|Raymond, Gavin G"
$oldusers =
"fadbd34|Alan Simon|Jones,ken A",
"fadbk45|Alice Lund|Dave,John h",
"fadoo78|Nathan Hugh|Trot,Carol M",
"fadt359|Jon Hart|Jones,Karen D",
"fafyl38|Miley Mcghee|Main,Josh D",
"abbrt86|Andrew Hayden|Mary,Martin G"
$Activeusers = #()
$Inactiveusers = #()
foreach ($nrow in $newusers) {
$Active = $false
($idNew,$newusrname,$mgr) = $nrow.split('|')
foreach ($orow in $oldusers){
($idOld,$oldusrname,$costcntr) = $orow.split('|')
if ( $idNew -ieq $idOld){
$Activeusers += [string]::join('|',($idNew,$nusrname,$costcntr,$mgr))
$Active = $true
}
}
if (!$Active)
{
$Inactiveusers += [string]::join('|',($idNew,$newusrname,$mgr))
}
}

Related

Sort a nested hash table by value

I have a hash array as such:
$weeklyStats[$RecipientName][$weekNr][$total]
Which is created in a loop as such:
$weeklyStats = #{}
$weekNr = get-date -UFormat %V
ForEach ($RecipientName in $MailTraffic.keys)
{
$weeklyStats[$RecipientName] = #{}
$weeklyStats[$RecipientName][$weekNr] = #{}
$weeklyStats[$RecipientName][$weekNr]['Total'] = 0
$weeklyStats[$RecipientName][$weekNr]['Sent'] = 0
$weeklyStats[$RecipientName][$weekNr]['Received'] = 0
foreach($item in $MailTraffic[$RecipientName].keys)
{
weeklyStats[$RecipientName][$weekNr]['Total'] =+ 1
if $MailTraffic[$RecipientName]['transaction'] == "Sent"
{
$weeklyStats[$RecipientName][$weekNr]['Sent'] =+ 1
}
else
{
$weeklyStats[$RecipientName][$weekNr]['Received'] =+ 1
}
}
}
I don't know how to 'dump' a variable in Powershell but here is the contents in json:
{
"mike": {
"11": {
"Total": 411,
"Sent": 21,
"Received":390,
}
},
"peter": {
"11": {
"Total": 751,
"Sent": 51,
"Received":700,
}
},
"frank": {
"11": {
"Total": 620,
"Sent": 20,
"Received":600,
}
},
}
I want to print out the keys and values in descending order of the $total.
I can only find examples how to do it if the hash table is only one level deep.
The intended output would be:
Name Total Received Sent
----- ----- ----- -----
peter 751 700 51
frank 620 600 20
mike 411 390 21
Sort by referencing the Keys property of the inner hashtable, then assign to a new [ordered] dictionary:
$sorted = [ordered]#{}
$stats.GetEnumerator() |Sort-Object {
# Sort by first key from each inner hashtable
$_.Value.Keys |Select -First 1
} -Descending |ForEach-Object {
# re-assign to our ordered dictionary
$sorted[$_.Key] = $_.Value
}
$sorted now contains your new sorted dictionary
Most PowerShell cmdlets are intended to handle (stream!) [PSObject] type (which includes a [PScustomerObject] type) lists for input and output.
(To understand the difference see e.g. Difference between PSObject, Hashtable, and PSCustomObject).
Nested hash tables are difficult to maintain and handle in PowerShell (see also: Powershell Multidimensional Arrays) because PowerShell is optimized for streaming which is rather difficult with cascaded objects, therefore I recommend you convert you nested hashtable in a (rather flat) [PScustomerObject] list, something like:
$PSStats =
ForEach ($name in $Stats.Keys) {
ForEach ($weekNr in $_.Keys) {
ForEach ($total in $_.Keys) {
[pscustomobject]#{name = $name; weekNr = $weekNr; total = $total}
}
}
}
Once you have converted it into PSCustomObject list, you can easily sort it and display the results:
$PSStats | Sort-Object Total
I would just create a custom object from your hash tables and then sort on the Title property:
# Creation of $mailtraffic
$mailtraffic = #{'Mike' = #{'Total' = 411; 'Sent' = 21; 'Received' = 390};'Peter' = #{'Total' = 751; 'Sent' = 51; 'Received' = 700};'Frank' = #{'Total' = 620; 'Sent' = 20; 'Received' = 600}}
# Sorting Code
$mailtraffic.GetEnumerator() |
Select #{n='Name';e={$_.Key}},#{n='Total';e={$_.Value.Total}},#{n='Received';e={$_.Value.Received}},#{n='Sent';e={$_.Value.Sent}} |
Sort Total -Descending

Odd and even pages footer - page X of Y in powershell

I would like to generate word documents in Powershell with different footer on even and odd pages.
I would like to have text with data on left side, and Page X of Y on right side on one page and reverse combination on next page.
First problem is in X of Y format. And second problem I have with placing text with field in one footer. If I put field, the text was disappear, and when I put text, field was disappearing.
PowerShell add field codes to ms word footer - does not work in my case.
I will be grateful for your help.
$dat = Get-Date -Format yyyy-MM-dd
$word = New-Object -ComObject word.application
$word.Visible = $false
$doc = $word.documents.add()
$doc.PageSetup.OddAndEvenPagesHeaderFooter = $true
$selection = $word.Selection
# ...
# content
# ...
$section = $doc.sections.item(1)
$footer = $section.Footers(1)
$Range = $footer.Range
$Range.Text = "Some text($dat)"
$Range.ParagraphFormat.Alignment = 0
$footer.PageNumbers.Add(2)
$Range.Font.Size = 10
$footer = $section.Footers(3)
$Range = $footer.Range
$Range.Text = "Some text($dat)"
$Range.ParagraphFormat.Alignment = 2
$footer.PageNumbers.Add(0)
$Range.Font.Size = 10
$outputPath = 'C:\FileToDocx.docx'
$doc.SaveAs($outputPath)
$doc.Close()
$word.Quit()
The problem is also that the $footer.PageNumbers.Add() is global and it does not depend from my odd and even footer range.
Also I was tried resolve my problem by swap PageNumbers to combination of $Range.Fields.Add($Range, 26) and $Range.Fields.Add($Range, 33), e.g.
$fieldsPage = $Range.Fields.Add($Range, 33)
$sumField = $fieldsPage.Result.Text
$fieldsNumPages = $Range.Fields.Add($Range, 26)
$sumField += ' of ' + $fieldsNumPages.Result.Text
$range.Text = "Some text($dat)`t`tPage $sumField"
but in this case I have static string. I don't know how to use this two type of fields with static text with $dat in footer without conversion to string. The footer forces me to use fields, because only they can be different on each page.

Declare a here-string containing variables outside of a loop

I would like to declare a here-string outside of a loop use that string in the loop where the variables get resolved.
My ideal scenario would look like below. This doesn't work as Powershell evaluates the string one time before entering the loop instead of each time inside the loop kind of obvious but bitten by it nevertheless.
$number = "Number $($_)"
1..2 | % { $number }
I know I can use one of these solutions
1..2 | % { "Number $($_)" }
$number = "Number {0}"
1..2 | % { $number -f $_ }
$number = "Number <replace>"
1..2 | % { $number -replace "<replace>", "$_" }
but they have drawbacks I'd like to avoid
Due to the size of the string, declaring it inside the loop obfuscates the logic of the loop making the code less readable.
The formatting solution is too easy to get wrong when many variables are involved.
In the replace solution it's easier to match what get's replaced by what variable but I would have to chain many replace commands.
Edit
Rereading my own question makes it obvious that the actual use case is missing from the question.
Note that ultimately I ended up choosing the formatting option
Following would declare the template with some variables that need replacing in a loop
$sqltemplate = #"
SELECT aud.dpt_mov_hex||aud.dpt_ref||aud.can_typ||TO_CHAR(aud.dte_aud-1,'YYYYMMDD')||'000001' transaction_id,
acc.dos_nbr contract_id, acc.pay_acc_nbr account_id,
CASE WHEN NULL IS NULL THEN unt.nam_unt ELSE unt.nam_unt||'<'||NULL ||'>' END product_id,
aud.dpt_ref, aud.dpt_mov_hex, aud.dpt_mov_dte uitwerkingsdatum,
CASE WHEN can_typ = 0 THEN 'VZ'||aud.dpt_mov_ven_typ ELSE 'VZ'||aud.dpt_mov_ven_typ||'-CR' END transactietype,
aud.dpt_mov_amt_eur bedrag_in_eur, aud.dte_cnv, aud.dpt_mov_fix_eur, aud.dpt_mov_con_inc, aud.dpt_mov_amt_sgn bedrag_teken,
aud.dpt_mov_amt_unt bedrag_in_units, aud.dpt_mov_amt_rte, aud.dpt_mov_amt_val_pre, aud.dpt_mov_amt_val_aft,
aud.dpt_mov_amt_ioc, aud.dte_exe verwerkingsdatum, aud.exe_mng, aud.cmt, aud.trn_nbr, aud.dte_aud datum_aanlevering, aud.can_typ
FROM lfe_dpt_mov_aud aud, vnv_isr_pay_acc acc, vnv_bel_unt unt
WHERE aud.dte_aud >= TO_DATE('$((Get-Date).ToString('dd.MM.yyyy'))', 'DD.MM.YYYY')
AND aud.dpt_ref = '{0}'
AND acc.pay_acc_nbr = '{1}'
AND unt.inv_unt = '{2}'
UNION
SELECT aud.dpt_mov_hex||aud.dpt_ref||aud.can_typ||TO_CHAR(aud.dte_aud-1,'YYYYMMDD')||'000001' transaction_id,
acc.dos_nbr contract_id, acc.pay_acc_nbr account_id,
CASE WHEN itr_rte IS NULL THEN unt.nam_unt ELSE unt.nam_unt||'<'||itr_rte ||'>' END product_id,
aud.dpt_ref, aud.dpt_mov_hex, aud.dpt_mov_dte uitwerkingsdatum,
CASE WHEN can_typ = 0 THEN 'VZ'||aud.dpt_mov_ven_typ ELSE 'VZ'||aud.dpt_mov_ven_typ||'-CR' END transactietype,
aud.dpt_mov_amt_eur bedrag_in_eur, aud.dte_cnv, aud.dpt_mov_fix_eur, aud.dpt_mov_con_inc, aud.dpt_mov_amt_sgn bedrag_teken,
aud.dpt_mov_amt_unt bedrag_in_units, aud.dpt_mov_amt_rte, aud.dpt_mov_amt_val_pre, aud.dpt_mov_amt_val_aft,
aud.dpt_mov_amt_ioc, aud.dte_exe verwerkingsdatum, aud.exe_mng, aud.cmt, aud.trn_nbr, aud.dte_aud datum_aanlevering, aud.can_typ
FROM lfe_dpt_mov_aud aud, vnv_dpt dpt, vnv_isr_pay_acc acc, vnv_bel_unt unt
WHERE aud.dpt_ref = dpt.dpt_ref
AND dpt.pay_acc = acc.pay_acc_nbr
AND dpt.inv_unt = unt.inv_unt
AND aud.dte_aud >= TO_DATE('$((Get-Date).ToString('dd.MM.yyyy'))', 'DD.MM.YYYY')
AND acc.pay_acc_nbr = '{1}'
AND unt.inv_unt = '{2}'
UNION
"#
and this template would get used in a statement such as this
$rolledbackMatchs is an array of custom object containing the three properties: dtp_ref, pay_acc_nbr and inv_unt.
$rolledbackMatches | ForEach-Object { $sqltemplate -f $_.dpt_ref, $_.pay_acc_nbr, $_.inv_unt }
Couple of approaches come to mind:
dot source here-string assignment from a separate file:
# loop.variables.ps1
$myVar = #"
Stuff going on with $_ in here
"#
and then in the loop itself:
1..2 | % { . .\loop.variables.ps1; <# do stuff with $myVar here #> }
Manually invoke string expansion:
$hereString = #'
Stuff (not yet) going on with $_ in here
'#
1..2 | % { $myVar = $ExecutionContext.InvokeCommand.ExpandString($hereString) }
Wrap it in a scriptblock
(as suggested by PetSerAl)
$stringBlock = {
#"
Stuff going on with $_ in here
"#
}
1..2 | % { $myVar = &$stringBlock}
I'm struggling to understand what you're trying to achieve here.
For a start you never define a here-string you just define $number as a string
A here-string would look like this
$number = #"
Number 4
"#
if all you're trying to do is push a number into a string try this
foreach ($number in (1..3)){
"Number $number"
}
which is close to your desired option and less ambiguous

Powershell hashtable with multiple values and one key

Im looking for a data structure/cmdlet that will allow me to add multiple values to a single key in Powershell.
My data would ideally look like this:
KEY-------------------------- VALUES
HOSTNAME1-------------DATABASE1,DATABASE2,DATABASE3
HOSTNAME2-------------DATABASE1,DATABASE2
etc...
I thought a hashtable would do the trick, but I'm unable to do the following:
$servObjects = #{}
$servObjects.Add("server1", #())
$servObjects.get_item("server1") += "database1"
This yields an empty array when I try:
$servObjects.get_item("server1")
I have also tried to do the following, hoping that powershell would understand what I want:
$servObjects2 = #{}
$servObjects2.add($servername, $databasename)
This will unfortunately yield a duplicate key exception
Thanks for any and all input
You basically want a hash table with values that are arrays. You don't have to use $hashtable.get_item or .add
$myHashTable = #{} # creates hash table
$myHashTable.Entry1 = #() #adds an array
$myHashTable.Entry1 += "element1"
$myHashTable.Entry1 += "element2"
This results in the following output:
$myHashTable
Name Value
---- -----
Entry1 {element1, element2}
$myHashTable.Entry1
element1
element2
If you have your data in an array you can group the array and convert to a hash table:
$ary = #()
$ary = $ary + [PSCustomObject]#{RowNumber = 1; EmployeeId = 1; Value = 1 }
$ary = $ary + [PSCustomObject]#{RowNumber = 2; EmployeeId = 1; Value = 2 }
$ary = $ary + [PSCustomObject]#{RowNumber = 3; EmployeeId = 2; Value = 3 }
$ary = $ary + [PSCustomObject]#{RowNumber = 4; EmployeeId = 2; Value = 4 }
$ary = $ary + [PSCustomObject]#{RowNumber = 5; EmployeeId = 3; Value = 5 }
$ht = $ary | Group-Object -Property EmployeeId -AsHashTable
$ht is then:
Name Value
---- -----
3 {#{RowNumber=5; EmployeeId=3; Value=5}}
2 {#{RowNumber=3; EmployeeId=2; Value=3}, #{RowNumber=4; EmployeeId=2; Value=4}}
1 {#{RowNumber=1; EmployeeId=1; Value=1}, #{RowNumber=2; EmployeeId=1; Value=2}}
In your original example, instead of writing
$servObjects.get_item("server1") += "database1"
you had written
$servObjects.server1 += "database1"
it would have worked.
I'm very new to PowerShell, but I prefer to use
$servObjects.Add("key",#())
over
$servObjects.key = #())
because the .Add will throw a duplicate exception if the key is already present in the hashtable, whereas the assignment will replace an existing entry with a new one. For my purposes, I have found that the implicit replacement is (more often than not) an error, either in my logic, or an anomaly in the input data that needs to be handled.
If you know the value at creation time, it would be clearer this way :
[hashtable]$hash = #{
HOSTNAME1 = #(DATABASE1, DATABASE2, DATABASE3);
HOSTNAME2 = #(DATABASE1, DATABASE2);
}
Which will get you the following :
Name Value
---- -----
HOSTNAME2 {DATABASE1, DATABASE2}
HOSTNAME1 {DATABASE1, DATABASE2, DATABASE3}

PowerShell HashTable - self referencing during initialization

I have a theoretical problem - how to reference a hash table during its initialization, for example, to compute a member based other already stated members.
Remove-Variable myHashTable -ErrorAction Ignore
$myHashTable =
#{
One = 1
Two= 2
Three = ??? # following expressions do not work
# $This.One + $This.Two or
# $_.One + $_.Two
# $myHashTable.One + $myHashTable.Two
# ????
}
$myHashTable.Three -eq 3 # make this $true
Any ideas how to do it? Is it actually possible?
Edit:
This was my solution:
$myHashTable =
#{
One = 1
Two= 2
}
$myHashTable.Three = $myHashTable.One + $myHashTable.Two
This won't be possible using the object initializer syntax I'm afraid. While it is possible to use variables, you'll have to compute the values before creating the object.
I cannot recommend this, but you can iterate the initializer twice or more:
(0..1) | %{
$a = #{
One = 1
Two = $a.One + 1
}
}
(0..2) | %{
$b = #{
One = 1
Two = $b.One + 1
Three = $b.Two + 1
}
}
Make sure all calculations are idempotent, i.e. do not depend on a number of iterations.
You can also recur to this...
sometimes when the hashtable is very long
and can be defined only in 2 or three recurrences...
works fine:
$AAA = #{
DAT = "C:\MyFolderOfDats"
EXE = "C:\MyFolderOfExes"
}
$AAA += #{
Data = $AAA.DAT + "\#Links"
Scripts = $AAA.EXE + "\#Scripts"
ScriptsX = $AAA.EXE + "\#ScriptsX"
}
Note in the second part we are just adding ( += ) more items to the first part... but now... we can refer the items in first part
of the hashtable