如何在PowerShell的forEach-Object循环中返回一个文件名?

5
我现在已经使用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"
}

我想比较文件夹中不同文件的名称,并在以后编辑或删除文件;但在此之前,我需要一个接一个地获取每个文件的名称。
编辑:非常感谢大家。

1
您可以使用 $_$PSItem 访问当前迭代对象,通过在名称后添加点来访问特定属性。例如:$_.FullName$_.Name$.BaseName(或者您可以使用 -PipeLineVariable 参数指定源 cmdlet)。 - user6811411
你可以尝试这里找到的答案:PowerShell ForEach $file in $Files - techguy1029
2个回答

5

在您的循环内只针对每个文件名,您可以执行以下操作:

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-ChildItem结果管道传输到Get-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;}

2
这是一个奇怪的解决方法,可以在文件夹路径中添加通配符来获取每个文件的完整路径(在字符串上下文中)。原始答案翻译成“最初的回答”。
Get-ChildItem $filePath\* | ForEach { "$_" }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接