推薦這個blog:

Award


(ASP.NET 2010、2011、2012年)

其他資源

簡體中文blog

最新回應

需求說明
要將某個目錄底下,所有目錄裡面的所有符合條件的檔案,備份、記錄並清空原本檔案內容。條件有二:第一,特定副檔名。第二,檔案內容包含特定字串。

範例

#created by 91, 檢查路徑是否存在,若不存在則建立folder
function CheckFolderExist($path)
{	
	if ((Test-Path $path) -ne $true)
    {			
		$o = mkdir $path		
    }
}

#檢查$path裡面所有副檔名為$extension的檔案,內容含有$pattern字串的檔案,按照其目錄結構備份到$backupPath,並將檔案清空
function DoStuff
{
	param ($path, $pattern, $extension, $backupPath)
		
	#透過-recurse 將$path底下所有目錄裡面,所有副檔名為$extension的檔案讀出來
	$File = Get-ChildItem $path -include *.$extension -recurse
		
	$StringVid = $pattern
	foreach ($Entry in $File) {
		#使用select-string -pattern,檢查檔案內容是否包含$pattern
		$List = select-string -pattern $StringVid $Entry
		if ($List.LongLength -gt 1) {		  		  
		  
		  #目標檔案的目錄結構
		  $backupDirPath =  $Entry.DirectoryName -replace [regex]::Escape($path) , ""
		  $backupDes = $backupPath + $backupDirPath + "\"
		  
		  CheckFolderExist $backupDes
		  
		  $Entry.FullName >> $backupPath\BouncerFileList.txt
		  cpi $Entry $backupDes		  		  		  
		  
		  #清空原本檔案內容
		  Set-Content $Entry.FullName ""
		  		  
		}
	}		
}

$path = "C:\MyHtmlFolder" #檢查目標路徑
$pattern = "不該出現的網頁內容" #網頁內容pattern
$extension = "html" #副檔名
$backupPath = "C:\backup" #備份路徑
DoStuff $path $pattern $extension $backupPath


結論
一樣,只是memo一下一些相關的語法,加上大家可能在管理file server上,可能需要定時的清理一下log檔或針對特殊內容的檔案進行處理。所以記錄一下,寫法還很C#,不太Shell,請海涵。若有建議的寫法,也請不吝賜教。


點部落-In Joey

↑ Grab this Headline Animator


關連文章

[.NET]產生AES的Key與IV

[jQuery]將marquee plugin封裝成User Control

[MSDN文件庫]The specified CGI application encountered an error and the server terminated the process

[Memo]使用Trim(Char[])要注意的地方

回應

目前沒有回應.

登入後使用進階評論

Please add 1 and 2 and type the answer here: