Powershell studio datagridview if 语句

Powershell studio datagridview if statement

我有一个 cellpainting 事件,正在尝试 correct/clean 这个 IF 语句。我想我在括号里迷路了。有人能再看看这个吗?谢谢你的时间。

我的最终目标是 IF 语句为:第 1 列日期是否超过 42 天 $null and 第 4 列值 = "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
        
    }

我想我修复了位置,但请检查逻辑。这样看

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"

我会将 if 条件拆分为单独的嵌套 ifs 并添加 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 #> }
    }
}