4

I'm trying to do the following:

$files = Get-ChildItem c:\temp | Select-Object Name
foreach ($i in $files) {
    Write-Host "Filename is $i"
}

Sample result:

Filename is @{Name=oracle10204.rsp}
Filename is @{Name=powershell.txt}

How do I get only the following?

Filename is oracle10204.rsp
Filename is powershell.txt

5 Answers 5

5

With the -Name switch you can get object names only:

 Get-ChildItem c:\temp -Name
Sign up to request clarification or add additional context in comments.

Comments

5

If you are adamant about getting your original attempt to work, try replacing

Select-Object Name

with

Select-Object -ExpandProperty Name

Comments

4

I am not sure why you are using Select-Object here, but I would just do:

Get-ChildItem c:\temp | % {Write-Host "Filename is $($_.name)"}

This pipes the output of Get-ChildItem to a Foreach-Object (abbreviation %), which runs the command for each object in the pipeline.

$_ is the universal piped-object variable.

4 Comments

Thanks, your example works, but how to get my foreach statement to give correct result?
@jrara - I'm saying don't use your foreach statement since this is the same thing but a much more efficient way. Pipelining is what powershell was designed for.
Well, yes, but I'm trying to learn powershell and I would like to know what is wrong with my foreach loop. I know that there is many other ways to do this.
In that case, remove the Select-Object and just output the name property of each file object.
3

Here is the answer to get just the name from your example. Surround the $i with $( ) and reference the .Name property. The $() will cause it to evaluate the expression.

$files = Get-ChildItem c:\temp | Select-Object Name
foreach ($i in $files) {
    Write-Host "Filename is $($i.Name)"
}

Comments

0

You can get this object as a string with the Get-ChildItem -Name parameter:

$variable = Get-ChildItem C:\temp -Name

This gives you a:

System.String
If you use the Name parameter, Get-ChildItem returns the object names as strings.

You can read about it in Get-ChildItem.

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.