2013-07-16 160 views
0

我有一個.txt文件中沒有擴展名約500個文件名。我有另一個.txt文件,全文件名超過1000個。Powershell搜索和替換

我需要遍歷較小的.txt文件並搜索當前在較大的.txt文件中讀取的行。如果找到它,則將該名稱複製到新的found.txt文件中,如果沒有,則移動到較小的.txt文件中的下一行。

我是新來的腳本,不知道從這裏開始。

Get-childitem -path "C:\Users\U0146121\Desktop\Example" -recurse -name | out-file C:\Users\U0146121\Desktop\Output.txt #send filenames to text file 
(Get-Content C:\Users\U0146121\Desktop\Output.txt) | 
ForEach-Object {$_ 1 

讓我知道如果這沒有意義。

+0

你可以添加一些示例輸入和你想要的輸出?這將有助於我們更好地理解這個問題。 – Eris

+0

請退後一步,描述您嘗試解決的實際問題,而不是您認爲的解決方案。你想通過這樣做來達到什麼目的? –

回答

1

您的示例顯示您通過遞歸通過文件夾桌面創建文本文件,您不需要文本文件循環,您可以使用該文件,但可以說,您生成短名稱的文本文件像你說的那樣。

$short_file_names = Get-Content C:\Path\To\500_Short_File_Names_No_Extensions.txt 

現在,你可以通過該數組有兩種方式循環:

使用foreach關鍵字:

foreach ($file_name in $short_file_names) { 
    # ... 
} 

或者使用ForEach-Object的cmdlet:

$short_file_names | ForEach-Object { 
    # ... 
} 

最大的區別是當前項目將是一個命名變量$file_name中的第一個和第二個中的非命名內置變量$_

假設你使用第一個。您需要查看$file_name是否在第二個文件中,如果是,請記錄您是否找到它。可以這樣做。我已在代碼中解釋每個部分的註釋。

# Read the 1000 names into an array variable 
$full_file_names = Get-Content C:\Path\To\1000_Full_File_Names.txt 

# Loop through the short file names and test each 
foreach ($file_name in $short_file_names) { 

    # Use the -match operator to check if the array contains the string 
    # The -contains operator won't work since its a partial string match due to the extension 
    # Need to escape the file name since the -match operator uses regular expressions 

    if ($full_file_names -match [regex]::Escape($file_name)) { 

     # Record the discovered item 
     $file_name | Out-File C:\Path\To\Found.txt -Encoding ASCII -Append 
    } 
}