PowerShell에서 문자열이 null인지 또는 비어 있는지 어떻게 확인할 수 있습니까?
IsNullOrEmpty
PowerShell에서 문자열이 null인지 또는 비어 있는지 확인하기 위해 기본 제공 기능이 있습니까?
나는 지금까지 그것을 찾을 수 없었고 내장 된 방법이 있다면 이것을 위해 함수를 작성하고 싶지 않습니다.
IsNullOrEmpty
정적 메소드를 사용할 수 있습니다 .
[string]::IsNullOrEmpty(...)
너희들은 이것을 너무 어렵게 만들고있다. PowerShell은이를 매우 우아하게 처리합니다.
> $str1 = $null
> if ($str1) { 'not empty' } else { 'empty' }
empty
> $str2 = ''
> if ($str2) { 'not empty' } else { 'empty' }
empty
> $str3 = ' '
> if ($str3) { 'not empty' } else { 'empty' }
not empty
> $str4 = 'asdf'
> if ($str4) { 'not empty' } else { 'empty' }
not empty
> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' }
one or both empty
> if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' }
neither empty
뿐만 아니라 [string]::IsNullOrEmpty
위해 널 (null)를 확인하거나 명시 적 또는 부울 표현식에서 부울 문자열을 캐스팅 할 수 비우합니다 :
$string = $null
[bool]$string
if (!$string) { "string is null or empty" }
$string = ''
[bool]$string
if (!$string) { "string is null or empty" }
$string = 'something'
[bool]$string
if ($string) { "string is not null or empty" }
산출:
False
string is null or empty
False
string is null or empty
True
string is not null or empty
함수의 매개 변수 인 경우 ValidateNotNullOrEmpty
다음 예에서 볼 수 있듯이 이를 검증 할 수 있습니다.
Function Test-Something
{
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$UserName
)
#stuff todo
}
개인적으로 공백 ($ STR3)을 '비어 있지 않음'으로 허용하지 않습니다.
공백 만 포함 된 변수가 매개 변수로 전달 될 때 매개 변수 값이 공백이 아니라고 '$ null'이 아닐 수 있다는 오류가 종종 발생합니다. 일부 제거 명령은 루트 대신 폴더를 제거 할 수 있습니다. 하위 폴더 이름이 "공백"인 경우 많은 경우 공백이 포함 된 문자열을 허용하지 않는 모든 이유가 있습니다.
이것이 최선의 방법이라고 생각합니다.
$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}
빈
$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}
빈
$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}
빈!! :-)
$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}
비어 있지 않음
[String] :: IsNullOrWhiteSpace ()가없는 컴퓨터에서 실행해야하는 PowerShell 스크립트가 있으므로 직접 작성했습니다.
function IsNullOrWhitespace($str)
{
if ($str)
{
return ($str -replace " ","" -replace "`t","").Length -eq 0
}
else
{
return $TRUE
}
}
# cases
$x = null
$x = ''
$x = ' '
# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}
순수한 PowerShell 방식으로이 작업을 수행하는 또 다른 방법은 다음과 같은 작업을 수행하는 것입니다.
("" -eq ("{0}" -f $val).Trim())
null, 빈 문자열 및 공백이 성공적으로 평가됩니다. 전달 된 값을 빈 문자열로 서식을 지정하여 null을 처리합니다 (그렇지 않으면 Trim이 호출 될 때 null이 오류를 발생시킵니다). 그런 다음 빈 문자열로 평등을 평가하십시오. 나는 여전히 IsNullOrWhiteSpace를 선호한다고 생각하지만 다른 방법을 찾고 있다면 이것이 효과가 있습니다.
$val = null
("" -eq ("{0}" -f $val).Trim())
>True
$val = " "
("" -eq ("{0}" -f $val).Trim())
>True
$val = ""
("" -eq ("{0}" -f $val).Trim())
>True
$val = "not null or empty or whitespace"
("" -eq ("{0}" -f $val).Trim())
>False
지루함을 느끼기 위해이 부분을 가지고 더 짧게 만들었습니다 (더 비밀 스럽지만).
!!(("$val").Trim())
또는
!(("$val").Trim())
당신이하려는 일에 따라.
대한 PowerShell을 2.0 교체 [string]::IsNullOrWhiteSpace()
ISstring -notmatch "\S"
( " \ S "= 공백이 아닌 문자)
> $null -notmatch "\S"
True
> " " -notmatch "\S"
True
> " x " -notmatch "\S"
False
성능은 매우 가깝습니다.
> Measure-Command {1..1000000 |% {[string]::IsNullOrWhiteSpace(" ")}}
TotalMilliseconds : 3641.2089
> Measure-Command {1..1000000 |% {" " -notmatch "\S"}}
TotalMilliseconds : 4040.8453
있습니다 "if ($str)"
및 "IsNullOrEmpty"
테스트가 모든 경우에 상대적으로 작동하지 않습니다는 :의 할당은 $str=0
모두 거짓 생산, 의도 프로그램의 의미에 따라,이 놀라운를 얻을 수 있습니다.
길이를 확인하십시오. 객체가 존재하면 길이를 갖습니다.
널 오브젝트는 길이가없고 존재하지 않으며 점검 할 수 없습니다.
문자열 객체는 길이가 있습니다.
문제는 IsNull 또는 IsEmpty, NOT IsNull 또는 IsEmpty 또는 IsWhiteSpace입니다.
#Null
$str1 = $null
$str1.length
($str1 | get-member).TypeName[0]
# Returns big red error
#Empty
$str2 = ""
$str2.length
($str2 | get-member).TypeName[0]
# Returns 0
## Whitespace
$str3 = " "
$str3.length
($str3 | get-member).TypeName[0]
## Returns 1
'Programming' 카테고리의 다른 글
파이썬 모듈에서 모든 함수를 나열하는 방법? (0) | 2020.02.27 |
---|---|
보이는 DOM에 요소가 있는지 확인하는 방법? (0) | 2020.02.27 |
iOS 및 WatchKit에서 이미지 tintColor를 변경하는 방법 (0) | 2020.02.27 |
iPhone / iPad / IO를위한 빠르고 마른 PDF 뷰어-팁과 힌트? (0) | 2020.02.27 |
Visual Studio에서 디버깅하는 동안 반환하기 전에 반환 값을 찾을 수 있습니까? (0) | 2020.02.27 |