在emulating tree命令的上下文中,查看子目录中的files:
posh>
posh> $dir = "/home/nicholas/Calibre Library/Microsoft Office User/549 (1476)"
posh>
posh> Get-ChildItem -Path $dir –File
Directory: /home/nicholas/Calibre Library/Microsoft Office User/549 (1476)
Mode LastWriteTime Length Name
---- ------------- ------ ----
----- 2/20/2021 3:22 AM 159883 549 - Microsoft Office User.txt
----- 2/20/2021 2:13 AM 351719 cover.jpg
----- 2/20/2021 2:31 AM 1126 metadata.opf
posh> 上面的文件名是如何分配给变量的?
一个String数组或列表就足够了。但是上面的“名字”是如何被捕获的呢?或者,“目录”或其他属性?
发布于 2021-02-22 17:11:31
powershell中的大多数cmdlet都返回对象。对象具有属性。Get-ChildItem返回DirectoryInfo和FileInfo对象的集合,每个对象都有自己的一组属性,尽管它们非常相似。
以下命令将以FileInfo对象的形式检索路径$dir中的所有文件,并将它们添加到$files中包含的数组中
$files = Get-ChildItem -Path $dir –File现在,$files中的每个对象都是一个FileInfo对象,其中包含Name、BaseName、Directory、LastWriteTime、CreationTime、Extension等属性。要查看对象上存在哪些属性,可以通过管道获取要获取的对象的|
$files | Get-Member这将提供有关对象类型及其属性和方法的一些信息。为简洁起见,以下列表已被截断。你可以也应该自己尝试一下。
TypeName: System.IO.FileInfo
Name MemberType Definition
---- ---------- ----------
AppendText Method System.IO.StreamWriter AppendText()
CopyTo Method System.IO.FileInfo CopyTo(string destFileName), System.IO.FileInfo CopyTo(string destFileName, ...
Create Method System.IO.FileStream Create()
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
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;}
Length Property long Length {get;}
Name Property string Name {get;}现在您知道了对象上存在哪些属性,可以像这样访问它们
PS C:\temp> $files.Name
test.ps1
test.xml
test1.xlsx
test2.csv
testemail.csv
testout.xml
testxml.xml
write.xml或
PS C:\temp> $files.FullName
C:\temp\test.ps1
C:\temp\test.xml
C:\temp\test1.xlsx
C:\temp\test2.csv
C:\temp\testemail.csv
C:\temp\testout.xml
C:\temp\testxml.xml
C:\temp\write.xml您还可以通过管道将对象传送到Select-Object,以获取修改后的对象,其中只包含所需的特性,甚至是自定义特性(计算特性)。
$files | Select-Object Name, CreationTime, @{Label='Age'; Expression= {((Get-Date).Date - ($_.CreationTime).Date).Days}}
Name CreationTime Age
---- ------------ ---
test.ps1 19.02.2021 10:56:25 3
test.xml 14.02.2021 19:28:19 8
test1.xlsx 04.02.2021 19:31:54 18
test2.csv 04.02.2021 23:00:46 18
testemail.csv 03.02.2021 15:35:43 19
testout.xml 14.02.2021 19:32:03 8
testxml.xml 14.02.2021 19:33:41 8
write.xml 08.02.2021 17:26:40 14现在,这只是Powershell的一个小介绍。它确实有更多的东西。我看过你的其他帖子,看到你很感兴趣。有很多非常好的教程。我建议你看看其中的几个,看看所有真正需要学习的东西。对于初学者来说,可以看看powershell中关于对象的this one
https://stackoverflow.com/questions/66311703
复制相似问题