Powershell get-content command - powershell

I am trying to return only key from the text file having below content
{
"expires": "2018-02-24T19:40:35.000Z",
"id": "xtysdasdagsweasdasvfdsgsdfcxaxasdasrgdascasdasdasxacasdgshgsfdfgasdasdsaedasdasdasfeasdfasdasdasd==",
"testvalue1": "test_tenant"
}
above mentioned "id" is token which keep getting change everyday.
my final out put should only content id value without "" something like below.
xtysdasdagsweasdasvfdsgsdfcxaxasdasrgdascasdasdasxacasdgshgsfdfgasdasdsaedasdasdasfeasdfasdasdasd==
I have tried with '''get-content -path c:..\filname.txt | select-string "id"''' but it does not return only key as mentioned above.
it returns full line
"id": "xtysdasdagsweasdasvfdsgsdfcxaxasdasrgdascasdasdasxacasdgshgsfdfgasdasdsaedasdasdasfeasdfasdasdasd==",
How to select only specific output I am referring?

Get-Content reads the file off disk, but you need to convert the resulting JSON string to an object you can interact with to get the id value:
# Read from disk and convert from JSON
$data = Get-Content -Path C:\path\to\filname.txt |ConvertFrom-Json
# Now we can dereference the `id` property value alone
$data.id

Related

Concatenate CSV results into a single variable with PowerShell

I'm trying to deploy our company URLs in Google Chrome as "Managed Bookmarks" using PowerShell. In order to accomplish the same thing using IE favorites I created a CSV file with 2 columns containing a Name and URL respectively. I import that CSV then I have a foreach statement that will go through each line and create a .url file in the user's favorites. To minimize effort for my staff I want to use this same CSV file for the Chrome Bookmarks so we only have one file to maintain. Then it wouldn't be necessary for us to modify and redeploy the script, and we could publish the CSV file on a network share to be updated as needed.
Chrome has a registry value that allows me to do what I need. Using 3 search engines as an example, I know how to "hard code" this and make it work.
$PolicyPath = 'Registry::HKEY_LOCAL_MACHINE\Software\Policies'
$GoogleKey = 'Google'
$ChromeKey = 'Chrome'
$ManagedBookmarks = '[ { "name": "Bing", "url": "http://www.bing.com" }, { "name": "Google", "url": "http://www.google.com" },{ "name": "Yahoo", "url": "http://www.yahoo.com" } ]'
Set-ItemProperty -Path "$($PolicyPath)\$($GoogleKey)\$($ChromeKey)" -Name 'ManagedBookmarks' -Value "$ManagedBookmarks" -Type String
Is there a way to do a foreach and concatenate the results into a single variable? That will result in the following format:
$ManagedBookmarks = "[ { "name:" "$($line.name)", "url": "$($line.url)"}, { "name:" "$($line+n.name)", "url": "$($line+n.url)"} ]"
If you have a CSV (call it csv.csv) file like the following, you can just import the CSV to create an object array and then convert the whole thing to a JSON object.
Name,URL
Bing,http://www.bing.com
Google,http://www.google.com
Yahoo,http://www.yahoo.com
$ManagedBookmarks = Import-Csv csv.csv | ConvertTo-Json
Per LotPings Recommendation, if you dislike the line feeds and/or carriage returns and extra spacing in that output, you can use the -Compress switch.
$ManagedBookmarks = Import-Csv csv.csv | ConvertTo-Json -Compress

Use a for loop for list and set element to environment variable then get value

I'm not familiar with powershell at all and only need it for a few commands. I was hoping that someone could assist me. I have a json file named optionsConfig.json that reads like so,
{
"test1": ["options_size", "options_connection", "options_object"],
"test2":["options_customArgs", "options_noUDP", "options_noName"]
}
In my powershell file, I have one line so far and this is to get the content of the json file.
$rawData = Get-Content -Raw -Path "optionsConfig.json" | ConvertFrom-Json
I had planned on having an environment variable on my system named test that would have the value of test1 or test2 and from that, I would look at the elements of the list in the associated value in the json file. With these elements from the list, I would assume that they are also environment variables and I would want to get their values. ( a list comprehension in python would be perfect here).I'm a python guy so I am not quite certain how to show this in powershell but say I did env = getEnvironmentVariable(test) and that equals test1. I would then say something like for i in $rawData.env
return getEnvironmentVariable(i)
I pretty much want another list or new json object with the values for the assumed environment variables that we get from the original json object.
Is there a way that I can do this in powershell? It would help a lot if anyone could assist. I apologize if I wasn't clear with anything. Thanks
(edit) I see that $rawData.Get-ChildItem Env:test does not work. Is there someone to write something like this in order to get the correct list from json file?
Also setting a new variable like so $var1 = Get-ChildItem Env.tool and doing $rawData.$test.value has no effect either.
# Sample values: make environment variable 'test' ($env:test)
# point to property 'test1'
$env:test = 'test1'
# Provide sample values for the environment-variable names listed
# in the 'test1' property.
$env:options_size = 'size1'
$env:options_connection = 'conn1'
$env:options_object = 'obj1'
# Read the JSON file into a custom object.
$configObj = Get-Content -Raw optionsConfig.json | ConvertFrom-Json
# Retrieve the environment variables whose
# names are listed in the $env:test property ('test1' in this example),
# as name-value pairs.
Get-Item -Path env:* -Include $configObj.$env:test
The above yields an array of [System.Collections.DictionaryEntry] instances each representing an environment variable's name and value:
Name Value
---- -----
options_connection conn1
options_object obj1
options_size size1
To convert the above to JSON:
Get-Item -Path env:* -Include $configObj.$env:test |
Select-Object Name, Value | ConvertTo-Json
Note: The seemingly redundant Select-Object call is necessary to strip additional properties that PowerShell adds behind the scenes, which would otherwise show in the resulting JSON.
If you wanted to rename the properties in the resulting JSON, you'd need Select-Object anyway, using calculated properties.
This yields:
[
{
"Name": "options_connection",
"Value": "conn1"
},
{
"Name": "options_object",
"Value": "obj1"
},
{
"Name": "options_size",
"Value": "size1"
}
]
I don't see a problem, just set and use $ENV:test
$rawdata = Get-Content .\optionsconfig.json | convertfrom-json
$Env:Test="test1"
$rawdata.$ENV:Test
$Env:Test="test2"
$rawdata.$ENV:Test
Sample output
options_size
options_connection
options_object
options_customArgs
options_noUDP
options_noName

GeoJson Powershell

I have a geojson file that needs to be submitted to an API. I am modifying a preexisting powershell script to execute this query but I am having trouble getting the geojson to parse correctly in the query string to pass to the API. Powershell is not my language at all but I've been able to get it to read the geojson. My print statement in my code looks like this:
$inputjson = Get-Content -Raw -Path C:/path/to/file.geojson | ConvertFrom-Json
Foreach ($feature in $inputjson.features){
$gjson = $feature.geometry
Write-Host $gjson
My output is then:
#{type=Polygon; coordinates=System.Object[]}
I have tried ToString() or even casting $gjson as string to try and force this to read as it appears in the file. In python I can do this easily enough but this is a complex script I don't have the time to rewrite from scratch. How do I get this to translate to string correctly? What exactly does that '#' decorator connote in json subfield in Powershell?
The point is that GeoJSON is not a flat object. This means that you have to (recursively) iterate through each embedded object to get each containing subitem:
$inputjson = Get-Content -Raw -Path C:/path/to/file.geojson | ConvertFrom-Json
Foreach ($feature in $inputjson.features){
$gjson = $feature.geometry
Write-Host "Type = " $gjson.Type
Foreach ($coordinate in $coordinates){
Write-Host "coordinate = " $coordinate
Maybe this will help you: $inputjson | Flatten, see: https://stackoverflow.com/a/46081131/1701026
#{key=value} is an hashtable
it's not clear what you are trying to achieve, maybe you want to reconvert ypur geometry to json ?
if so
$feature.geometry | ConvertTo-Json
is what you need

Read a CSV in powershell with a variable number of columns

I have a CSV that contains a username, and then one or more values for the rest of the record. There are no headers in the file.
joe.user,Accounting-SG,CustomerService-SG,MidwestRegion-SG
frank.user,Accounting-SG,EastRegion-SG
I would like to read the file into a powershell object where the Username property is set to the first column, and the Membership property is set to either the remainder of the row (including the commas) or ideally, an array of strings with each element containing a single membership value.
Unfortunately, the following line only grabs the first membership and ignores the rest of the line.
$memberships = Import-Csv -Path C:\temp\values.csv -Header "username", "membership"
#{username=joe.user; membership=Accounting-SG}
#{username=frank.user; membership=Accounting-SG}
I'm looking for either of these outputs:
#{username=joe.user; membership=Accounting-SG,CustomerService-SG,MidwestRegion-SG}
#{username=frank.user; membership=Accounting-SG,EastRegion-SG}
or
#{username=joe.user; membership=string[]}
#{username=frank.user; membership=string[]}
I've been able to get the first result by enclosing the "rest" of the data in the csv file in quotes, but that doesn't really feel like the best answer:
joe.user,"Accounting-SG,CustomerService-SG,MidwestRegion-SG"
Well, the issue is that what you have isn't really a (proper) CSV. The CSV format doesn't support that notation.
You can "roll your own" and just process the file yourself, something like this:
$memberships = Get-Content -LiteralPath C:\temp\values.csv |
ForEach-Object -Process {
$user,$membership = $_.Split(',')
New-Object -TypeName PSObject -Property #{
username = $user
membership = $membership
}
}
You could do a half and half sort of thing. Using your modification, where the groups are all a single field in quotes, do this:
$memberships = Import-Csv -Path C:\temp\values.csv -Header "username", "membership" |
ForEach-Object -Process {
$_.membership = $_.membership.Split(',')
$_
}
The first example just reads the file line by line, splits on commas, then creates a new object with the properties you want.
The second example uses Import-Csv to create the object initially, then just resets the .membership property (it starts as a string, and we split the string so it's now an array).
The second way only makes sense if whatever is creating the "CSV" can create it that way in the first place. If you have to modify it yourself every time, just skip this and process it as it is.

Outputing $_ hashtable variables in a write-warning using a ForEach-Object

so I'm trying to use this load of powershell from here: Getting the current hash key in a ForEach-Object loop in powershell
$myHash.keys | ForEach-Object {
Write-Host $_["Entry 1"]
}
It's all working but I want to output the value as part of another string, i.e.:
$results.notvalid | ForEach-Object {
write-warning 'Incorrect status code returned from $_["url"],
code: $_["statuscode"]'
}
so I want the output to be:
Incorrect status code returned from www.xxxx.com, code: 404
but instead I get
Incorrect status code returned from $_["url"], code: $_["statuscode"]
what am I missing?
BTW, this works if I just do
$results.notvalid | ForEach-Object {
write-warning $_["url"]
}
I then get
www.xxxx.com
I prefer using format strings over embedded expressions (i.e. $()). I find it more readable. Also, PowerShell creates properties on a hashtable for each key, so instead of indexing (i.e. $_['url']) you can $_.url.
$results.notvalid |
ForEach-Object { 'Incorrect status code returned from {0}, code: {1}'
-f $_.url,$_.statuscode } |
Write-Warning
You must put string in double quote instead of single quote if you want variables to be read. Also, in this spot you are not accessing directly a variable value, so you should use $() to be sure code to be evaluated in advance.
$results.notvalid | ForEach-Object {
write-warning "Incorrect status code returned from $($_['url']), code: $($_['statuscode'])"
}