2

考虑示例脚本代码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;

运行 2 次后的预期输出:

I am True.
Already Imported.

运行2次后的实际输出:

I am false
Import done.

如果我将Test-AlreadyImported函数导入 Powershell 并执行它,那么它会返回false. 但是在脚本中它总是返回true.

我在犯什么概念性错误?

4

1 回答 1

3

-ForceforNew-Item表示:创建项目,即使它已经存在(覆盖)。新创建的文件将为空,因此Test-AlreadyImported始终返回 true。

如果您删除该-Force参数,则会返回您的预期输出。

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;
于 2018-09-23T19:02:14.340 回答