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

Zul*_*hai 5 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"
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:非常感谢大家

Adm*_*ngs 5

For each filename only within your loop, you can do the following:

Get-ChildItem $filepath -File | Foreach-Object {
    $fileName = $_.Name
    $fileName   # Optional for returning the file name to the console
}
Run Code Online (Sandbox Code Playgroud)

For each filename and its path only within your loop, you can do the following:

Get-ChildItem $filepath -File | Foreach-Object {
    $fileName = $_.FullName
}
Run Code Online (Sandbox Code Playgroud)

Explanation:

使用此代码结构,默认情况下您只能访问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;}
Run Code Online (Sandbox Code Playgroud)