2014-11-17 3 views
0

"Datamonitor"라는 단어가 들어있는 디렉토리 내의 모든 파일을 검색하고 "Datamonitor"라는 접두어가 붙은 기존 이름을 사용하여 파일의 이름을 바꾸는 스크립트를 작성하려고합니다.Powershell, 키워드가 들어있는 파일을 찾은 다음 해당 파일의 이름을 바꿉니다.

SelectString cmdlet을 사용했지만이 방법을 사용할 수없는 것 같습니다. 아마도 수정 될 수있는 코드를 발견했지만 어떻게 해결할 수 없었습니다.

$directoryToTarget=$args[0] 
$wordToFind=$args[1] 
$wordToReplace=$args[2] 

Clear-Content log.txt 

Get-ChildItem -Path $directoryToTarget -Filter *.properties -Recurse | where { !$_.PSIsContainer } | % { 

$file = Get-Content $_.FullName 
$containsWord = $file | %{$_ -match $wordToFind} 
If($containsWord -contains $true) 
{ 
    Add-Content log.txt $_.FullName 
    ($file) | ForEach-Object { $_ -replace $wordToFind , $wordToReplace } | 
    Set-Content $_.FullName 
} 
} 

사람이 내 키워드 검색이 개정 도울 수 및 .properties의 파일을 Rename-Item -Newmane {"Datamonitor_""+$_.Name}

많은 감사

답변

0

다음은 모든 모양 *을 포함겠습니까 그들은 키워드를 포함하는 경우 'DataMonitor'파일의 이름이 바뀝니다.

Get-ChildItem -Path $directoryToTarget -Filter *.properties -Recurse | where { !$_.PSIsContainer } | % { 

    $i = Get-Content $_ |Select-String "Datamonitor" -SimpleMatch 

    if ($i -ne $null) 
    { 
     Rename-Item $_ -NewName ('Datamonitor_'+$_.name) 
    } 
} 

단점은 한 번만 실행할 수 있다는 것입니다. 여러 번 실행하면 파일 이름에 'Datamonitor_'가 추가됩니다. 이것은 쉽게 고칠 수 있습니다.

추신. 귀하의 질문에 모든 파일을 요청한 다음 get-childitem에서 필터를 지정하십시오. 당신이 원하는 모든 파일을 경우 나는 그냥 파일 내용를, 파일 이름$wordToFind의 경기에 대한 * .properties의

+0

도움 주셔서 감사합니다. – sticks

+0

죄송합니다. 질문이 하나 더 있습니다 ... "datamonitor"가 포함 된 모든 파일의 파일 이름을 포함하는 텍스트 파일을 만들고 싶다면 어떻게해야합니까? 'ForEach-Object {$ _. Name}> C/path/file.txt'와 같은 것으로'Rename-Item'을 바꿀 수 있습니까? – sticks

+0

ForEach-Object {$ _. Name | out-file C : \ path \ file.txt -append –

0
$file | %{$_ -match $wordToFind} 

검사를 -filter 제거,이 예제의 요구에 맞게 필터를 사용했다. 후자의 경우

$file | ? { (Get-Content $_) -pattern $wordToFind } 

또는 (더 나은) 같은 두 가지가 정규 표현식과 일치 할 것을

$file | ? { Select-String -LiteralPath $_ -Pattern $wordToFind } 

주의가 필요합니다, 그래서 $wordToFind에 특수 문자가 포함 된 경우 제대로을 탈출해야합니다

[regex]::Escape($wordToFind) 
+0

도움 주셔서 감사합니다. – sticks

관련 문제