nested Foreach and Variables

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 11 months ago.

  • Author
    Posts
  • #5426

    by MichaelPS at 2013-01-11 06:12:56

    Hey guys,

    I want to backup all GPOs of all my domains. The backup for one domain works just fine, but I have a problem with multiple domains. So far I got this:


    $Domain = (Get-ADForest).Domains | Foreach {
    $GPO = Get-GPO -all -Domain $Domain | Foreach {
    $strGPOName = $GPO.Displayname
    $strId = $GPO.Id
    OutLn "INFO: Backing up $strGPOName"
    Backup-GPO -Guid $strId -Domain $Domain -path $strBackupLocation
    Get-GPOReport -Guid $strId -Domain $Domain -reporttype html -path $GPODir\Report\$name.html
    }
    }

    (FYI: OutLn is a own function, and variables like strBackupLocation are defined earlier.)

    I want to get all domains (Get-ADForest), then do something for each Domain (Get-GPO) and for each GPO do something else (Backup, Report...). I think the use of variables and loops is not correct in my example. Who could help me?

    Thanks in advance!

    Greets,
    Michael

    by ArtB0514 at 2013-01-11 06:25:33

    It looks like you are trying to use the value of $Domain before it's defined. Try replacing the first line of your script with:

    Foreach ($Domain In (Get-ADForest).Domains) {

    I'm not sure this is the only issue in your script (for instance, I don't see where the variable $name gets a value). So, I'm not sure that it will deliver what you want.

    by MichaelPS at 2013-01-11 06:43:21

    You're right! The following code works just perfect, thank you!

    Foreach ($Domain in (Get-ADForest).Domains) {
    Get-GPO -all -Domain $Domain | Foreach {
    $strGPOName = $_.Displayname
    $strId = $_.Id
    OutLn "INFO: Backing up $strGPOName in Domain $Domain"
    Backup-GPO -Guid $strId -Domain $Domain -path $strBackupLocation
    Get-GPOReport -Guid $strId -Domain $Domain -reporttype html -path $GPODir\Report\$Domain---$strGPOName.html
    }
    }

You must be logged in to reply to this topic.