开关参数和 If 语句

Switch Parameter and an If Statement

我正在尝试使用开关参数的值作为触发器来写入 csv 文件(如果使用脚本从命令行调用该参数)。但是,使用我当前的代码,无论是否包含参数,都会创建 csv 文件。这是怎么回事?

此外,是否有更好的方法来处理我的 else/if else/if else 部分?

[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)]
    [string]$dir,
    [Parameter(Mandatory=$true)]
    [int]$days,
    [switch]$csv=$false
)

Process {
    Clear-Host
    $totSize = 0
    $totFiles = 0
    $modDate = (Get-date).AddDays(-$days).Date
    $modfiles = Get-ChildItem -Path $dir -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -ge $modDate } 
    If ($csv = $true){
        $modfiles | Select-Object -Property FullName, Length,LastWriteTime | Export-Csv -Path .\modFiles.csv -NoTypeInformation
    }
    foreach ($file in $modfiles){
        $totFiles = $totFiles + 1
        $totSize = $totSize + $file.Length 
    }

    If ($totSize -lt 1MB){
        $outSize = $totSize/1KB
        $unit = "KB"
    }
    elseif (($totSize -ge 1MB) -and ($totSize -lt 1GB)){
        $outSize = $totSize/1MB
        $unit = "MB"   
    }
    elseif ($totSize -ge 1GB){
        $outSize = $totSize/1GB
        $unit = "GB" 
    } 

    $outRound = [math]::Round($outSize,2)
    Write-Host $totFiles "Files"
    Write-Host $outRound $unit
}

两个问题。

  1. 不要为 [switch] 参数指定默认值。它会把你搞得一团糟。保留它,如果指定它将是 $true,如果是 $false 没有。
  2. 在测试逻辑值时,例如 If 语句,不要使用赋值等号 (=),使用比较等号 (-eq)。
If ($csv -eq $true){
    $modfiles | Select-Object -Property FullName, Length,LastWriteTime | Export-Csv -Path .\modFiles.csv -NoTypeInformation
}

编辑(感谢@Scepticalist):此外,如果您正在测试的变量已经包含 [bool] 值,或者可以隐式转换为 [bool],您甚至不需要 -eq $true比较的一部分,所以:

If ($csv){
        $modfiles | Select-Object -Property FullName, Length,LastWriteTime | Export-Csv -Path .\modFiles.csv -NoTypeInformation
    }