Check if a string is not NULL or EMPTY

前端 未结 6 1793
别跟我提以往
别跟我提以往 2020-12-15 15:38

In below code, I need to check if version string is not empty then append its value to the request variable.

if ([string]::IsNullOrEmpty($version))
{
    $re         


        
相关标签:
6条回答
  • 2020-12-15 15:44

    If the variable is a parameter then you could use advanced function parameter binding like below to validate not null or empty:

    [CmdletBinding()]
    Param (
        [parameter(mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$Version
    )
    
    0 讨论(0)
  • 2020-12-15 15:45

    I would define $Version as a string to start with

    [string]$Version
    

    and if it's a param you can use the code posted by Samselvaprabu or if you would rather not present your users with an error you can do something like

    while (-not($version)){
        $version = Read-Host "Enter the version ya fool!"
    }
    $request += "/" + $version
    
    0 讨论(0)
  • 2020-12-15 15:46

    if (!$variablename) { Write-Host "variable is null" }

    I hope this simple answer will is resolve the question. Source

    0 讨论(0)
  • 2020-12-15 15:52
    if (-not ([string]::IsNullOrEmpty($version)))
    {
        $request += "/" + $version
    }
    

    You can also use ! as an alternative to -not.

    0 讨论(0)
  • 2020-12-15 15:56

    You don't necessarily have to use the [string]:: prefix. This works in the same way:

    if ($version)
    {
        $request += "/" + $version
    }
    

    A variable that is null or empty string evaluates to false.

    0 讨论(0)
  • 2020-12-15 16:08

    As in many other programming and scripting languages you can do so by adding ! in front of the condition

    if (![string]::IsNullOrEmpty($version))
    {
        $request += "/" + $version
    }
    
    0 讨论(0)
提交回复
热议问题