我有两个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"
self::where('user_id', $user_id)
->where('amount_due','<', 'amount_repaid')
->where('loan_type', $loan_type)
->get()
...但是似乎没有太大帮助,如何强制捕获传递的函数参数?
答案 0 :(得分:1)
问题似乎出在脚本块New-Credential $userName $password
的内容上。我不熟悉该cmdlet,是您编写或导入的模块中的cmdlet吗?如果它是有效的cmdlet,则似乎参数的内容存在问题,或者没有与之匹配的“重载”。
也许您应该.Trim()
和.ToString()
那个$Configuration.userName