У меня есть два скрипта PowerShell. Test-Stuff.ps1
и Functions.ps1
. Test-Stuff.ps1
полагается на Functions.ps1
, включая функцию, которая окружает вызов функции для Write-Host
начала и конца исключения функции, переданного в качестве параметра.
Работает нормально, если функция, переданная в качестве параметра, также не приходит из Functions.ps1
. В этом случае параметры переданных функций не фиксируются функцией вызова.
Test-Stuff.ps1
# Let's stop whenever there is something wrong
$ErrorActionPreference = "Stop"
# Cleanup screen
Clear-Host
# We import the functions in that other PowerShell files
Import-Module "$PSScriptRoot\Functions.ps1" -Force
# Works fine
Invoke { Set-Location -Path $PSScriptRoot } "Change Current Working Directory to $PSScriptRoot"
# works fine too
Invoke { Write-Host "Testing" -ForegroundColor Red }
$configurationFileName = "Preprod.json"
# Works just fine
$configuration = Invoke { Get-Content -Raw -Path $configurationFileName | ConvertFrom-Json } "Fetch configuration"
$userName = $configuration.userName
$password = $configuration.serviceAccountPassword
# Does not work
$credential = Invoke { New-Credential $userName $password } "Fetch credential"
Functions.ps1
Function Write-Start($text)
{
Write-Host ([System.Environment]::NewLine + "${text}...") -ForegroundColor Gray
}
Function Write-Stop($text)
{
Write-Host ("${text}: Done") -ForegroundColor Green
}
Function Invoke([scriptblock]$scriptBlock, $text)
{
Write-Start $text
$result = $scriptBlock.Invoke()
Write-Stop $text
return $result
}
Исполнение .\TestStuff.ps1
:
Change Current Working Directory to C:\Users\eperret\Desktop\LetsSortThingsOut\KYC\Manual Deployment...
Change Current Working Directory to C:\Users\eperret\Desktop\LetsSortThingsOut\KYC\Manual Deployment: Done
...
Testing
: Done
Fetch configuration...
Fetch configuration: Done
Fetch credential...
Exception calling "Invoke" with "0" argument(s): "Exception calling ".ctor" with "2" argument(s): "Cannot process argument because the value of argument "userName" is not
valid. Change the value of the "userName" argument and run the operation again.""
At C:\Users\eperret\Desktop\LetsSortThingsOut\KYC\Manual Deployment\Functions.ps1:15 char:5
+ $result = $scriptBlock.Invoke()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CmdletInvocationException
PS C:\Users\eperret\Desktop\LetsSortThingsOut\KYC\Manual Deployment>
Я пытался использовать GetNewClosure
$credential = Invoke { New-Credential $userName $password }.GetNewClosure() "Fetch credential"
... но, похоже, не очень помогает, как я могу обеспечить захват переданных параметров функции?