Массив переменных в PowerShell имеет нулевые члены - PullRequest
0 голосов
/ 19 декабря 2018

У меня есть сценарий PowerShell, в котором я хочу убедиться, что определенные переменные имеют значение, прежде чем продолжить.

Поэтому у меня есть следующее:

$dataRow = $sheet.Cells.Find($country).Row
$serverCol = $sheet.Cells.Find($serverString).Column
$databaseCol = $sheet.Cells.Find($databaseString).Column
$userCol = $sheet.Cells.Find($userString).Column
$passwordCol = $sheet.Cells.Find($passString).Column
$partnerCol = $sheet.Cells.Find($partnerString).Column

#All variables in this array are required. If one is empty - the script cannot continue
$requiredVars = @($dataRow, $serverCol, $databaseCol, $userCol, $passwordCol, $partnerCol)

Но когда я выполняю foreach над массивомвот так:

foreach ($var in $requiredVars)
{
    Write-Host DataRow = ($dataRow -eq $var)
    Write-Host ServerCol = ($serverCol -eq $var)
    Write-Host DatabaseCol = ($databaseCol -eq $var)
    Write-Host UserCol = ($userCol -eq $var)
    Write-Host PasswordCol = ($passwordCol -eq $var)
    Write-Host PartnerCol = ($partnerCol -eq $var)
    if ($var -eq $null)
    {
        [System.Windows.Forms.MessageBox]::Show("No data found for given string!")
        $excel.Quit()
        return
    }
}

Я всегда получаю MessageBox.Я добавил часть «Write-Host», чтобы увидеть значение каждой переменной, затем изменил ее, чтобы увидеть, какая переменная имеет значение null, но все переменные содержат значения, и все проверки, которые вы видите здесь, возвращают «False».

Я хотел бы знать, что я делаю неправильно, и если массив $requiredVars копирует только значения, а не ссылки или что-то в этом роде.

Ответы [ 2 ]

0 голосов
/ 19 декабря 2018

Вместо использования отдельных переменных, вы можете рассмотреть возможность использования Hashtable для их хранения.
Это значительно упрощает проверку отдельных элементов:

# get the data from Excel and store everything in a Hashtable
# to use any of the items, use syntax like $excelData.passwordCol or $excelData['passwordCol']
$excelData = @{
    'dataRow'     = $sheet.Cells.Find($country).Row
    'serverCol'   = $sheet.Cells.Find($serverString).Column
    'databaseCol' = $sheet.Cells.Find($databaseString).Column
    'userCol'     = $sheet.Cells.Find($userString).Column
    'passwordCol' = $sheet.Cells.Find($passString).Column
    'partnerCol'  = $sheet.Cells.Find($partnerString).Column
}

# check all items in the hash. If any item is $null then exit
foreach ($item in $excelData.Keys) {
    # or use: if ($null -eq $excelData[$item])
    if (-not $excelData[$item]) {   
        [System.Windows.Forms.MessageBox]::Show("No data found for item $item!")
        $excel.Quit()

        # IMPORTANT: clean-up used COM objects from memory when done with them
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet) | Out-Null
        # Your code doesn't show this, but you'll have a $workbook object in there too
        # [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
        [System.GC]::Collect()
        [System.GC]::WaitForPendingFinalizers()

        return
    }
}
0 голосов
/ 19 декабря 2018

Один из способов прямого решения вашего вопроса заключается в следующем:

$a = "foo"
$b = "bar"
$c = $null

$requiredVariables = $a, $b, $c

# How many total entries in array?
($requiredVariables).Count

# How many of them have a value?
($requiredVariables | Where-Object {$_}).Count

# So one option for a single check would be:
if (($requiredVariables.Count) -ne ($requiredVariables | Where-Object {$_}).Count) {
    Write-Warning "Not all values provided"
}

Однако альтернативный [и лучший] подход состоит в том, чтобы сделать ваш код функцией, которая включает проверку параметров

function YourCustomFunction {
    Param (
    [ValidateNotNullOrEmpty()]
    $a
    ,
    [ValidateNotNullOrEmpty()]
    $b
    ,
    [ValidateNotNullOrEmpty()]
    $c
    )

    Process {
        Write-Output "Your function code goes here..."
    }
}

# Call your function with the params
YourCustomFunction -a $a -b $b -c $c

Пример вывода:

Test-YourCustomFunction: Невозможно проверить аргумент для параметра 'c'.Аргумент нулевой или пустой.Укажите аргумент, который не является пустым или пустым, а затем повторите команду.В строке: 39 символов: 48

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...