1

I've got the following:

$WebContent = Invoke-WebRequest -Uri "URLHERE/$PCNAME" -UseDefaultCredential |
              Select-Object -ExpandProperty Content

And it outputs perfectly:

Key1: sfsdfsdfsfdsfsdsfs
Key2: SD:34:SD:34:SD:34
Version: 4
Timestamp: 4/13/2018 4:00:11 PM

But I need to be able to put the content of Key1 and Key2 into a variable, without the space, and accommodating the possibility of varying lengths of each key.

I was trying to use Substring($len - 83,14) to get the length of it all and parse out the exact spot of the Key, but for some reason they are changing in length and a few have cut off the key which gives a incorrect output. I probably need to get the whole line and then put into a variable everything after the ':' and ' '.

Any ideas?

4
  • Can't you do $WebContent.Key1? Commented Jul 19, 2018 at 16:39
  • @TheIncorrigible1 The data appears to be the response from a web request, so it's most likely a string array, not a PowerShell object. Commented Jul 19, 2018 at 16:44
  • 1
    @AnsgarWiechers Sometimes the iwr cmdlet is nice and parses things into objects for you, but it's impossible to know with certainty without more detail. Commented Jul 19, 2018 at 16:44
  • @TheIncorrigible1 does it? I've only known irm to do that. Commented Jul 19, 2018 at 17:00

2 Answers 2

3

Assuming that the response you got is text, not a structured object, you could do something like this:

$data = $WebContent -replace ': ', '=' |
        Out-String |
        ConvertFrom-StringData

The above will replace colons followed by a space with a = character and merge all into a single string, so that ConvertFrom-StringData can convert the list of key/value pairs to a hashtable. Then you can assign values to individual variables like this:

$key = $data['Key1']

or just use the hashtable as-is.

Sign up to request clarification or add additional context in comments.

Comments

1

Split the content into lines, match the ones you want and ignore the rest, replace the part you don't want, store the result:

$test = @'
Key1: sfsdfsdfsfdsfsdsfs
Key2: SD:34:SD:34:SD:34
Version: 4
Timestamp: 4/13/2018 4:00:11 PM
'@


$result = ($test -split "`r?`n") -match '^key.: ' -replace '^key.: '

Depending on what you mean by "get the two keys into one variable"; this result will be an array of string.

One of many, many possible approaches.

1 Comment

$key1, $key2 = ...?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.