Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell capture first filename from a folder

Tags:

powershell

Newbie to powershell I need to capture first file name from a directory. However my current script captures all file names. Please suggest changes to my code below.

#   Storing path of the desired folder
$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path -Force -Recurse
$contents.Name

The result is following

test-01.eof
test-02.eof
test-03.eof

i just want one file (any) from this list. So expected result should be

test-01.eof
like image 545
data-bite Avatar asked Nov 30 '22 14:11

data-bite


2 Answers

You could use Select-Object with the -first switch and set it to 1

$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path -Force -Recurse -File | Select-Object -First 1

I've added the -File switch to Get-ChildItem as well, since you only want to return files.

like image 155
TobyU Avatar answered Jan 19 '23 10:01

TobyU


$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path -Force -Recurse
$contents # lists out all details of all files
$contents.Name # lists out all files
$contents[0].Name # will return 1st file name
$contents[1].Name # will return 2nd file name
$contents[2].Name # will return 3rd file name

The count starts from 0. So $contents here is an array or a list and whatever integer you mention in [] is the position of the item in that array/list. So when you type $contents[9], you are telling powershell that get the 9th item from the array $contents. This is how you iterate through a list. In most programming languages the count begins from 0 and not 1. It is a bit confusing for a someone who is entering the coding world but you get used to it.

like image 38
Gajendra D Ambi Avatar answered Jan 19 '23 09:01

Gajendra D Ambi