powershell 中的大多数 cmdlet 返回对象。对象具有属性。当您执行 Get-ChildItem 时,它返回 DirectoryInfo 和 FileInfo 对象的集合,每个对象都有自己的一组属性,尽管非常相似。
以下命令将检索路径 $dir 中的所有文件作为 FileInfo 对象,并将它们添加到包含在 $files 中的数组中
$files = Get-ChildItem -Path $dir –File
现在,$files 中的每个对象都是一个 FileInfo 对象,其中包含 Name、BaseName、Directory、LastWriteTime、CreationTime、Extension 等属性。要查看对象上存在哪些属性,您可以通过管道将 | 对象传递给 Get-Member
$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 的一个小介绍。其实还有很多。我看过你的其他帖子,看到你很感兴趣。那里有很多非常好的教程。我建议您看一下其中的一些,并了解真正要学习的所有内容。对于初学者,请查看 this one 关于 powershell 中的对象