param(
[Parameter(Mandatory=$True,Position=1)]
[String]$fileName
)
#$fileName doesn't include the directory or the extension
$dir = "C:\Users\pb\Desktop\source"
$latest = Get-ChildItem -Path $dir |
Where-Object {$_.Name -Like "*$fileName*"} |
Sort-Object LastwriteTime -Descending |
Select-Object -First 1 -exclude "*import*"
$fileName = $latest.name
$Source = "C:\Users\pb\Desktop\source\${fileName}"
基本上,使用.name
make $latest
上的$latest
包括目录和名称,还是只包含文件名,
例如$fileName
现在等于c:\users\pb\desktop\source\"fileName"
还是只有"fileName"
?
答案 0 :(得分:0)
在PowerShell中,与许多其他语言一样,点符号用于访问对象的属性。在您的情况下,$latest
包含FileInfo
对象(如果*$filename*
与文件夹匹配,则为DirectoryInfo
对象),该对象具有多个属性,例如Name
,FullName
,LastWriteTime
,Attributes
等
您可以通过将对象传递到Format-List
cmdlet来显示对象的属性及其各自的值,同时可以通过每个对象具有的GetType()
方法检查类型: / p>
PS C:\> Get-Item 'C:\Temp\test.txt'
PS C:\> $f.GetType().FullName
System.IO.FileInfo
PS C:\> $f | Format-List *
PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Temp\test.txt
PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Temp
PSChildName : test.txt
PSDrive : C
PSProvider : Microsoft.PowerShell.Core\FileSystem
PSIsContainer : False
VersionInfo : File: C:\Temp\test.txt
InternalName:
OriginalFilename:
FileVersion:
FileDescription:
Product:
ProductVersion:
Debug: False
Patched: False
PreRelease: False
PrivateBuild: False
SpecialBuild: False
Language:
BaseName : test
Mode : -a---
Name : test.txt
Length : 8
DirectoryName : C:\Temp
Directory : C:\Temp
IsReadOnly : False
Exists : True
FullName : C:\Temp\test.txt
Extension : .txt
CreationTime : 03.06.2015 00:11:07
CreationTimeUtc : 02.06.2015 22:11:07
LastAccessTime : 03.06.2015 00:11:07
LastAccessTimeUtc : 02.06.2015 22:11:07
LastWriteTime : 03.06.2015 00:11:17
LastWriteTimeUtc : 02.06.2015 22:11:17
Attributes : Archive
可以使用Get-Member
cmdlet检查对象的属性和方法:
PS C:> $f | Get-Member
TypeName: System.IO.FileInfo
Name MemberType Definition
---- ---------- ----------
Mode CodeProperty System.String Mode{get=Mode;}
AppendText Method System.IO.StreamWriter Append...
CopyTo Method System.IO.FileInfo CopyTo(str...
Create Method System.IO.FileStream Create()
CreateObjRef Method System.Runtime.Remoting.ObjRe...
...
PSIsContainer NoteProperty System.Boolean PSIsContainer=...
PSParentPath NoteProperty System.String PSParentPath=Mi...
PSPath NoteProperty System.String PSPath=Microsof...
PSProvider NoteProperty System.Management.Automation....
Attributes Property System.IO.FileAttributes Attr...
CreationTime Property datetime CreationTime {get;set;}
CreationTimeUtc Property datetime CreationTimeUtc {get...
Directory Property System.IO.DirectoryInfo Direc...
...
BaseName ScriptProperty System.Object BaseName {get=i...
VersionInfo ScriptProperty System.Object VersionInfo {ge...
在您的示例中,$latest.Name
返回属性Name
的值,如上所示,它只是没有路径的文件名。因此$fileName
仅包含值filename
,而不包含c:\users\pb\desktop\source\filename
。