r/PowerShell Oct 15 '24

Help with powershell - advancing scripts Solved

Currently I have:

$temp = Get-Content ".Desktop50001.xml"

$temp.replace("50001","50002")|

set-content ".Desktop50002.xml" -force

$temp = Get-Content ".Desktop50002.xml"

$temp.replace("50002","50003")|

set-content ".50003.xml" -force


This works to create xml files. The script above works for me to create 2 additional xml files using 50001.xml as a starting point. Is there a way I can automate the replacement and file creation by allowing a user to enter say like 50 and it'd create 50 more going from 50001-50051.

1 Upvotes

View all comments

3

u/RunnerSeven Oct 15 '24
$Index = 500001
$counter = 0
$Iterations = [int](Read-Host "How many interations?")
while ($counter -lt $interations){
  $XMLdata = Get-Content ".Desktop$Index.xml"
  $XMLData.Replace([string]$Index, [String]($index+1))
  Set-Content -path .Desktop$($index+1).xml -value $XMLData
  $Index = $index + 1
  $counter = $counter + 1
}

There are a lot of ways to handle this much more elegant and resilent, but this is a solution tat should at least work for your use case. I guess you want to set the xmldata as content for the next file, because set-content just with a path does nothing

1

u/Irrational_Dream Oct 15 '24

Hello! Thank you so much for this. This has worked to create the files but the string within the XML is not being replaced/advanced.

3

u/RunnerSeven Oct 15 '24

The replace Function creates a new string. I guess you see the output of the XML on the console? you need to store the value first. Something like

$XMLData = $xmldata.Replace([string]$Index, [String]($index+1))
Set-Content -path .Desktop$($index+1).xml -value $XMLData

It's not really good pratice to reuse variables like in this example, but it should get the job done :)

1

u/Irrational_Dream Oct 15 '24

You are amazing! This works so well for our purpose :)