0
votes

I have a script in Powershell that I'm having some trouble with.

$Path = 'C:\Projects\Powershell\TEst'
$MiddleName = 'torres'

CD $Path


Get-ChildItem .\ -filter *PCPLink*| ForEach-Object {
$content = Get-Content $_.FullName  | 
ForEach-Object {$_ -replace $MiddleName, $MiddleName[0]} |out-file $_.FullName -force
}

It's pretty straight forward, the issue I'm having is

I need this to look for multiple files that share the filename filter, for each file i need it to spit out a file with the same name and just the first character value $MiddleName truncated. NOT THE ENTIRE FILE

But when I change the script to output $_.Fullname, the files are empty. What am I missing?

So the file would look like

Torres
Tom
Tony
Tickle

I'm expecting

T
Tom
Tony
Tickle

Actual output from this script is Blank

It DOES pick up the two files I have it filtered to match.

1
Why are you trying to capture something in $Content if you are piping to Out-File? - TheMadTechnician
The original script I had had get content in parens, I needed to avoid that because it wasn't working how I intended, do you have a solution for this ? @TheMadTechnician - Hituptony
I think I've got it. I'll get you an answer shortly. - TheMadTechnician

1 Answers

2
votes

You are piping Get-Content to a ForEach loop, and then to Out-File, and that's all fine and dandy, but by the time you get to Out-File your $_ object is no longer representative of the file being affected, it is now the content of the file from the Get-Content cmdlet.

$Path = 'C:\Projects\Powershell\TEst'
$MiddleName = 'torres'
ForEach($File in (Get-ChildItem $Path -filter '*.csv')){
(Get-Content $File.FullName) -replace $MiddleName, $MiddleName[0] |out-file $File.FullName -force
}