Reputation: 65
I have a folder and within that folder it has .txt files with fax numbers as part of the file name (the first 10 characters contain the fax number).
I am trying to write a script that would read each file name for the fax number then writes it into a "control file".
However, it cannot put all the fax numbers at one time into the Control file. I need it to read the fax number of file 1 and write it into the control file, then move onto file 2, read the fax number and overwrite the control file with the fax number of file 2. And so on and so forth.
The script I have so far reads the fax numbers and writes to the control file, but it reads all the fax numbers and adds each one to the control file. I need it to write one by one.
This is what I have so far:
$directory = "C:\Users\blah\Desktop\TestFolder"
$controlfile = "C:\Users\blah\Desktop\Scripts\control.txt"
$filename = Get-ChildItem -path $directory -name -filter *.txt
foreach($file in $directory)
{
$faxnumber = $filename.substring(0,10)
Set-Content $controlfile "<tofaxnum:$faxnumber>
<toname:XXX>
<tocompany:XXX>
<fromname: XXX>
<fromphone:XXX>" -force
}
So if there are 3 files in $directory
it writes all 3 fax numbers into the control file as opposed to looking at the first file then writing, then moving onto the 2nd file then writing, then onto the 3rd. Any help or ideas you can provide would be very much appreciated.
Upvotes: 1
Views: 63
Reputation: 59031
You have to iterate over each filename returned from the Get-ChildItem
cmdlet instead of using the filenames within the loop:
$directory = "C:\Users\blah\Desktop\TestFolder"
$controlfile = "C:\Users\blah\Desktop\Scripts\control.txt"
$filenames = Get-ChildItem -path $directory -name -filter *.txt
foreach($filename in $filenames)
{
$faxnumber = $filename.substring(0,10)
Set-Content $controlfile "<tofaxnum:$faxnumber>
<toname:XXX>
<tocompany:XXX>
<fromname: XXX>
<fromphone:XXX>" -force
}
Upvotes: 2