2017-12-12 15 views
0

폴더에서 SQL 파일을 작업하고 이름을 바꾸고 파일 내용이 '/ ** '파일 내용에서 처음 세 줄을 제거하고 파일을 덮어 쓰려고합니다. 아래 코드는 작동하지만 주석 처리 된 행 중 하나를 추가하면 오류 메시지가 반환됩니다. 내가 주석 라인 중 하나를 꿔Where-Object 및 StartsWith를 사용하여 내용을 기반으로 파일을 필터링하는 방법 - Powershell v4.0

function Get-ScriptDirectory 
{ 
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value 
    Split-Path $Invocation.MyCommand.Path 
} 

$sqlfolder = Get-ScriptDirectory 

$files = Get-ChildItem $sqlfolder\* -Include *.sql 

Foreach ($file in $files) { 
    Write-Output $file.name 
    $newName = $file.name.Substring($file.name.LastIndexOf(" ")+1) 
    Rename-Item $file -NewName $newName 
    get-content $file | 
    ##Where-Object {$_.StartsWith("/**")} | 
    ##Where-Object {$_ -Like "/**"} | 
     select -Skip 3 | 
     set-content "$file-temp" 
    move "$file-temp" $file -Force 
} 

은 처음 세 줄은 문자열 '/ **'로 시작하는 파일에서 제거 될 수 있도록합니다.

오류 메시지 :

move : Cannot find path ...-temp' because it does not exist. 
... ObjectNotFound ... PathNotFound ... 
+2

'파일 내용이 '/ **''로 시작하지만'/ ** '로 시작하는 줄만 필터링하고 그 중 3 줄은 건너 뜁니다.' 'set-content'에 어떤 라인도 공급되지 않습니다. 코드에'if'를 써야합니다. – TessellatingHeckler

+0

Rename-Item $ 파일 -NewName $ newName 사용자 이름을 가져야합니다. get-content $ newName이 필요합니다. –

+0

@TessellatingHeckler에서 제안한대로 IF 조건을 작성하고 조건이 충족되지 않는 경우 else 조건을 유지하십시오. 그게 너의 문제를 해결해야 해. –

답변

1

가 난 단지 텍스트로 시작하는 파일을 수정 할 수 있었다 '/ **'는 의견 제안 등의 If를 사용하여.

function Get-ScriptDirectory 
{ 
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value 
    Split-Path $Invocation.MyCommand.Path 
} 

$sqlfolder = Get-ScriptDirectory 

$files = Get-ChildItem $sqlfolder\* -Include *.sql 

Foreach ($file in $files) { 
    # Write-Output $file.name 
    $newName = $file.name.Substring($file.name.LastIndexOf(" ")+1) 
    Rename-Item $file -NewName $newName 

    $firstLine = (Get-Content $file)[0] 

    if ($firstLine.StartsWith("/**")){ 
     Get-Content $file | 
     select -Skip 3 | 
     set-content "${file}-temp" 
     move "${file}-temp" $file -Force 
    } 
}