thank you for your help in advance. I am clearly new to powershell. i am barely/poorly able to cobble together batch files and stuck in the 1980’s way of doing things.
I need to find a value out of data from an internal website rest called “something” within a whole series of text lines that will be a number, although i need that number to be 0 before a server shuts down
i can currently achieve this with the script below, however i do it in a number of messy hops, outputing values in temp*.txt files, performing remove all text lines but the text line containing “something” and then stripping all the letters, only keeping numbers - looking for a value of 0
is there any way to instead of outputting all this data into temp text files, i could use variables? or is there a neater way to perform this…?
$command = Invoke-RestMethod http://localhost:80/data -Method Get > temp1.txt
$output = get-content temp1.txt
foreach ($line in $output) {
if ($line -like “something”) {
$line | out-file -FilePath “temp2.txt”
$pattern = ‘[^0-9]’
$outcome = $line -replace($pattern,‘’)
If ($outcome -gt 0) {“It is not 0, do not shutdown.”} else {“It is 0, you can shutdown.”} # replace with {“shutdown /m \localhost /f /s”}
}
}
del temp1.txt, temp2.txt
What Invoke-RestMethod will get you back is typically a custom object with rich properties and values available. Instead, just get the output from the Invoke-RestMethod command:
$command = Invoke-RestMethod http://localhost:80/data -Method Get
Then, check what you have to work with:
$Command | Get-Member
I’d be willing to be you could trim this down to something pretty easy, along the lines of:
$Command.PropertyName -match 'something'
And that would tell you exactly what you need to know.
I have gotten further cleaning things by way of your direction, much appreciated. currently it looks like this, without the need for temp files etc - so i am much happier:
Not bad! Worth noting that everything you can see from Get-Member is available in a much simpler fashion as well!
Once you have the property name, all you need do is ask the object for it:
$Something = $Command.Something -replace '[^\d]'
Basically, every property and method you see with Get-Member can be accessed using the dot-property accessor and specifying the property or method name.