3

I need to format, add text to, a list of files I am getting using Powershell. I can simply use the following script to get my list of files:

Get-ChildItem("c:\path") | where {$_.Length -eq 0} | select name

This works well returning a list of file names:

file1.txt
file2.txt
file2.txt

What I am trying to do is add additional text to the output so it looks more like this:

'file1.txt',
'file2.txt',
'file3.txt',

This I am finding to be more difficult than it should be. I tried this:

$l = Get-ChildItem("c:\path") | where {$_.Length -eq 0} | select name | foreach($_) { "'$_,"}

This doesn't quite do it, as the field name is added to the output:

'@{Name=file1.txt}.Name',
'@{Name=file2.txt}.Name',
'@{Name=file3.txt}.Name',

Is there a way to format this better or remove the object information?

4 Answers 4

3

You're very close. Use the -expandproperty parameter for select-object to get the property as a simple array of strings.

$l = Get-ChildItem("c:\path") |
    where {$_.Length -eq 0} |
    select -expandproperty name | foreach($_) { "'$_,"}
Sign up to request clarification or add additional context in comments.

1 Comment

I selected this method as it provides the most control over which fields you may want to select from.
1

Try this

$l = Get-ChildItem("D:\Test") | where { $_.Length -eq 0 } | %{"'$_',"}

4 Comments

Strange, this does work. Why is $_ in the last part only returning the Name and not all the fields? I would assume it still contains everything, or is it only returning the first field?
What does the % do? e.g. %{"'$_',"}
% is alias for "foreach" cmdlet
I think $_ works because there might be some ToString method which is called when you are providing value in string.
1

If you've got V3 or better you can do it this way:

@((Get-ChildItem c:\path  | where Length -eq 0).name) -match '\S'| foreach { "'$_'," }

1 Comment

Issue with this is that '', is returned if there are no files returned.
0
$l = Get-ChildItem("c:\path") | where {$_.Length -eq 0} | select $_.Name | foreach { "'$_'," }

Comments

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.