需要帮助,在针对此脚本的foreach中合并多个变量

时间:2019-06-18 17:11:09

标签: powershell

我是PowerShell的新手,正在尝试修改现有脚本以在foreach循环中运行多个变量(域)。下面的脚本片段。

$ DomainIdentities是将确定脚本运行所针对的$ TargetDomain的变量。假设我有两个域domainA.lab.local和domainB.lab.local,在foreach中将这两个循环在两个域上运行的最佳方法是什么?

    Write-Host 'Gathering and analyzing target domain information...'
    Import-Module ActiveDirectory
    Import-Module GroupPolicy

    $TargetDomain = Get-AdDomain -Identity $DomainIdentities | Select Name,DNSRoot,NetBIOSName,DomainMode,PDCEmulator

    Write-Host ''
    Write-Host '   Domain NetBIOS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.NetBIOSName
    Write-Host '   Domain DNS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DNSRoot 
    Write-Host '   PDC emulator: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.PDCEmulator
    Write-Host '   DomainMode: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DomainMode
    Write-Host '   Checking domain functional mode is ''Windows2008Domain'' or higher.....' -NoNewline

    $Status | Add-Member -MemberType NoteProperty -Name 'DomainModePassed' -Value (!(($TargetDomain.DomainMode -eq 'Windows2000Domain') -or ($TargetDomain.DomainMode -eq 'Windows2003InterimDomain') -or ($TargetDomain.DomainMode -eq 'Windows2003Domain')))
    If ($Status.DomainModePassed) {Write-Host -ForegroundColor Green 'PASSED'} 
    Else {Write-Host -ForegroundColor Red 'FAILED'}

    Write-Host ''

1 个答案:

答案 0 :(得分:1)

Domains声明为在脚本顶部采用多个字符串值的参数:

param(
    [string[]]$Domains
)

Write-Host 'Gathering and analyzing target domain information...'
Import-Module ActiveDirectory
Import-Module GroupPolicy

foreach($Domain in $Domains){
    $TargetDomain = Get-ADDomain -Identity $Domain | Select Name,DNSRoot,NetBIOSName,DomainMode,PDCEmulator

    Write-Host ''
    Write-Host '   Domain NetBIOS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.NetBIOSName
    Write-Host '   Domain DNS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DNSRoot 
    Write-Host '   PDC emulator: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.PDCEmulator
    Write-Host '   DomainMode: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DomainMode
    Write-Host '   Checking domain functional mode is ''Windows2008Domain'' or higher.....' -NoNewline

    $Status | Add-Member -MemberType NoteProperty -Name 'DomainModePassed' -Value (!(($TargetDomain.DomainMode -eq 'Windows2000Domain') -or ($TargetDomain.DomainMode -eq 'Windows2003InterimDomain') -or ($TargetDomain.DomainMode -eq 'Windows2003Domain')))
    If ($Status.DomainModePassed) {Write-Host -ForegroundColor Green 'PASSED'} 
    Else {Write-Host -ForegroundColor Red 'FAILED'}

    Write-Host ''
}

然后将域名传递给脚本,如下所示:

.\path\to\script.ps1 -Domains ad.contoso.com,ad.fabrikam.com