PowerShell에서 문자열을 안전하게 bool로 변환
PowerShell 스크립트의 인수를 부울 값으로 변환하려고 합니다.이 줄
[System.Convert]::ToBoolean($a)
"true" 또는 "false"와 같은 유효한 값을 사용하기만 하면 작동하지만 "bla" 또는 ""와 같은 유효하지 않은 값이 전달되면 오류가 반환됩니다.입력 값이 잘못되면 값을 false로 설정하고 변환 성공 또는 실패를 나타내는 부울을 반환하는 TryParse와 유사한 것이 필요합니다.참고로, 저는 시도했습니다.:Parse 및 [bool]을 사용해 보십시오.:TryParse, PowerShell이 인식하지 못하는 것 같습니다.
지금 저는 두 개의 추가 if 진술서를 가지고 이 일을 어설프게 처리해야 합니다.
제가 지금까지 찾은 사용법 및 블로그 게시물 중 잘못된 값을 다루는 게시물이 없다는 것이 저를 놀라게 한 것입니다.제가 뭔가를 놓쳤나요? 아니면 PowerShell 아이들이 입력 검증을 하기에 너무 멋있나요?
시도/포획 블록을 사용할 수 있습니다.
$a = "bla"
try {
$result = [System.Convert]::ToBoolean($a)
} catch [FormatException] {
$result = $false
}
제공:
> $result
False
TryParse사용하는 동안 작동해야 합니다.ref변수를 먼저 선언합니다.
$out = $null
if ([bool]::TryParse($a, [ref]$out)) {
# parsed to a boolean
Write-Host "Value: $out"
} else {
Write-Host "Input is not boolean: $a"
}
$a = 'bla'
$a = ($a -eq [bool]::TrueString).tostring()
$a
False
또 다른 가능성은 스위치 문을 사용하고 평가만 수행하는 것입니다.True,1그리고.default:
$a = "Bla"
$ret = switch ($a) { {$_ -eq 1 -or $_ -eq "True"}{$True} default{$false}}
이 경우 문자열이 다음과 같을 경우True $true반환됩니다.다른 모든 경우$false반환됩니다.
또 다른 방법은 다음과 같습니다.
@{$true="True";$false="False"}[$a -eq "True" -or $a -eq 1]
존 프리센의 PowerShell 소스 Ternary 연산자
이것을 다시 찾았고 저만의 답을 찾았습니다. 하지만 코멘트로서 몇 가지 수정/기타 입력 값이 포함된 답으로 추가하고 예상대로 작동하는지 확인하기 위한 페스터 테스트도 추가했습니다.
Function ParseBool{
[CmdletBinding()]
param(
[Parameter(Position=0)]
[System.String]$inputVal
)
switch -regex ($inputVal.Trim())
{
"^(1|true|yes|on|enabled)$" { $true }
default { $false }
}
}
Describe "ParseBool Testing" {
$testcases = @(
@{ TestValue = '1'; Expected = $true },
@{ TestValue = ' true'; Expected = $true },
@{ TestValue = 'true '; Expected = $true },
@{ TestValue = 'true'; Expected = $true },
@{ TestValue = 'True'; Expected = $true },
@{ TestValue = 'yes'; Expected = $true },
@{ TestValue = 'Yes'; Expected = $true },
@{ TestValue = 'on'; Expected = $true },
@{ TestValue = 'On'; Expected = $true },
@{ TestValue = 'enabled'; Expected = $true },
@{ TestValue = 'Enabled'; Expected = $true },
@{ TestValue = $null; Expected = $false },
@{ TestValue = ''; Expected = $false },
@{ TestValue = '0'; Expected = $false },
@{ TestValue = ' false'; Expected = $false },
@{ TestValue = 'false '; Expected = $false },
@{ TestValue = 'false'; Expected = $false },
@{ TestValue = 'False'; Expected = $false },
@{ TestValue = 'no'; Expected = $false },
@{ TestValue = 'No'; Expected = $false },
@{ TestValue = 'off'; Expected = $false },
@{ TestValue = 'Off'; Expected = $false },
@{ TestValue = 'disabled'; Expected = $false },
@{ TestValue = 'Disabled'; Expected = $false }
)
It 'input <TestValue> parses as <Expected>' -TestCases $testCases {
param ($TestValue, $Expected)
ParseBool $TestValue | Should Be $Expected
}
}
이전 답변이 더 완전하지만, 만약 당신이 그것을 안다면.$foo -eq 1, "1", 0, "0", $true, $false...강요할 수 있는 모든 것.[int]
다음 중 하나statements작업:
[System.Convert]::ToBoolean([int]$foo)
[System.Convert]::ToBoolean(0 + $foo)
간단한 해결책이 필요한 사람에게 도움이 되길 바랍니다.
언급URL : https://stackoverflow.com/questions/27484682/safely-converting-string-to-bool-in-powershell
'programing' 카테고리의 다른 글
| 아이폰으로 서버에 사진을 업로드하려면 어떻게 해야 합니까? (0) | 2023.09.05 |
|---|---|
| WCF GET URL 길이 제한 문제: 잘못된 요청 - 잘못된 URL (0) | 2023.08.31 |
| 표 성능 대보기 (0) | 2023.08.31 |
| Laravel 4에서 원시 SQL 쿼리 이스케이프 (0) | 2023.08.31 |
| Swift에서 배열의 항목을 새 위치로 다시 정렬하는 방법은 무엇입니까? (0) | 2023.08.31 |