如何从Powershell中的forEach-Object循环返回文件名?

时间:2019-07-01 17:43:26

标签: powershell

我已经使用Powershell一天了,我需要使用循环返回文件夹中每个文件的文件名。这是我目前拥有的:

$filePath = 'C:\Users\alibh\Desktop\Test Folder' #the path to the folder
cd $filePath

Get-ChildItem $filePath |
ForEach-Object{
$fileName = "here is where I return the name of each file so I can edit it 
later on"
}

我想比较文件夹中不同文件的名称,以后再编辑或删除文件;但在此之前,我首先需要能够逐个获取每个文件的名称。

编辑:非常感谢

2 个答案:

答案 0 :(得分:0)

仅对于循环中的每个文件名,您可以执行以下操作:

Get-ChildItem $filepath -File | Foreach-Object {
    $fileName = $_.Name
    $fileName   # Optional for returning the file name to the console
}

对于仅循环中的每个文件名及其路径,您可以执行以下操作:

Get-ChildItem $filepath -File | Foreach-Object {
    $fileName = $_.FullName
}

说明:

通过这种代码结构,默认情况下,您只能访问Foreach-Object脚本块中的每个文件名,但最后一个对象传递给循环除外。 $_$PSItem代表Foreach-Object {}脚本块中的当前对象。它包含Get-ChildItem返回的单个对象的所有属性。通过将$_结果传送到Get-ChildItemGet-Member变量本身,您可以有效地查看$_变量可访问的所有属性,如下所示:

Get-ChildItem $filepath -File | Get-Member -MemberType Property

   TypeName: System.IO.FileInfo

Name              MemberType Definition
----              ---------- ----------
Attributes        Property   System.IO.FileAttributes Attributes {get;set;}
CreationTime      Property   datetime CreationTime {get;set;}
CreationTimeUtc   Property   datetime CreationTimeUtc {get;set;}
Directory         Property   System.IO.DirectoryInfo Directory {get;}
DirectoryName     Property   string DirectoryName {get;}
Exists            Property   bool Exists {get;}
Extension         Property   string Extension {get;}
FullName          Property   string FullName {get;}
IsReadOnly        Property   bool IsReadOnly {get;set;}
LastAccessTime    Property   datetime LastAccessTime {get;set;}
LastAccessTimeUtc Property   datetime LastAccessTimeUtc {get;set;}
LastWriteTime     Property   datetime LastWriteTime {get;set;}
LastWriteTimeUtc  Property   datetime LastWriteTimeUtc {get;set;}
Length            Property   long Length {get;}
Name              Property   string Name {get;}

答案 1 :(得分:0)

这是一个奇怪的解决方法,用于获取每个文件的完整路径(在字符串上下文中),在文件夹路径中添加通配符:

Get-ChildItem $filePath\* | ForEach { "$_" }
相关问题