【问题标题】:Powershell conditionPowershell 条件
【发布时间】:2021-03-27 19:14:47
【问题描述】:

如果我使用不等于“Dynamique”或“Statique”的 TypeAdressage 调用函数,我想抛出错误,但是当我使用“Dynamique”调用它时会抛出错误

  function Changer-Type {
    param(
        [string]$Identifiant,
        [string]$TypeAdressage,
        [string]$Path
    )

    if ($TypeAdressage -ne "Dynamique"-or ($TypeAdressage -ne "Statique")){
    Write-Error "Type Adressage impossible"
        }

      

        else{

    if(-not(Test-Path $Path -PathType Leaf) -or [IO.Path]::GetExtension($Path) -ne '.csv') {
        throw 'File does not exist or is not a Csv...'
    }

    $computers = Import-Csv -Path $Path -Delimiter ';'

    $computers | Where-Object { $_.Identifiant -eq $Identifiant } | 
                 ForEach-Object { $_.TypeAdressage = $TypeAdressage }
    # write the updated $computers object array back to disk
    $computers | Export-Csv -Path $Path -Delimiter ';'  -NoTypeInformation
}

    }
$csvPath = 'C:\Temp\Peripherique.csv'
Changer-Type -Identifiant "Q00032" -TypeAdressage "Dynamique" -Path $csvPath

Changer-Type -Identifiant "PWIN10" -TypeAdressage "test" -Path $csvPath

【问题讨论】:

  • -or 更改为-and
  • 我会将您的条件更改为:if (-not ('Dynamique', 'Statique', 'orAnyOtherType' -eq $TypeAdressage)) { ...,另请参阅:If all values in 'foreach' are true
  • Mathias 是对的,当您想测试两个事物的不等式时,-and 是正确的连词。与随意交谈相反。

标签: powershell conditional-statements


【解决方案1】:

为什么不让 PowerShell 验证参数 $TypeAdressage 始终是两个(或更多)预定义字符串之一?

function Changer-Type {
    param(
        [string]$Identifiant,
        [ValidateSet('Dynamique','Statique')]
        [string]$TypeAdressage,
        [string]$Path
    )

    if(-not(Test-Path $Path -PathType Leaf) -or [IO.Path]::GetExtension($Path) -ne '.csv') {
        throw 'File does not exist or is not a Csv...'
    }

    $computers = Import-Csv -Path $Path -Delimiter ';'

    $computers | Where-Object { $_.Identifiant -eq $Identifiant } | 
                 ForEach-Object { $_.TypeAdressage = $TypeAdressage }
    write the updated $computers object array back to disk
    $computers | Export-Csv -Path $Path -Delimiter ';'  -NoTypeInformation
}

Changer-Type -TypeAdressage Dynamique

作为额外奖励,使用[ValidateSet()] 还可以在编码时为您提供智能感知:

【讨论】:

    【解决方案2】:

    我建议更改您的 if 语句。因为你在说: 如果 $TypeAdressage 不等于“动态” 或者 $TypeAdressage 不等于“Dynamique”。

    if 语句永远为真,因为 $TypeAdressage 永远不会同时是“Dynamique”和“Dynamique”。

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2021-12-25
      • 2017-01-20
      相关资源
      最近更新 更多