【问题标题】:How do I return a filename from a forEach-Object loop in Powershell?如何从 Powershell 中的 forEach-Object 循环返回文件名?
【发布时间】:2019-11-12 08:58:16
【问题描述】:

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

我想比较文件夹中不同文件的名称,稍后编辑或删除文件;但在开始之前,我首先需要能够一个接一个地获取每个文件的名称。

编辑:非常感谢大家

【问题讨论】:

  • 您可以使用$_$PSiItem 访问当前迭代的对象,并通过在其名称后附加一个点来访问特定属性。 $_.FullName$_.Name$.BaseName(或者,您可以使用原始 cmdlet 指定 -PipeLineVariable
  • 你可以试试这里找到的答案:PowerShell ForEach $file in $Files

标签: powershell


【解决方案1】:

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

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 { "$_" }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      相关资源
      最近更新 更多