0

ファイル内の文字列を検索して、文字列を含むファイル名を表示しようとしています

以下のようなスクリプトを作成しました。

Function GetFileContainsData ([string] $Folderpath,[string] $filename, [string] $Data) { 

    $Files=Get-ChildItem $Folderpath -include $filename -recurse | Select-String -pattern $Data | group path | select name
    return,$Files
}

$configFiles= GetFileContainsData "C:\MyApplication" "web.config" "localhost"
Foreach ($file in $configFiles) { Add-Content -Path "Filelist.txt" -Value $file.Name}

このスクリプトは、文字列「localhost」を含むすべてのファイル名をFilelist.txtに書き込みます。

複数の文字列を見つけたいのですが。配列を渡すと

$stringstofind=("localhost","$env:ComputerName")
Foreach ($strings in $stringsToFind) {
    $configFiles= GetFileContainsData $Installpath "web.config" $strings
    Foreach ($file in $configFiles) { Add-Content -Path "Filelist.txt" -Value $file.Name}
}

ファイルのリストとともに配列内の各文字列を検索し、更新します。同じファイルに両方の文字列がある場合、Filelist.txtにそのファイルの2つのエントリがあります。

ファイル内で複数の文字列を見つけて、ファイルの名前をリストすることは可能ですか?[ファイル名の冗長な入力を排除するため]

4

2 に答える 2

2

実際には、のパラメータとして をSelect-String受け入れるので、ループは必要ありません。string[]-Pattern

Get-Uniqueその後、重複を削除するために使用できます。

実際、Select-Stringファイルのリストもパスとして受け入れるため、次のようにすることができます。

Get-ChildItem $FolderPath -Include $Filenames -Recurse | Select-String -Pattern $StringsToFind | Select-Object path | Sort-Object | Get-Unique -AsString

関数とループを 1 行に置き換える

編集:最終的な作業バージョンは

$Files=Get-ChildItem $Folderpath -include $filename -recurse | Select-String -pattern $Data | group path | select name |Get-Unique -AsString
于 2012-08-21T07:26:20.547 に答える
0

次のスクリプトは、私が抱えていた問題を解決します。carlpett の有益な情報をありがとう

<#
    .NAME
        Get-FilenameHasString
    .SYNOPSIS
        To search strings in file and return the filenames.
    .DESCRIPTION
        This script will be useful to find strings in list of files.
        It will eliminate the duplicate filenames
    .PARAMETER Filenames
        This parameter will be having filenames where the string needs to be searched.
    .PARAMETER FolderPath
        This parameter will be having folder where it will look for the filenames
    .PARAMETER StringsToFind
        This parameter will be having the strings to be searched
    .EXAMPLE
       .\Get-FilenameHasString -Filenames "Web.config" -FolderPath "C:\Program Files (x86)\MyProj" -$StringsToFind ("$env:ComputerName","localhost")
       To get the  list of web.config files which is there in Folder path having StringsTofind. The result will be saved in Filelist.log by default.
    #>

Param ( 
    $Filenames="web.config",
    $FolderPath="C:\Program Files (x86)\MyProj",
    $StringsToFind=("$env:ComputerName","localhost"),
    $Logfile="FileList.log"
    )

$configFiles= Get-ChildItem $FolderPath -Include $Filenames -Recurse | Select-String -Pattern $StringsToFind | Group path | select name | Get-Unique -AsString
Foreach ($file in $configFiles) { Add-Content -Path $Logfile -Value $file.Name}
于 2012-08-27T12:15:26.523 に答える