Como verificar se uma string está vazia no PowerShell

  1. Verificar se uma String É Not NULL ou EMPTY no PowerShell
  2. Alternativas ao IsNullOrEmpty para Verificar se uma String É Null ou Vazia no PowerShell
  3. Usar o Operador -eq para Verificar se uma String É Null ou Vazia no PowerShell
  4. Usar RegEx para Verificar se uma String É Null ou Vazia no PowerShell
Como verificar se uma string está vazia no PowerShell

Neste artigo, discutiremos os métodos que podem ser usados para verificar se uma determinada string é null ou vazia no PowerShell.

Verificar se uma String É Not NULL ou EMPTY no PowerShell

IsNullOrEmpty é um método comum em script/linguagem de programação para verificar se uma determinada string está vazia ou null. Um null é um valor de string que não foi atribuído, e uma string vazia é uma string com " " ou dada String.Empty.

Alternativas ao IsNullOrEmpty para Verificar se uma String É Null ou Vazia no PowerShell

Há uma maneira fácil de fazer a função equivalente do PowerShell IsNullOrEmpty. Os seguintes segmentos de código podem ser usados.

A string dada no comando é null. Portanto, a saída do código é como abaixo.

Código de Exemplo 1:

PS C:\Users\Test> $str1 = $null
PS C:\Users\Test> if ($str1) { 'not empty' } else { 'empty' }

Saída:

empty

Se a string estiver vazia, a saída ainda será vazia.

Código de Exemplo 2:

PS C:\Users\Test> $str2 = ''
PS C:\Users\Test> if ($str2) { 'not empty' } else { 'empty' }

Saída:

empty

Se a string não estiver vazia e não estiver null, a saída será não vazia.

Código de Exemplo 3:

PS C:\Users\Test> $str3 = ' '
PS C:\Users\Test> if ($str3) { 'not empty' } else { 'empty' }

Saída:

not empty

Existem comandos para comparar duas strings e verificar se duas ou mais estão vazias.

PS C:\Users\Agni>  if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' }

Saída:

one or both empty

Além disso, nem vazia é uma possível comparação usada acima para comparar duas strings declaradas. Isso pode ser identificado como o método mais claro e conciso de usar o IsNullOrEmpty.

Além do método acima, o método estático IsNullOrEmpty também pode ser usado no PowerShell.

Usar o Operador -eq para Verificar se uma String É Null ou Vazia no PowerShell

O operador -eq compara dois valores em busca de igualdade. Você pode comparar uma string com uma string vazia para verificar se ela está vazia.

Código:

$str1 = ""
if ($str1 -eq "") {
    Write-Host "String is empty"
}
else {
    Write-Host "String is not empty"
}

Saída:

String is empty

Usar RegEx para Verificar se uma String É Null ou Vazia no PowerShell

Os padrões de uma string podem ser correspondidos usando Expressões Regulares. Você pode usar um padrão regex que corresponda a strings vazias ou contendo apenas espaços em branco.

Código:

$str4 = "   "
if ($str4 -match "^\s*$") {
    Write-Host "String is empty"
}
else {
    Write-Host "String is not empty"
}

Saída:

String is empty
Está gostando dos nossos tutoriais? Inscreva-se no DelftStack no YouTube para nos apoiar na criação de mais vídeos tutoriais de alta qualidade. Inscrever-se
Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Artigo relacionado - PowerShell String