这个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
但是,使用相同的语法,以下脚本会提示输入凭据,然后退出到命令行(运行方式如下:。\ ScriptName.ps1 -ConfigFile Chef.config),这意味着lambda函数未正确执行(为了测试,每个应该只输出服务器名称。)
为什么前一个lambda函数返回服务器名称,但脚本中的那些没有?
$id = 10;
$arr = ('0', '3', '2', '1');
$searchId = "SELECT id FROM items WHERE groupId = '$id'";
$result = $db->query($searchId);
foreach($arr as $r) {
$row = $result->fetch_assoc();
$sql = " UPDATE items
SET position = '$r'
WHERE id = '{$row['id']}' ";
}
答案 0 :(得分:1)
如果不进行测试,我会继续说出来,因为您将脚本块执行放在PowerShell Jobs中,然后不对它们做任何事情。当您启动一个作业时,它会启动一个新的PowerShell实例并执行您提供的代码以及您提供的参数。完成后,完成的PSRemotingJob
对象就会停留在那里,并且在您实际执行某些操作之前不会执行任何操作。
在您的代码中,您启动的所有作业都将分配给$ Jobs变量。您还可以使用Get-Job
获取所有正在运行的作业:
Get-Job -State Running
如果您想获得从工作中返回的任何数据,您必须使用Receive-Job
# Either
$Jobs | Receive-Job
# Or
Get-Job -State Running | Receive-Job