在第一个 foreach 循环 运行 完成后,Powershell 在循环完成后调用另一个 PS1

Powershell calls another PS1 in loop finishes after first foreach loop run completes

我有 2 个 Powershell 脚本,一个是主要脚本 (ServerInfo.ps1),另一个是用作包装器的辅助脚本,在将使用不同凭据的循环中启动第一个脚本由于对不同的 AD Domains/Forests 进行查询,每个循环都需要每个域的不同域信用。

主脚本 运行 如果我 运行 单独从每个域中的机器手动和本地执行 运行 并且根据需要执行(获取详细信息),则主脚本 运行 很好从远程机器导出到 csv)

以下为Wrapper脚本(域名示例因安全原因更改)

# This is a Wrapper Script for ServerInfo.ps1
$username = Read-Host -Prompt 'Enter User Account to be used - Do not specify domain'
$Password = Read-Host -Prompt 'Input User Password - NOTE must be the same on all domains' -AsSecureString
$domains = "d1.contoso.com","d2.contoso.com","dev.contosodev1.com","test.contosotest1.com"
$Arguments = "-file c:\serverinfo\ServerInfo.ps1", "-ServerType 'DCs'"

ForEach ($domain in $domains) {
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "$domain$username", $Password
Start-Process powershell.exe -Credential $credential -NoNewWindow -ArgumentList $Arguments -WorkingDirectory 'c:\Serverinfo\' -Wait
}

具体来说,这将用于查询具有提升权限帐户的域控制器,该帐户在每个域上都是相同的,因为成员计算机上使用的帐户没有内置管理员或 AD(Domain/Enterprise 管理员)级别权限在域控制器上。目的还在于 运行 来自域成员的脚本,而不是 DC 上的本地脚本。

由于主要脚本 (serverinfo.ps1) 超过 1000 行代码,我将简单地说,包装器最初传递参数“-ServerType DCS”,ServerInfo.ps1从帐户所属的相应域的 AD 中获取所有域控制器名称,并执行诸如每个 DC 的 WMI 和注册表查询之类的操作,将输出导出到 CSV 文件。

对于第一个域,这个 运行 没有任何问题并且 ServerInfo.ps1 脚本可以查询第一个域中的每个 DC,然后两个 PowerShell 脚本 close/stop 运行 没有继续到包装循环中的第二个域,也就是说,一旦第一个域完成,"foreach ($Domain in $Domains)" 循环就不起作用了。

因为我在包装器中没有看到任何脚本错误,并且 ServerInfo 中没有退出或其他 cancellation/Finish 命令。Ps1,我不知道为什么包装器没有按预期工作。

For the first domain, this runs fine without any issue and the ServerInfo.ps1 script does it job querying every DC in the first domain, but then both PowerShell scripts close/stop running without it continuing to the second domain in the wrapper loop aka, the "foreach ($Domain in $Domains)" loop is not working once the first domain completes.

我很确定你的循环有效。只需在该循环中插入一个 Write-Host "Iteration for domain: $domain",您就会看到,它确实遍历了所有域。

我更关心你调用其他脚本的方式。使用 Start-Process -Credential,该过程将在所提供用户的用户 space 中执行。在您的场景中,如果您想 运行 在所有域的任何域计算机上,这将需要域之间的任何信任关系。你有什么? 如果没有,您必须以某种安全的方式将凭据传递给被调用的脚本,以便它可以在使用远程控制 cmdlet 时对自己进行身份验证。