0

I would like to use powershell to read and write to a database as part of a larger project. The connection string is already in the appsettings.json file in the project.

I searched around and found $json = Get-Content 'appsettings.json' | Out-String | ConvertFrom-Json

I keep getting an error:

ConvertFrom-Json : Invalid object passed in, ':' or '}' expected. (252): {

But the file has no issue when it is being read in by the C# application.

Is there a way to read the system configuration files in the same fashion as a C# application?

Something like:

 var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        Configuration = builder.Build();

Thanks in advance.

  • The implication is that your `appsettings.json` doesn't contains _invalid JSON_, at least based on the parsing that `ConvertFrom-Json` performs. Without additional information, it's impossible to diagnose your problem. For an _online_ way to validate JSON, try https://www.online-json.com/json-validator – mklement0 May 10 '23 at 22:25

2 Answers2

0

Your commands are correct, the out-string is not necessary, but does not break anything either.

Get-Content appsettings.json | ConvertFrom-Json

Are you sure you are getting the right file from the right directory? If in doubt, have the contents of the file displayed directly in PowerShell.

Get-Content appsettings.json

Generally, you can access a connection string from appsettings.json this way:

(Get-Content appsettings.json | ConvertFrom-Json).ConnectionStrings.MyDatabase

In my example, I get the connection string with the name "MyDatabase". The appsettings.json for this example looks like this:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
  }
  },
  "ConnectionStrings": {
    "MyDatabase": "Server=localhost;Database=test;"
  },
}
Jann Westermann
  • 291
  • 1
  • 2
  • Note that while `Out-String` isn't necessary, it can make a difference, due to heuristics built into `ConvertFrom-Json`. However, the much more efficient equivalent to using `Out-String` is to simply use the `-Raw` switch with `Get-Content` - see [this answer](https://stackoverflow.com/a/71053689/45375). Your answer contains useful information in general, but given that the actual problem may simply be _invalid JSON_, I feel that simply pointing that out _in a comment_ may have been the better response. – mklement0 May 10 '23 at 22:31
0

I found that I have comments in my json file. I ended up using:

$json = Get-Content '.appsettings.json' | Where-Object {$_ -notmatch '//'} | Out-String 
$json = $json | ConvertFrom-Json

This removed the comment line and everything converted as I expected. I was able to get my connection string:

$Conn01 = new-object System.Data.SqlClient.SqlConnection $json.ConnectionStrings.DefaultConnection