using variables

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

  • Author
    Posts
  • #5296

    by MichaelPS at 2012-11-21 02:06:40

    Hi!

    I'm writing a small script, wich automaticly detects all authorized DHCP servers, and copy the DHCP database backup from those DHCP servers (which is created hourly by default) to another location.

    So far I got this:

    Get-ADObject -LDAPFilter “(&(objectClass=dHCPClass)(dhcpIdentification=DHCP Server object))” -SearchScope Subtree -SearchBase "CN=Configuration,DC=hv,DC=group" | foreach {Copy-Item -Path \\$_\C$\Windows\System32\dhcp\backup -Destination C:\DHCP_Backup\$_ -Recurse}

    The first part, Get-ADObject, is working poperly. I get all authorized DHCP servers.

    But for the foreach part, I have the problem that "$_" is the Distinguished Name, not the FQDN. I also tried things like $_.Name oder $_.Properties.Name, which is not working. I guess it's a pretty basic question, but I dont get the right way. Maybe you guys can help me out?
    I need \\server.domain\C$\Windows... for the Copy-Item line.

    Thanks in advance!
    Michael

    by Klaas at 2012-11-21 02:41:04

    Does this work?

    Get-ADObject -LDAPFilter “(&(objectClass=dHCPClass)(dhcpIdentification=DHCP Server object))” -SearchScope Subtree -SearchBase "CN=Configuration,DC=hv,DC=group" |
    Select-Object -Expandproperty name |
    foreach {Copy-Item -Path \\$_\C$\Windows\System32\dhcp\backup -Destination C:\DHCP_Backup\$_ -Recurse}

    by MichaelPS at 2012-11-21 05:54:35

    It does! Great, thank you!

    by DonJ at 2012-11-21 07:23:12

    FWIW, in your original, $_ was actually the entire object you retrieved. Not just the DN. $_.Name would be proper, but that isn't the FQDN either.

    Rather than piping the whole thing to ForEach-Object, I'd pipe it to Get-Member to see what properties were available.

    What Klaas did is use Select-Object to extract the Name property's contents for you. Where you were going wrong with $_.Name is sticking it in the middle of a string – PowerShell probably wasn't evaluating the thing properly. ($_.Name) probably would work, too, as the parentheses force it to evaluate that expression first.

    -Path "\\$($_.Name)\C$\Windows..."

    Would be my best bet. Just so that you know what was happening.

You must be logged in to reply to this topic.