如何从 Powershell/Powershell Core 中同一脚本中的另一个函数调用函数?
How to call function from another function inside the same script in Powershell/Powershell Core?
考虑示例脚本代码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 并执行它,那么它会 returns false
。但是在脚本中它总是 returns true
.
我犯的概念错误是什么?
-Force
for New-Item
表示:创建项目,即使它已经存在(覆盖)。新创建的文件将为空,因此 Test-AlreadyImported
returns 始终为真。
如果删除 -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;
考虑示例脚本代码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 并执行它,那么它会 returns false
。但是在脚本中它总是 returns true
.
我犯的概念错误是什么?
-Force
for New-Item
表示:创建项目,即使它已经存在(覆盖)。新创建的文件将为空,因此 Test-AlreadyImported
returns 始终为真。
如果删除 -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;