此lambda函数按预期执行:
$WriteServerName = {
param($server)
Write-Host $server
}
$server = "servername"
$WriteServerName.invoke($server)
servername
但是,使用相同的语法,以下脚本提示输入凭据,然后退出到命令行(按以下方式运行:。\ ScriptName.ps1 -ConfigFile Chef.config),这意味着lambda函数未正确执行(用于测试) ,每个都应仅输出服务器名称)。
为什么以前的lambda函数返回服务器名称,而脚本中的却没有?
Param(
$ConfigFile
)
Function Main {
#Pre-reqs: get credential, load config from file, and define lambda functions.
$jobs = @()
$Credential = Get-Credential
$Username = $Credential.username
$ConvertedPassword = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.password)
$Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($ConvertedPassword)
$Config = Get-Content $ConfigFile -Raw | Out-String | Invoke-Expression
#Define lambda functions
$BootStrap = {
param($Server)
write-host $server
}
$RunChefClient = {
param($Server)
write-host $server
}
$SetEnvironment = {
param($Server)
write-host $server
}
#Create bootstrap job for each server and pass lambda functions to Scriptblock for execution.
if(($Username -ne $null) -and ($Password -ne $null))
{
ForEach($HashTable in $Config)
{
$Server = $HashTable.Server
$Roles = $HashTable.Roles
$Tags = $HashTable.Tags
$Environment = $HashTable.Environment
$ScriptBlock = {
param ($Server,$BootStrap,$RunChefClient,$SetEnvironment)
$BootStrap.invoke($Server)
$RunChefClient.invoke($Server)
$SetEnvironment.invoke($Server)
}
$Jobs += Start-Job -ScriptBlock $ScriptBlock -ArgumentList @($Server,$BootStrap,$RunChefClient,$SetEnvironment)
}
}
else {Write-Host "Username or password is missing, exiting..." -ForegroundColor Red; exit}
}
Main
最佳答案
如果没有测试,我将继续说这是因为您将脚本块执行放在PowerShell Jobs中,然后对它们不执行任何操作。当您开始工作时,它会启动一个新的PowerShell实例,并执行您提供的代码以及所提供的参数。完成后,完成的PSRemotingJob
对象将坐在那里,直到您实际对其执行任何操作之前,不执行任何操作。
在您的代码中,您启动的所有作业都分配给$ Jobs变量。您还可以使用 Get-Job
获得所有正在运行的作业:
Get-Job -State Running
如果要获取作业返回的任何数据,则必须使用
Receive-Job
# Either
$Jobs | Receive-Job
# Or
Get-Job -State Running | Receive-Job
关于powershell - PowerShell-不执行Lambda函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640487/