Reputation: 2019
I have a list of files in a folder each are in this format: custID_invID_prodID. For every file I need to break it into sections based on '_'. Currently I have this code
$files = Get-ChildItem test *.txt
$Part = $files.Split(';')[$($files.Split('_').Count-1)]
Write-Host "${Part}"
The problem is that it appears that $files
is a list of all the files and I need it to run each file on its own. Can anyone offer some pointers on how to do this for the entire folder?
Upvotes: 0
Views: 498
Reputation: 5560
"The problem is that it appears that $files is a list of all the files and I need it to run each file on its own."
That is correct, running get-childitem on a folder will give you a list of all files (and subfolders). In order to go through them one by one, you need a loop:
$file = @()
$files = Get-ChildItem Test *.txt
foreach($f in $files)
{
$file += ([String]$f).Split("_")
$count = ([String]$f).Split("_") | Measure-Object | select count
}
if($count.count -eq 3) {
for($i=2; $i -lt $file.length; $i+=3) {
$file[$i] = $file[$i].trimend(".txt")
}
}
Upvotes: 1
Reputation: 2019
I was able to fix this by using this code:
$Part = $file.name.Split('_')[$($file.name.Split('_').Count-1)]
Write-Host "${Part}"
Upvotes: 0