Search code examples
powershellfor-loopget-childitem

Get-ChildItem Zero Results Output


I have an issue that I cannot resolve no matter which way I am wrapping it up. I am including my latest code which is not giving me the desired outcome and the code for a solution that does work but for only one file at a time. I cannot work out how to loop through each of the files automatically however.

In a nutshell, I have a directory with many CSV files some of the entries within the CSVfile have a negative value (-) I need to remove this minus sign in all instances.

Now what works is if I use the following (on a single file)

$content = Get-Content "L:\Controls\BCR\0001cash.csv" | ForEach {$_ -replace $variable, ""} | Set-Content "L:\controls\bcr\0001temp.csv"

What I am trying to do is iterate through the many thousand of these objects automatically and not have to refer to them individually.

I started with:

$Directory = "L:\Controls\BCR\"
$variable = "-"
$suffix = ".tmp"

To define the directory, minus symbol that I want to remove and the suffix of the file I want to change to...

$Files = Get-ChildItem $Directory | Where-Object {$_.Extension -like "*csv*"} | Where-Object {$_.Name -like "*cash*"}

Is obtaining each of the files that I wish to work with

And I am then working with

ForEach ($File in $Files) { Get-Content $Files | ForEach {$_ -replace $variable, ""} | Set-Content {$_.Basename + $Variable}

The results however are nothing...

At a loss? Anyone???

$Directory = "L:\Controls\BCR\"
$variable = "-"
$suffix = ".tmp"


$Files = Get-ChildItem $Directory | Where-Object {$_.Extension -like "*csv*"} | Where-Object {$_.Name -like "*cash*"}

$process = ForEach ($File in $Files) { Get-Content $Files | ForEach {$_ -replace $variable, ""} | Set-Content {$_.BaseName + $suffix}



}

Solution

  • You are using the wrong variable in the Get-Content cmdlet ($Files instead of $File). Also You can simplify your script:

    $Directory = "L:\Controls\BCR\"
    $variable = "-"
    $suffix = ".tmp"
    Get-ChildItem $Directory -Filter '*cash*csv' | 
        ForEach-Object {
            (Get-Content $_ -Raw) -replace $variable |
                 Set-Content {$_.BaseName + $suffix}
        }