How to set LastWriteTime property of a file?

99封情书 提交于 2019-12-07 12:51:54

问题


I would like to change the creation date of the files that I generate with this script :

$clientname = Read-Host "Enter the client name"
$path = Read-Host "Enter the complete path of .bak files"

$time = "01-00-00"
$space = " "


for ($i = 0; $i -lt 7;$i++)
{

$date = (Get-Date).AddDays(-1-$i).ToString('yyyy-MM-dd') 

New-Item -ItemType file $path$clientname$space$date$space$time.bak

}

So it gives me theses files :

Mode                LastWriteTime     Length Name                                                          
----                -------------     ------ ----                                                          
-a---        16/08/2013     16:55          0 client 2013-08-15 01-00-00.bak                                  
-a---        16/08/2013     16:55          0 client 2013-08-14 01-00-00.bak                                  
-a---        16/08/2013     16:55          0 client 2013-08-13 01-00-00.bak                                  
-a---        16/08/2013     16:55          0 client 2013-08-12 01-00-00.bak                                  
-a---        16/08/2013     16:55          0 client 2013-08-11 01-00-00.bak                                  
-a---        16/08/2013     16:55          0 client 2013-08-10 01-00-00.bak                                  
-a---        16/08/2013     16:55          0 client 2013-08-09 01-00-00.bak  

I want to modify the LastWriteTime property of each files, I want it to be the same as the date in the file name.

Example for this file "client 2013-08-15 01-00-00.bak" the LastWriteTime will be "15/08/2013 01:00"

I'm stuck and I do not how can we do that

Thank you


回答1:


Not tested, but try this in your loop after you call New-Item:

$file = Get-ChildItem $path$clientname$space$date$space$time.bak
$file.LastWriteTime = (Get-Date).AddDays(-1-$i)

If you want to see a full listing of things you can do with FileInfo objects, try calling $file | gm in your powershell console. You could also view the docs on MSDN.




回答2:


for ($i=0; $i -lt 7;$i++)
{
     $date = (Get-Date).AddDays(-1-$i)
     $filedate = $date.ToString('yyyy-MM-dd') 
     $file = New-Item -ItemType File $path$clientname$space$filedate$space$time.bak
     $file.LastWriteTime = $date
}


来源:https://stackoverflow.com/questions/18276452/how-to-set-lastwritetime-property-of-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!