【问题标题】:PowerShell switch still generating output filesPowerShell 开关仍在生成输出文件
【发布时间】:2019-09-18 15:50:32
【问题描述】:

我一直在编写一个脚本,该脚本输出两个文件并包含一个参数,用于确定结果是否输出到几个 .csv 文件。

    [Parameter(Mandatory = $False)]
    [String]$ToFile = $True

    if ($ToFile = $True) {
        $OutputCerts.GetEnumerator() | Export-Csv -NoTypeInformation -Path $Path
    }

    if ($IncludeExpiredCerts -eq $True -And $ToFile -eq $True) {
        $ExpiredCerts.GetEnumerator() | Export-Csv -NoTypeInformation -Path $ExpiredPath
    }

我遇到的问题是$ToFile 开关,当$ToFile 为真时,它会输出$OutputCerts .csv,当我将$IncludeExpiredCerts 开关设置为真时,我得到两个.csv文件如您所料,但是,当我将$ToFile 开关设置为 false 时,我仍然得到 .csv 输出,但我不确定为什么。

任何建议将不胜感激。

【问题讨论】:

  • if ($ToFile = $True)if ($ToFile -eq $True)
  • 非常感谢,知道这将是一件小事doh
  • 另外,参数$ToFile 不应该是[String],而是[Bool]。为什么不将它用作[switch]$ToFile 并像if ($ToFile) {...} 一样使用它

标签: powershell scripting


【解决方案1】:

我相信 notjustme 的评论可以解决您的问题,但我想补充一点:

使用[switch]$ToFile 怎么样? 这将提供一个只允许布尔值的开关参数。如果您使用的是字符串类型,则可以使用任何文本并且会被接受。

与其他开关值一样,默认情况下为 false,使用时为 true。例如:

function Test-Funct {
    param([switch]$test = $true)
    Write-Host Switch Value: $test
}

那么当测试时:

Test-Funct
Switch Value: False

Test-Funct -test
Switch Value: True

同样有效:

Test-Funct -test:$false
Switch Value: False

Test-Funct -test:$true
Switch Value: True

如果您想将参数设置为强制参数,另一种选择是使用 bool 类型:

function Test-Funct {
    param(
        [Parameter(Mandatory=$true)]
        [bool]$test
    )
    Write-Host Switch Value: $test
}

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2022-01-16
    • 2014-12-19
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多