Reputation: 304
I have this script that stores filenames into a text file:
Get-ChildItem -Path "C:\Users\MyUser\Documents\Files" -Name |
Out-File "C:\Users\MyUser\Documents\Files\FileList.txt"
The result is:
file1.txt file2.txt file3.txt file4.txt
I would like it to produce a list of PowerShell statements in a text file so that I could use them later like this:
Add-Content -Path "C:\Users\MyUser\Documents\Files\file1.txt" -Value "foo"
Add-Content -Path "C:\Users\MyUser\Documents\Files\file2.txt" -Value "foo"
Add-Content -Path "C:\Users\MyUser\Documents\Files\file3.txt" -Value "foo"
Add-Content -Path "C:\Users\MyUser\Documents\Files\file4.txt" -Value "foo"
Is it possible to concatenate a string to the file name the way I need?
Upvotes: 0
Views: 246
Reputation: 35428
I am also not sure whether I understand your question correctly but maybe this is what you are looking for:
Get-ChildItem -Path "C:\Users\MyUser\Documents\Files" |
% {
"Add-Content -Path `"{0}`" -Value `"foo`"" -f $_.FullName
} | Out-File "C:\Users\MyUser\Documents\Files\FileList.txt"
Upvotes: 1
Reputation: 47872
I'm a little unsure about what you're asking, but if I have it correct you want to get a list of files, add a line to the end of the file, and put the names of the files in text file.
Get-ChildItem -Path "C:\Users\MyUser\Documents\Files" |
ForEach-Object {
$_ | Add-Content -Value "foo"
$_.Name
} | Out-File "C:\Users\MyUser\Documents\Files\FileList.txt"
This is one possible way. It passes each item to ForEach-Object
, where a value is added to the file, and the file name is sent to the pipeline. That gets piped into Out-File
which writes the list.
There are many ways to achieve this; it's best to study and play with pipelining and then look at the various cmdlets and how they handle pipeline input.
Upvotes: 0