如何从Powershell中的forEach对象循环返回文件名?
我已经使用Powershell一天了,我需要使用循环返回文件夹中每个文件的文件名。以下是我目前拥有的:如何从Powershell中的forEach对象循环返回文件名?,powershell,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 ed
$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"
}
我想比较文件夹中不同文件的名称,然后编辑或删除文件;但在我开始之前,我首先需要能够一个接一个地获取每个文件的名称
编辑:非常感谢大家对于循环中的每个文件名,您可以执行以下操作:
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
}
对于循环中的每个文件名及其路径,您可以执行以下操作:
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对象
脚本块中的每个文件名,但传递到循环中的最后一个对象除外。
$\u
或$PSItem
表示Foreach对象{}
脚本块中的当前对象。它将包含由Get ChildItem
返回的单个对象的所有属性。通过将Get ChildItem
结果管道化到Get Member
或$\ucode>变量本身,可以有效地查看$\ucode>变量可访问的所有属性,如下所示:
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;}
下面是一个奇怪的解决方法,用于获取每个文件的完整路径(在字符串上下文中),在文件夹路径中添加通配符:
Get-ChildItem $filePath\* | ForEach { "$_" }
通过在当前迭代对象的名称后面加上一个点,您可以使用$\ucode>或$PSiItem
和特定属性访问该对象$\u0.FullName
,$\u0.Name
,$.BaseName
(或者,您可以使用原始cmdlet指定一个-PipeLineVariable
),您可以尝试以下答案: