using variables

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.