N
N
NewDevLab2020-03-31 15:50:52
PowerShell
NewDevLab, 2020-03-31 15:50:52

How to correctly check the return of a function?

Why doesn't the first IF work?

[string] $pathToProjectFile = "C:\AnyProject.csproj";

function TestPath($Path) {
    return (Test-Path -Path $Path -PathType leaf)
}

$Result = TestPath($pathToProjectFile);
$Result.GetType().FullName
$Result

# Проверка наличия файла проекта
if (TestPath($pathToProjectFile) -eq $false) {
    Write-Host "1. Файл проекта '$pathToProjectFile' не существует!" -foregroundcolor red
    exit;
}

# Проверка наличия файла проекта
if ($Result -eq $false) {
    Write-Host "2. Файл проекта '$pathToProjectFile' не существует!" -foregroundcolor red
    exit;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MaxKozlov, 2020-03-31
@NewDevLab

because the first IF should look like
if ((TestPath $pathToProjectFile) -eq $false) {
In Powershell, you need to take the whole call in brackets, and not the arguments
your "-eq $false" become additional arguments to the function, not comparison operators
. You can see this if you write your function as

function TestPath($Path) {
    Write-Host -fore Green "Args: $args"
    return (Test-Path -Path $Path -PathType leaf)
}

And then you will see
Args: -eq False
the green color

E
Eugene, 2020-03-31
@BeatHazard

In the condition of the first IF, take TestPath($pathToProjectFile) outside the condition, drive it into a variable, and insert this variable into the IF, like this:
$TestPath = TestPath($pathToProjectFile)
if ($TestPath -eq $false)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question