jrara
jrara

Reputation: 16981

How to get a string instead of an array in PowerShell?

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

Upvotes: 4

Views: 8904

Answers (5)

JNK
JNK

Reputation: 65157

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.

Upvotes: 4

piotrektt
piotrektt

Reputation: 189

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.

Upvotes: 0

OldFart
OldFart

Reputation: 2479

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

Select-Object Name

with

Select-Object -ExpandProperty Name

Upvotes: 5

Shay Levy
Shay Levy

Reputation: 126742

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

 Get-ChildItem c:\temp -Name

Upvotes: 5

jhamm
jhamm

Reputation: 1888

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)"
}

Upvotes: 3

Related Questions