Get-sentiment Powershell - powershell

How would I go about getting the score decimal returns into just returning the scores as a Percentage?Current powershell line
Get-Sentiment -Text "Im angry", "Hey good morning!" | ForEach-Object documents
Returns
id score
-- -----
1 0.00449720025062561
2 0.98748815059661865
Any Help is appreciated.

You should look at the string tokenization and filtering:
"{0:P2}" -f $SomeVariableContainingANumberToConvertToPercentage
Where '0' is the index for the first token, 'P' is telling PowerShell to format it as a 'percentage' and '2' is telling it to limit the conversion to two places (e.g. 95.22%)
Edit:
Based on your edit with the Return data, you'd want to format the returned object's 'Score' property.
$data = "id,score
1,0.00449720025062561
2,0.98748815059661865
" | ConvertFrom-Csv
$data | Select-Object id,#{n='ScoreFormatted'; e={ ("{0:P2}" -f [float]$_.Score) }}
Outputs:
id ScoreFormatted
-- --------------
1 0.45%
2 98.75%

Related

PowerShell script to sort an array ascending order and return last value

I am having below PowerShell script which does not result in the sorting order I want.
$string = #("Project-a1-1", "Project-a1-10", "Project-a1-2", "Project-a1-5", "Project-a1-6", "Project-a1-8")
$myobjecttosort=#()
$string | ForEach{
$myobjecttosort+=New-Object PSObject -Property #{
'String'=$_
'Numeric'=[int]([regex]::Match($_,'\d+')).Value
}
}
$myobjecttosort | Sort-Object Numeric | Select Numeric,String | Format-Table -AutoSize
The output of the above script:
Numeric String
1 Project-a1-5
1 Project-a1-6
1 Project-a1-8
1 Project-a1-1
1 Project-a1-10
1 Project-a1-2
Required Output
1 Project-a1-1
2 Project-a1-2
3 Project-a1-5
4 Project-a1-6
5 Project-a1-8
6 Project-a1-10
Also, I want always output to be returned as the last value so here output would be Project-a1-10
Sort-Object accepts a script block allowing for a more robust sort. With that said, just like any other object in the pipeline, the objects are accessible via $PSItem, or $_. So, a quick way to go about this is splitting the string at the - selecting just the ending numerical digits, then casting [int] to the result to sort by.
$string = "Project-a1-1", "Project-a1-10", "Project-a1-2", "Project-a1-5", "Project-a1-6", "Project-a1-8"
$string |
Sort-Object -Property { [int]($_ -replace '^.*?(?=\d+$)') } |
% { $i = 1 } {
'{0} {1}' -f $i++, $_
}
The above yields:
1 Project-a1-1
2 Project-a1-2
3 Project-a1-5
4 Project-a1-6
5 Project-a1-8
6 Project-a1-10
Passing the sorted items to % (alias to Foreach-Object), we can then format a new string giving it an index # to each string starting at 1.

PowerShell - How do you do math on two columns in a Select-Object Expression?

I'm trying to come up with a percent column by dividing two columns in a select-object. This is what I'm using:
Get-DbaDbLogSpace -SqlInstance serverName |
Select-Object ComputerName, InstanceName, SqlInstance, Database, LogSize,
LogSpaceUsed, LogSpaceUsedPercent,
#{Name="PercentFree"; Expression={($_.LogSpaceUsed / $_.LogSize)}} |
Format-Table
This returns an 'OB' on the expression column (see pic below). How do I do math with two columns in a Select-Object expression please?
If doing this a different way outside of a Select-Object would be better, I'm open to it.
This is what the data looks like for the above code:
Thanks for the help.
The operands of your calculation appear to be strings with byte multipliers (e.g. 38.99 MB), so you'll have to transform them to numbers in order to perform division on them.
Here's a simplified example:
Note: I'm using Invoke-Expression to transform the strings to numbers, relying on PowerShell's support for byte-multiplier suffixes such as mb in number literals (e.g., 1mb - note that there must be no space before the suffix). While Invoke-Expression (iex) should generally be avoided, it is safe to use if you trust that the relevant property values only ever contain strings such as '38.99 MB'.
[pscustomobject] #{
Database = 'db1'
LogSize = '11 MB'
LogSpaceUsed = '3 MB'
} |
Format-Table Database, LogSize, LogSpaceUsed,
#{
Name = "PercentFree"
Expression = {
'{0:P2}' -f ((Invoke-Expression ($_.LogSpaceUsed -replace ' ')) /
(Invoke-Expression ($_.LogSize -replace ' ')))
}
}
Note that I'm passing the properties, including the calculated one directly to Format-Table - no need for an intermediary Select-Object call. Note that the calculated property outputs the percentage as a formatted string, using the -f operator, so that the number of decimal places can be controlled.
Output:
Database LogSize LogSpaceUsed PercentFree
-------- ------- ------------ -----------
db1 11 MB 3 MB 27.27%
Thanks to #mklement0, this is what works.
Get-DbaDbLogSpace -SQLInstance servername | Format-Table Database, LogSize, LogSpaceUsed,
#{
Name = "PercentFree"
Expression = {
'{0:P2}' -f ((Invoke-Expression ($_.LogSpaceUsed -replace ' ')) /
(Invoke-Expression ($_.LogSize -replace ' ')))
}
}

Concatenate string with object in Powershell

Currently I want to get a list of active user on Windows 10 using Powershell.
After some searching I found this helps:
Get-LocalUser | Where-Object -Property Enabled -eq True
And here is the output:
Name Enabled Description
---- ------- -----------
User_1 True
User_2 True
I just want to concatenate strings to a list of values of Name column from above, which will be like below:
Active user(s): User_1, User_2
Do you have any idea how I can do that? I'm just a non-tech guy trying to learn some useful command so forgive me if this is a basic to you.
You can do the following:
# Retrieve the name values
$Users = Get-LocalUser |
Where-Object Enabled -eq True | Select-Object -Expand Name
# Create the output string
"Active user(s): {0}" -f ($Users -join ', ')
Using -Expand (or -ExpandProperty) from Select-Object, the target property's value is returned rather than the object that contains the property.
-f is the string format operator. It uses substitution for the {position} syntax. The -join operator creates a string from a list with , as the delimiter.

Powershell Get Hashtable Values

I've got this Hashtable with this values:
Name Value
---- -----
Bayas_palm_stem_A0311.jpg 1
Bayas_palm_stem_A0312.jpg 2
Bukit_Bangkong_area.tiff 1
BY_and_siblings_A0259.jpg 5
Cassava_camp_A0275.jpg 1
Children_A0115.jpg 6
cip_barau_kubak.jpg 1
How can i get only the Name and Value where Value is greater than 1 ?
I'm tryng with this code, but i'm doing something wrong!!!
$RT | Group-Object Name , Value | Where-Object {$RT.Values -gt 1}
Thanks a lot for any help.
Use $hashtable.GetEnumerator() to enumerate the individual name-value pairs in the hashtable:
$RT.GetEnumerator() |Where-Object {$_.Value -gt 1}
Beware that if you assign the resulting pairs to a variable, it's not longer a hashtable - it's just an array of individual name-value pairs.
To create a new hashtable with only the name-value pairs that filter through, do:
$RTFiltered = #{}
$RT.GetEnumerator() |Where-Object {$_.Value -gt 1} |ForEach-Object {$RTFiltered.Add($_.Name, $_.Value)}
Like this:
$RT.getenumerator() | Where-Object {$_.Value -gt 1}
Assuming you have a Hashtable defined like this.
$rt = #{
"Bayas_palm_stem_A0311.jpg " = 1
"Bayas_palm_stem_A0312.jpg " = 2
"Bukit_Bangkong_area.tiff " = 1
"BY_and_siblings_A0259.jpg " = 5
"Cassava_camp_A0275.jpg " = 1
"Children_A0115.jpg " = 6
"cip_barau_kubak.jpg " = 1
}
You can call GetEnumerator() which allows you to iterate through the Hashtable.
Once you've got an enumeration of the members, then your normal PowerShell value comparisons will work.
You can get values greater than 1 like this:
$rt.GetEnumerator() | ? Value -gt 1
Name Value
---- -----
BY_and_siblings_A0259.jpg 5
Children_A0115.jpg 6
Bayas_palm_stem_A0312.jpg 2

PS: Filter selected rows with only max values as output?

I have a variable results ($result) of several rows of data or object like this:
PS> $result | ft -auto;
name value
---- -----
a 1
a 2
b 30
b 20
....
what I need to get all the rows of name and max(value) like this filtered output:
PS> $result | ? |ft -auto
name value
---- -----
a 2
b 30
....
Not sure what command or filters available (as ? in above) so that I can get each name and only the max value for the name out?
$result | group name | select name,#{n='value';e={ ($_.group | measure value -max).maximum}}
This should do the trick:
PS> $result | Foreach {$ht=#{}} `
{if ($_.Value -gt $ht[$_.name].Value) {$ht[$_.Name]=$_}} `
{$ht.Values}
This is essentially using the Begin/Process/End scriptblock parameters of the Foreach-Object cmdlet to stash input objects with a max value based on a key into a hashtable.
Note: watch out for extra spaces after the line continuation character (`) - there shouldn't be any.