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
答案 0 :(得分:5)
您可以将Select-Object与-first开关一起使用并将其设置为1
<div class="container-fluid banner-1">
<div class="row">
<div class="col">
<div class="triangle-down"></div>
<div class="row">
<div class="col offset-md-6 pcontainer">
<h2>Why Move to Websphere Commerce v9</h2>
<p class="one">Give customers the ability to seamlessly move between channels to browse and buy when, where and how it’s most <span><a href="#">convenient</a></span> for them.</p>
<p class="two">IBM Watson Commerce’s innovation ecosystem offers complete and deep
<br>capabilities so you gain maximum impact from every customer interaction and transaction.</p>
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">
Learn More
</button>
</div>
</div>
</div>
</div>
</div>
我也将-File开关添加到Get-ChildItem,因为您只想返回文件。
答案 1 :(得分:4)
splitString[0] = "<START>"
splitString[1] = "message<B>UnknownLengthOfText<BEOF>"
splitString[2] = "message<B>UnknownLengthOfText<BEOF>"
splitString[3] = "<END>"
计数从0开始。因此$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
是一个数组或列表,而您在$contents
中提到的任何整数都是该项目在该数组/列表中的位置。因此,当您键入[]
时,就是在告诉powershell从数组$contents[9]
获得第9个项目。这是您遍历列表的方式。在大多数编程语言中,计数从0而不是1开始。对于进入编码世界但您已经习惯它的人来说,这有点令人困惑。
答案 2 :(得分:0)
Please use below command which is simple and helpful. Adding recurse will only put slight load on the machine or powershell (when the code is huge and it has been used somewhere)
$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path | sort | Select-Object -First 1
$contents.Name
test-01.eof
Select-Object -First will select each object (or row) and provide first row data as an output if you put as 1