Sqrt method returns 0 - powershell

I need a method which returns the standard deviation of the last access time in a folder. Here is the code:
function standardDeviation {
Param(
[Parameter(Mandatory=$true)]
[String]$tPath
)
$moy = moyAge $tPath
$variance = 0
$nbFiles = 1
dir | ForEach-Object {
if (!($_.PsIsContainer)) {
$nbDays = $_.LastAccessTime
$nbDays = $nbDays.Days
$sq = $nbDays - $moy
$sq = $sq*$sq
$variance += $sq
$nbFiles++
}
}
$variance = $variance / $nbFiles
$variance = [math]::sqrt($variance)
}
I don't know why, but it always returns 0. Does someone know why?
(moyAge works, and returns an int (number of days))

Your function doesn't actually return anything, so any call will "return" $null. Either change
$variance = [math]::sqrt($variance)
to
[math]::sqrt($variance)
or add a line
$variance
or
return $variance
at the end of the function.
Also, as #MathiasRJessen pointed out, DateTime objects don't have a Days property. If you want the difference in days between today and a specific date you need to calculate a timespan first:
$nbDays = ((Get-Date).Date - $_.LastAccessTime.Date).Days

Related

What is the correct IP address conversion from number?

I am trying to convert number into IP address using powershell method and checking same online, I am getting 2 different result.
Example:
number = 16812043
result1 = 11.136.0.1 #using powershell
result2 = 1.0.136.11 #https://codebeautify.org/decimal-to-ip-converter
I have tried below code
function Convert-NumberToIP
{
param(
[Parameter(Mandatory=$true)][string]$number
)
[Int64] $numberInt = 0
if([Int64]::TryParse($number, [ref]$numberInt))
{
if(($numberInt -ge 0) -and ($numberInt -le 0xFFFFFFFFl))
{
([IPAddress] $numberInt).ToString()
}
}
}
Convert-NumberToIP -number 16812043
I am getting 2 different result not sure which 1 is correct, or should I update the function.
Use the IPAddress.NetworkToHostOrder() method to flip the endianness of the octets represented by your decimal number:
PS ~> [ipaddress]::new([ipaddress]::NetworkToHostOrder(16812043)).IPAddressToString
1.0.136.11

Is it possible to use with and endwith instructions?

I am translating vba code to PowerShell
Does with and endwith exist in PowerShell?
What is the alternative?
Could you give me an example?
The VBA With ... End With statement is just a shorthand syntax - see With...End With Statement (Visual Basic):
With objectExpression
[ statements ]
End With
So, for example this VBA script:
With MyVar
.PropertyX = 100
.PropertyY = "myvalue"
.MyMethod()
End With
is equivalent to this VBA script:
MyVar.Property = 100
MyVar.PropertyY = "myvalue"
Myvar.MyMethod()
which translates simply to this in PowerShell:
$myVar.PropertyX = 100
$myVar.PropertyY = "myvalue"
$myvar.MyMethod()
However, if the objectExpression is a longer expression you can just assign it to a temporary variable:
With MyVar.MyProperty.MyOtherProperty
.PropertyX = 100
.PropertyY = "myvalue"
.MyMethod()
End With
becomes this instead in VBA:
MyTempVar = MyVar.MyProperty.MyOtherProperty
MyTempVar.PropertyX = 100
MyTempVar.PropertyY = "myvalue"
MyTempVar.MyMethod()
which translates to PowerShell as follows:
$myTempVar = $myVar.MyProperty.MyOtherProperty
$myTempVar.PropertyX = 100
$myTempVar.PropertyY = "myvalue"
$myTempVar.MyMethod()
Best alternative in Powershell:
foreach ($_ in $MyVar) {
$_.PropertyX = 100
$_.PropertyY = "myvalue"
$_.MyMethod()
}
At least I like it...

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 - 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

This code kills the page

I have a function
makeMarks: (first, nextIncrement, classifier) ->
results = new Array()
t = first(#minT)
while t<=#maxT
mark =
t: t
x: this.tToX(t)
class: classifier(t)
results.push(mark)
t = nextIncrement(t)
results
this function works great with the following two functions as parameters
# parameters for hour tickmarks
#firstHour = (t) ->
msPerHour = 1000*60*60
Math.floor(t / msPerHour) * msPerHour
#nextHour = (currentHour) ->
msPerHour = 1000*60*60
currentHour + msPerHour
when called as such
marks = markMaker.makeMarks( #firstMonth, #nextMonth, #classifier)
Now to the problem:
# parameters for month tickmarks
#firstMonth = (minT) ->
msPerDay = 1000*60*60*24
t = Math.floor(minT/msPerDay) * msPerDay
d = new Date(t)
while(d.getDate() isnt 0)
t += msPerDay
d.setTime(t)
t
#nextMonth = (currentMonth) ->
msPerDay = 1000*60*60*24
t = currentMonth + msPerDay
d = new Date(t)
while(d.getDate() isnt 0)
t += msPerDay
d.setTime(t)
t
The hour code works fine, but the month code doesn't seem to terminate.
The getDate function never returns 0. Its minimum value is 1 and it's maximum value is 31. If you're looking for anything outside that range, that's a long wait for a train that don't come.