Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12201

Powershell script is holding a file during append resulting in error

$
0
0

I am trying to write script to extract some data from json and then append them to .txt file for my next Use-Case.

When I execute code below:

$columns = "ID_Report","Name","Created_by","Last_mod_by"$file = Get-Content -Path "W:\Personal\Ulrich\VA-Scraping\reports.json" -Raw | ConvertFrom-Json$key_first = "items"Write-Output "$($columns[0]);$($columns[1]);$($columns[2]);$($columns[3]);$($columns[4])" > xxx.txtforeach ($record in $file){    if ($record | Select-Object -ExpandProperty $key_first -ErrorAction SilentlyContinue){         foreach ($item in $record.items){"$($item.id);$($item.name);$($item.createdBy);$($item.modifiedBy)" | Add-Content "W:\Personal\Ulrich\Skriptiky\xxx.txt"         }    }}

I get many errors resulting in truncation of exported data:

Add-Content : The process cannot access the file 'W:\Personal\Ulrich\Skriptiky\xxx.txt' because it is being used by another process.At line:12 char:82+ ... tem.modifiedBy)" | Add-Content "W:\Personal\Ulrich\Skriptiky\xxx.txt"+                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : WriteError: (W:\Personal\Ulrich\Skriptiky\xxx.txt:String) [A    dd-Content], IOException+ FullyQualifiedErrorId : GetContentWriterIOError,Microsoft.PowerShell.Commands.AddCon    tentCommand

Is there a way to fix this?

Edit:Tried direct aproach, but still the same result.Changed the code to code below and looks like it works better now.

$columns = "ID_Report","Name","Created_by","Last_mod_by"$file = Get-Content -Path "W:\Personal\Ulrich\Skriptiky\VA-Scraping\reports.json" -Raw | ConvertFrom-Json$outfile = "W:\Personal\Ulrich\Skriptiky\VA-Scraping\vystupy\$(Get-Date -f yyyyMMdd).txt"$key_first = "items"Write-Output "$($columns[0]);$($columns[1]);$($columns[2]);$($columns[3]);$($columns[4])" | Out-File -FilePath $outfile$file | ForEach-Object {$_.items } | ForEach-Object {Write-Output "$($_.id);$($_.name);$($_.createdBy);$($_.modifiedBy)"} |  Add-Content "$outfile"

I take this as answered, thank you for your advices.


Viewing all articles
Browse latest Browse all 12201

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>