Powershell从文件夹中捕获第一个文件名

Powershell从文件夹中捕获第一个文件名,powershell,Powershell,新手到powershell 我需要从目录中捕获第一个文件名。但是,我当前的脚本捕获所有文件名。请建议更改我下面的代码 # Storing path of the desired folder $path = "C:\foo\bar\" $contents = Get-ChildItem -Path $path -Force -Recurse $contents.Name 结果如下 test-01.eof test-02.eof test-03.eof 我只想要这个列表中的一个文件。所以预

新手到powershell 我需要从目录中捕获第一个文件名。但是,我当前的脚本捕获所有文件名。请建议更改我下面的代码

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

test-01.eof
test-02.eof
test-03.eof
我只想要这个列表中的一个文件。所以预期的结果应该是

test-01.eof

您可以将选择对象与-first开关一起使用,并将其设置为1

$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path -Force -Recurse -File | Select-Object -First 1
我还将-File开关添加到了
getchilditem
,因为您只想返回文件

$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

计数从0开始。因此,
$contents
这里是一个数组或列表,您在
[]
中提到的任何整数都是该项在该数组/列表中的位置。因此,当您键入
$contents[9]
时,您告诉powershell从数组
$contents
中获取第9项。这就是迭代列表的方式。在大多数编程语言中,计数从0开始,而不是从1开始。对于一个正在进入编码世界的人来说,这有点让人困惑,但你已经习惯了。

请使用下面的命令,这是一个简单而有用的命令。添加recurse只会给机器或powershell带来轻微的负载(当代码庞大且已在某处使用时)

存储所需文件夹的路径 输出将如预期的那样:
Select Object-First将选择每个对象(或行)并提供第一行数据作为输出(如果您将其设置为1)

如果您能更详细地解释您的答案,这肯定会对初次使用powershell的用户有所帮助;)只需执行以下操作:
$fileName=(获取子项-路径$Path |排序|选择对象-第一个1)。Name
$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path | sort | Select-Object -First 1
$contents.Name
test-01.eof