2

Consider the example script code importer.ps1

#!/usr/bin/env pwsh

New-Item -Path $profile -Force | Out-Null;

function main {
    if (Test-AlreadyImported) {
        Write-Host "Already Imported.";
    }
    else {
        Add-Content $profile "#My Additions" | Out-Null;
        Add-Content $profile "`$env:PSModulePath = `$env:PSModulePath + `";$PSScriptRoot`";" | Out-Null;
        Write-Host "Import done.";   
    }
}

function Test-AlreadyImported {
    if (Get-Content $profile | Select-String -Quiet "#My Additions") {
        Write-Host "I am true";
        return $true;
    }
    else {
        Write-Host "I am false";
        return $false;
    }
}

main;

Expected Output after running 2 times:

I am True.
Already Imported.

Actual Output after running 2 times:

I am false
Import done.

If I import the Test-AlreadyImported function to Powershell and execute it, then it returns false. But in-script it always returns true.

What is the conceptual mistake I'm making?

1
  • I would go for debugging and put a breakpoint in the beginning, so I can follow with every single line in the script step by step. This should help you understand what is going on and why. Commented Sep 23, 2018 at 20:07

1 Answer 1

3

-Force for New-Item means: Create the item, even if it's already there (overwrite). The newly created file will be empty, thus Test-AlreadyImported returns always true.

If you remove the -Force parameter, your expected output is returned.

New-Item -Path $profile -ErrorAction SilentlyContinue | Out-Null;

function main {
    if (Test-AlreadyImported) {
        Write-Host "Already Imported.";
    }
    else {
        Add-Content $profile "#My Additions" | Out-Null;
        Add-Content $profile "`$env:PSModulePath = `$env:PSModulePath + `";$PSScriptRoot`";" | Out-Null;
        Write-Host "Import done.";   
    }
}

function Test-AlreadyImported {
    if (Get-Content $profile | Select-String -Quiet "#My Additions") {
        Write-Host "I am true";
        return $true;
    }
    else {
        Write-Host "I am false";
        return $false;
    }
}

main;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.