How to get a string instead of an array in PowerShell?
I'm trying to do the f开发者_开发技巧ollowing:
$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
With the -Name switch you can get object names only:
Get-ChildItem c:\temp -Name
If you are adamant about getting your original attempt to work, try replacing
Select-Object Name
with
Select-Object -ExpandProperty Name
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.
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)"
}
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.
精彩评论