使用 PowerShell 获取目录中的文件名 [英] Using PowerShell to get a file name in a directory

查看:119
本文介绍了使用 PowerShell 获取目录中的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录,其中包含一个名为 Bruce.txt 的文件.我需要将文件名复制到平面文件中.我尝试使用 copy-item 命令,但它复制的是内容而不是名称.

I have a directory that contains a file called Bruce.txt. I need to copy the file name to a flat file. I tried using the copy-item command but that copies the contents not the name.

是否有将 Bruce.txt(名称而不是内容)复制到平面文件的命令?所以在它完成后会有一个名为 process.txt 的文件,它的内容将是 Bruce.txt.我尝试使用

Is there a command to copy Bruce.txt (the name not the contents) to a flat file? So after it completes there will be a file called process.txt and its contents will be Bruce.txt. I tried using

Copy-Item -Path "C:\Users\Bruce\deploy\*.txt" -Destination "C:\Users\Bruce\process.txt".

deploy 内部是一个名为 Bruce.txt 的文本文件,其中包含 select count() from EMP_NR 的内容.

Inside of deploy is a text file called Bruce.txt with the contents of select count() from EMP_NR.

我需要 Bruce.txt 将名称复制到 process.txt 而不是 Select count() 等.

I need Bruce.txt the name copied to process.txt not the Select count() etc.

对于 Shell 脚本,我使用 ls 命令,它的效果很好,我可以使用 Powershell 做什么?

For Shell script I use the ls command and it works wonderful what can I use for Powershell?

推荐答案

您需要使用 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.

这篇关于使用 PowerShell 获取目录中的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆