2015-01-08 112 views
1

需要一個PowerShell腳本,將文件夾和文件從一個位置移動到另一個位置,然後是舊的x天,但某些文件夾是免費的。需要一個PowerShell腳本,將文件夾和文件從一個位置移動到另一個位置

還需要有能力通過電子郵件發送它移動的文件和文件夾的列表。

我可以移動文件夾中的文件,但我不確定如何移動整個文件夾。

下面是一些代碼,到目前爲止,我已經把任何建議將是巨大

Set-ExecutionPolicy RemoteSigned 

#----- define parameters -----# 
#----- get current date ----# 
$Now = Get-Date 
#----- define amount of days ----# 
$Days = "7" 
#----- define folder where files are located ----# 
$TargetFolder = "C:\test" 
$TargetPath = "C:\test5" 

#----- define extension ----# 
$Extension = "*.*" 
#----- define LastWriteTime parameter based on $Days ---# 
$LastWrite = $Now.AddDays(-$Days) 

#----Exclusion List ----# 
$exclude [email protected]('test1', 'test2') 


#----- get files based on lastwrite filter and specified folder ---# 
$Files = Get-Childitem -path $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime  -le "$LastWrite"} -and $_Name -ne $exclude | foreach ($_)} #- 


foreach ($File in $Files) 
    { 
    if ($File -ne $NULL) 
     { 
     write-host "Deleting File $File" -ForegroundColor "DarkRed" 
     Move-Item $File.FullName $TargetPath -force 
     } 
    else 
     { 
     Write-Host "No more files to delete!" -foregroundcolor "Green" 
     } 
    } 
+0

你選擇基於文件的目錄lastwrite時間或你是否需要查看文件夾本身的最後一次寫入時間而不考慮內容? – Matt

+0

實際上,文件夾的lastwritetime本身與內容無關。 – user4432997

回答

0

支撐在PowerShell的V3或更高的簡寫。這將找到所有的文件夾,其中LastWriteTime比7天更舊,並移動它們。

$LastWrite = (Get-Date).AddDays(-7) 
gci c:\temp -Directory -Recurse | ?{$_.LastWriteTime -le $LastWrite} | select -expand fullname | %{Move-Item $_ $TargetPath} 

如果您只是查看文件夾時間以避免邏輯錯誤,那麼文件排除就沒有意義。同樣的代碼,但更易於閱讀:

$LastWrite = (Get-Date).AddDays(-7) 
Get-ChildItem $TargetFolder | Where-Object{$_.LastWriteTime -le $LastWrite} | Select-Object -ExpandProperty FullName | ForEach-Object{ 
    Move-Item $_ $TargetPath 
} 

買者

有可能是你在哪裏試圖移動文件夾和家長可能先前已經被移動的問題。真的沒有測試環境來檢查現在。爲了以防萬一,可以在副本之前使用一點測試。

If(Test-Path $_){Move-Item $_ $TargetPath} 

爲使用電子郵件電子郵件

的一個起點將是Send-MailMessage。還有其他方法。

文件夾排除

如果你想省略某些文件夾中有一對夫婦的方式來實現這一目標。如果您知道要刪除的整個文件夾名稱,則可以像您已有的那樣添加此$exclude [email protected]('test1', 'test2'),並更改Where子句。

Where-Object{$_.LastWriteTime -le $LastWrite -and $exclude -notcontains $_.Name} 

如果您不知道全名,也許這$exclude只包含你可以這樣做的部分名稱使用,以及一點點的正則表達式

$exclude [email protected]('test1', 'test2') 
$exclude = "({0})" -f ($exclude -join "|") 

#..... other stuff happens 

Where-Object{$_.LastWriteTime -le $LastWrite -and $_.Name -notmatch $exclude} 
+0

謝謝,我將如何去爲某些文件夾添加例外,而不是文件本身。例如,假設我有一個包含20個子文件夾的文件夾,並且我想移動20個文件夾。如何爲我不想移動的文件夾添加例外列表? – user4432997

+0

@ user4432997請參閱更新 – Matt

+0

如果文件夾可能已存在於目標中。有沒有辦法將它設置爲覆蓋它。目前,如果該文件已存在於目標中,則該文件將失敗,並且該文件已存在時無法創建文件。我知道你已經包含該測試If(Test-Path $ _){Move-Item $ _ $ TargetPath},但即使它存在,我也希望它能夠繼續並覆蓋。 – user4432997

相關問題