Reputation: 107
I'm trying to put together a foreach loop that will give me the date in each of the file names constructed using substrings on the filename using the following code:
$DailyFile = gci '\\web-servr-w01\Accounting' | ? {$_.Name -like 'GL_XTRAK_*'} | select -First 5 |select -ExpandProperty Name
$FileMon = $DailyFile.Substring(24,2)
$FileDay = $DailyFile.Substring(26,2)
$FileYr = $DailyFile.Substring(28,4)
$FileDate = get-date -Year $FileYr -Month $FileMon -Day $FileDay -Format "MM-dd-yyyy"
foreach($File in $DailyFile)
{
$FileDate
}
But running that gives me the following output:
04-30-2019
04-30-2019
04-30-2019
04-30-2019
04-30-2019
When I was expecting:
04-30-2019
05-01-2019
05-02-2019
05-03-2019
05-04-2019
I've verified that the code works when I only select a single file by modifying the GCI statement using '-skip 1 -first 1' or -skip 2 -first 1' etc.
I'm a Powershell novice so please be gentle.
Upvotes: 0
Views: 99
Reputation: 174485
You need to loop over all the files and grab the date parameters from each of them:
$DailyFileNames = gci '\\web-servr-w01\Accounting' | ? {$_.Name -like 'GL_XTRAK_*'} | select -First 5 |select -ExpandProperty Name
foreach($FileName in $DailyFileNames)
{
$FileMon = $FileName.Substring(24,2)
$FileDay = $FileName.Substring(26,2)
$FileYr = $FileName.Substring(28,4)
$FileDate = Get-Date -Year $FileYr -Month $FileMon -Day $FileDay -Format "MM-dd-yyyy"
$FileDate
}
At which point you might notice that turning the strings into a DateTime
object and back to a string again is unnecessary:
$DailyFileNames = gci '\\web-servr-w01\Accounting' | ? {$_.Name -like 'GL_XTRAK_*'} | select -First 5 |select -ExpandProperty Name
foreach($FileName in $DailyFileNames)
{
$FileMon = $FileName.Substring(24,2)
$FileDay = $FileName.Substring(26,2)
$FileYr = $FileName.Substring(28,4)
"$FileMon-$FileDay-$FileYr"
}
Upvotes: 2