out-file -filepath $ target -append在ISE中工作,否则失败

时间:2018-05-18 17:07:39

标签: file powershell out powershell-ise

我创建了一个脚本来从CSV文件构建SQL查询文件。当我在ISE中运行它时,它可以正常工作并完全按照我的预期构建文件。但是,如果我尝试从powershell或cmd会话启动脚本,我会收到错误:

Out-File : The process cannot access the file
'C:\Users\user.name\Documents\Working\terrorist525.sql' because it is
being used by another process.

脚本如下:

$start | out-file -filepath $target1 -append
$infile = $source1
$reader = [System.IO.File]::OpenText($infile)
$writer = New-Object System.IO.StreamWriter $file1;

$counter = 1
try {
    while (($line = $reader.ReadLine()) -ne $null)
    {
        $myarray=$line -split "\t" | foreach {$_.Trim()}
        if ($myarray[0] -Match "\d{1,4}\.\d{1,3}" -and $myarray[1] -ne {$null}){
$myarray[1] = $myarray[1] -replace "'","''"
$myarray[2] = $myarray[2] -replace "'","''"
$myarray[3] = $myarray[3] -replace "'","''"
$myarray[4] = $myarray[4] -replace "'","''"
$myarray[5] = $myarray[5] -replace "'","''"
"Insert into #terrorist Select convert(varchar(60),replace('OSFI Name: "+$myarray[1],$myarray[2],$myarray[3],$myarray[4],$myarray[5]+,"','''''','''')), no_,branch,name,surname,midname,usual,bname2 " | Out-File -filepath $target1 -append -force
If ($myarray[1] -eq "") {$myarray[1]=”~”}
If ($myarray[2] -eq "") {$myarray[2]=”~”}
If ($myarray[3] -eq "") {$myarray[3]=”~”}
If ($myarray[4] -eq "") {$myarray[4]=”~”}
If ($myarray[5] -eq "") {$myarray[5]=”~”}
"from cust where cust.surname in ('"+$myarray[2]+,"','"+$myarray[1]+,"','"+$myarray[3]+,"','"+$myarray[4]+,"','"+$myarray[5]+,"') and ( name in ('"+$myarray[1]+,"', '"+$myarray[2]+,"', '"+$myarray[3]+,"', '"+$myarray[4]+,"', '"+$myarray[5]+,"') or 
midname in ('"+$myarray[1]+,"', '"+$myarray[2]+,"', '"+$myarray[3]+,"', '"+$myarray[4]+,"', '"+$myarray[5]+,"') or 
usual in ('"+$myarray[1]+,"', '"+$myarray[2]+,"', '"+$myarray[3]+,"', '"+$myarray[4]+,"', '"+$myarray[5]+,"') or 
bname2 in ('"+$myarray[1]+,"', '"+$myarray[2]+,"', '"+$myarray[3]+,"', '"+$myarray[4]+,"', '"+$myarray[5]+,"') ) 
go" | Out-File -filepath $target1 -append -force

        }   

            #$writer.WriteLine($original);

            #Write-Output  $original;
            #Write-Output  $newlin
    }
}
finally {
    $reader.Close()
    $writer.Close()
}

$end1 | Out-File -filepath $target1 -append
(GC $target1).replace("?","") | Set-Content $target1

在运行$start | add-content -path $target1时,好像out-file没有放弃文件 我读过的所有内容都说不应该这样。

2 个答案:

答案 0 :(得分:0)

虽然它没有回答为什么你的文件被锁定的问题,但我确实保留了一个使用SysInternal的Handle.exe从文件中删除锁的函数。

class

答案 1 :(得分:0)

$start | Out-File -filepath $target1 -append

$infile = $source1
$reader = [System.IO.File]::OpenText($infile)
$writer = New-Object System.IO.StreamWriter $file1;
$writer.Close()
$counter = 1
try {

通过在此特定位置添加$ writer.close(),它解决了问题。