且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 PowerShell 获取目录中的文件名

更新时间:2021-12-09 08:29:07

您需要使用 Get-ChildItem cmdlet.

You need to use the Get-ChildItem cmdlet.

Get-ChildItem C:\Users\Bruce\deploy\*.txt | Select-Object -ExpandProperty Name | Out-File C:\Users\Bruce\process.txt -Force -Append

但是,当您使用 PowerShell 时,ls 在这里实际上对您有用,就像 gcidir 一样Get-ChildItem 的所有别名:

However, as you're using PowerShell, ls would actually work for you here, as would gci and dir as they're all aliases for Get-ChildItem:

>  get-alias | ? {$_.DisplayName -ilike "*get-childitem*" }

CommandType     Name
-----------     ----
Alias           dir -> Get-ChildItem
Alias           gci -> Get-ChildItem
Alias           ls -> Get-ChildItem

如果您愿意,您也可以使用 >>> 而不是管道到 Out-File.

You can also use > or >> instead of piping to Out-File if you so wish.

由于 Get-Childitem cmdlet 返回对象列表,因此您还需要选择要从对象中提取的信息.如果您在包含一些内容的目录中执行 ls ,您将看到内容被格式化为表格.

Because the Get-Childitem cmdlet returns a list of objects, you then need to also select which information you want to extract from the object. If you do a ls in a directory with some content, you will see the contents are formatted into a table.

通过使用 Select-Object cmdlet,您可以提取要写入文件的对象属性,在本例中为 Name 属性.

By using the Select-Object cmdlet, you can extract the object properties you want to write to your file, in this case the Name property.