0

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.

3
  • Why are you trying to capture something in $Content if you are piping to Out-File? Commented Nov 9, 2015 at 19:19
  • 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 Commented Nov 9, 2015 at 19:21
  • I think I've got it. I'll get you an answer shortly. Commented Nov 9, 2015 at 19:24

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh shoot, I think my original script would've worked if I removed the pipe after (Get-Content $File.FullName) ...Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.