Powershell studio datagridview if statement - powershell

I have a cellpainting event and am trying to correct/clean this IF statement up. I think I'm getting lost in my parenthess. Is someone able to take a second look at this? Thanks for your time.
My end goal is the IF statemant to be: Column 1 date older than 42 days or not $null and column 4 value = "SEP"
$datagridview1_CellPainting=[System.Windows.Forms.DataGridViewCellPaintingEventHandler]{
$SEPreturnlimit = "{0:MM/dd/yyyy}" -f (get-date).AddDays(-42)
if ((($_.ColumnIndex -eq 1 -and ([datetime]$_.Value -le $SEPreturnlimit -and [datetime]$_.Value.ToString() -ne $null))) -and ($datagridview1.rows .Cells[4].Value -eq "SEP")) #Column 1 date older than 42 days or not $null **and** column 4 value = "SEP"
{
$this.Rows[$_.RowIndex] | %{ $_.DefaultCellStyle.BackColor = 'crimson' } #Color Row
}

I would split the if conditions into separate nested ifs and also add a try..catch
$datagridview1_CellPainting = [System.Windows.Forms.DataGridViewCellPaintingEventHandler] {
if ($_.ColumnIndex -eq 1 -and $datagridview1.rows.Cells[4].Value -eq 'SEP') {
$SEPreturnlimit = (Get-Date).AddDays(-42).Date # set to 42 days back at midnight
try {
# if we succeed in parsing out a datetime object
$date = [datetime]$_.Value
# test if we have a DateTime object and if that date is older than the reference date
if (($date) -and $date-le $SEPreturnlimit) {
# cannot check this myself, but shouldn't that simply be
# $this.Rows[$_.RowIndex].DefaultCellStyle.BackColor = 'crimson'
$this.Rows[$_.RowIndex] | ForEach-Object{ $_.DefaultCellStyle.BackColor = 'crimson' } #Color Row
}
}
catch { <# do nothing #> }
}
}

I think I fixed the placement, but check the logic. Have a look at it this way
if
(
(
$_.ColumnIndex -eq 1 -and
(
[datetime]$_.Value -le
$SEPreturnlimit -and
[datetime]$_.Value.ToString() -ne
$null
)
) -and
(
$datagridview1.rows .Cells[4].Value -eq
'SEP'
)
) #Column 1 date older than 42 days or not $null **and** column 4 value = "SEP"

Related

Operator -gt and -le / Problem with negative numbers

i have the following code snippet where i change the values in a column (named G) of a csv to Y if the integer value is greater then 1 and to N if it is equal to 1 and smaller.
ForEach-Object {if ($_.G -gt '1') {$_.G = 'Y'} if ($_.G -le '1') {$_.G = 'N'} $_}
It works fine with the exception of negative numbers. I always get a Y. I don't have any idea. Example data:
F,G
item1, -58
item2, -77
item3, 562
Does anyone have an idea?
Regards, Hubertus
In order to evaluate the $_.G property as a number you need to specify the type as [int]. Example using your code:
$testObject = New-Object PSObject -Property #{
G='-1'
}
$testObject| %{
if ([int]$_.G -gt 1)
{
$out = "{0} is greater than 1" -f $_.G
Write-Host $out -ForegroundColor Green
[string]$_.G = "Y"
}
elseif ([int]$_.G -le 1)
{
$out = "{0} is Less than 1" -f $_.G
Write-Host $out -ForegroundColor Green
[string]$_.G = "N"
}
}
Note: In order to assign $_.G as a string you have to change the type to [string]. In my opinion, I would use another property to indicate "Y/N" instead of flipping the type back and forth on the property.
The left side of -le or -gt controls the type for both sides, int32 (integer) in this case. You probably want an else in there, to not look at the G again after changing it.
'G
-1
1
2' |
convertfrom-csv |
ForEach-Object {
if (1 -le $_.G)
{$_.G = 'Y'}
else
{$_.G = 'N'}
$_
}
G
-
N
Y
Y

Check if value falls within a specific range powershell

I am having a code which is giving me 2 values like below
$pattern = '\s(-?\d+.?\d+)\s'
$RX_Val = [regex]::Matches($RXTX_Data[0], $pattern).Value
$TX_Val = [regex]::Matches($RXTX_Data[1], $pattern).Value
PS C:\Windows\system32> $RX_Val
-3.4
PS C:\Windows\system32> $TX_Val
-2.3
Need get RX and TX value should fall under range -1 to -7
like the above 2 values falls within the range
if the values are like 1 and -8 respecively, then it should give error
I tried below code, but not getting the proper response
if((($RX_Val -gt -1) -and ($RX_Val -lt -7)))# -and (($TX_Val -gt '-1') -and ($TX_Val -lt '-7')))
{
Write-Host "OK"
}
else
{
Write-Host "NOT OK"
}
also tried
$RX_Val -In -1..-7
please let me know what i am missing here
Tried given solution in below way
$RX_Val = [int][regex]::Matches($RXTX_Data[0], $pattern).Value
$TX_Val = [int][regex]::Matches($RXTX_Data[1], $pattern).Value
if(($RX_Val -in -1..-7) -and ($TX_Val -in -1..-7))
{
Write-Host "OK"
}
else
{
$RXTX_Data | Out-File -FilePath "E:\$file_name" -Force
}
but failed for below scenario as the values are converted to int. it is suppose to print OK
$RX_Val=-0.1
$TX_Val=-1.5
The issue is that the value return by your regex extraction is a STRING. You need to convert it to an INT to be able to do your calculation.
$RX_Val = [int][regex]::Matches($RX, $pattern).Value
$TX_Val = [int][regex]::Matches($TX, $pattern).Value
Sure you can make the logic work from there.
As a bonus, the cast to [int] will also take care of the whitespace left from the regex.

Powershell Equivalent of Linq Statement

I have the following function in a library that is being converted to Powershell from C# and I havn't the first clue how to go about translation this statement. I realize SO is not for do a task for me type questions but anyone have any thoughts on where to begin?
IEnumerable<string[]> ReadI3TableString(string sFileData)
{
var records = sFileData.Split(new[] { (char)05, (char)00 }, StringSplitOptions.RemoveEmptyEntries).Skip(1)
.Select(line => line.Split(line.ToArray().Where(c => ((Int16)c) >= 128 || ((Int16)c) < 32).ToArray(), StringSplitOptions.RemoveEmptyEntries)).Where(p => p.Length > 1);
return records;
}
It's not really a "Linq-ish" implementation, rather using Powershell operators and the Powershell pipeline to the same effect:
$records = $fileData -split { $_ -in #([char]0, [char]5) } |
Select -Skip 1 |
Where-Object {
($_ -split { $_ -ge [char] 128 -or $_ -lt 32 }).Count -gt 1
}
Note: with some sample data I could validate this, but this works with mocked up data I had set up.

Display results of a SQL query with PowerShell

I have been provided a PS script which calls a simple SQL query, displays the results and plays a voice... supposedly. This is designed to go into a BI gadget which just displays a number from the PS script.
The correct count from the query is not displaying and is for some reason stuck on 2.
$sql = "<simple COUNT query>"
$items = invoke-sql -server "<server name>" -database "<db name>" -user "<uname>" -password "<password>" -sql $sql -timeout 180
$day = (get-date).DayOfWeek.Value__
# $items[0] = 10
if ($day -ge 1 -and $day -le 5)
{
$date = Get-Date
if ($date.Hour -ge 8 -and $date.Hour -lt 17)
{
if ($items[0] -gt 0)
{
$voice = New-Object -Com sapi.spvoice
$voice.Rate = 1
$voice.volume = 100
Do {
Start-Sleep -s 1
$Counter = Get-Date
}
Until ($Counter.Second/15 -is [int])
if ($items[0] -gt 1)
{
[void]$voice.Speak("New Ticket.")
}
else
{
[void]$voice.Speak("New Ticket.")
}
}
}
}
Write-Output $items.Count
The SQL component I have no issues with and definitely works correctly when run, but I have no experience with PowerShell scripting so can someone please assist?
$Items.count is going to give you the number of records in your result set. Technically these are DataRow objects and $Items is a DataTable. If you are getting multiple rows back, you need to determine WHICH row you want to show.
Basically the way to would query the returned DataTable is:
($Items[x]).Column
Where x is the 0-indexed row you want to return and Column is the name of the column you want to return. So if you want the ItemCount column from the second row you would use:
($Items[1]).ItemCount

The PowerShell -and conditional operator

Either I do not understand the documentation on MSDN or the documentation is incorrect.
if($user_sam -ne "" -and $user_case -ne "")
{
Write-Host "Waaay! Both vars have values!"
}
else
{
Write-Host "One or both of the vars are empty!"
}
I hope you understand what I am attempting to output. I want to populate $user_sam and $user_case in order to access the first statement!
You can simplify it to
if ($user_sam -and $user_case) {
...
}
because empty strings coerce to $false (and so does $null, for that matter).
Another option:
if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
...
}
Try like this:
if($user_sam -ne $NULL -and $user_case -ne $NULL)
Empty variables are $null and then different from "" ([string]::empty).
The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":
$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False