Export Results To Individual Files

Frequent Contributor

Hello I am trying to export .xml files from a list of servers so it creates a separate file for each server in a loop. But the problem is it looks like the loop would overwrite the results from each server in the loop to the same output file. I have been searching but cannot find a way to do what I want it to do. Here is what I have for the scrip.

$computers = get-content .\servers.txt
foreach ($computer in $computers){
Export-DhcpServer -ComputerName $computer -File "C:\DHCP_EXPORT\DHCP-Config.xml" -Force

Can someone tell me how I can get this to create a separate .xml file for each server in the servers.txt file? Its hard to search for a solution for this in Google so I though I could get some help here.
Thanks in advance!! 

2 Replies
best response confirmed by charlie4872 (Frequent Contributor)

Hello @charlie4872,

One of the options would be to add $computer to resulting filename:

$computers = get-content .\servers.txt
foreach ($computer in $computers){
Export-DhcpServer -ComputerName $computer -File "C:\DHCP_EXPORT\$computer-DHCP-Config.xml" -Force

This will create a separate file for every computer in the input file in your DHCP_EXPORT folder.

Hope that helps


Thanks AndySvints this does exactly what I was looking for!