Home > Enterprise >  Formatting in PowerShell
Formatting in PowerShell

Time:10-01

I am getting the content of a JSON file into the variable $variable and filtering the $variable on a condition as in the code below and holding the filtered data in $logs. The output of echo $logs is as below.

0.842093077,
0.792955,
0.8910225,
0.8724875,
0.852885333,
0.774708,
0.987243333,
0.87078,
0.9565,
0.839393333

My question is how do i convert each of these decimal values to a percentage like 84.20 %, 79.20% and so on, so that when the mail goes out with the Percentage Utilisation field as a percentage value and not a decimal value?

DESIRED SAMPLE OUTPUT

Workspace Name         : A NAME
Workspace Allowance    : 100
Workspace Usage        : 79.2955
Workspace Size Free    : 20.7
**Percentage Utilization : 79.29**
Predicted Usage        : 86.05585477

PRESENT OUTPUT

Workspace Name         : A NAME
Workspace Allowance    : 100
Workspace Usage        : 79.2955
Workspace Size Free    : 20.7
*Percentage Utilization : 0.792955*
Predicted Usage        : 86.05585477
# Convert the CSV file into its JSON equivalent
    import-csv "Workspacesize.csv" | ConvertTo-Json | Add-Content -Path "output.json" -Force -ErrorAction Stop
    
    
    # Import email settings from config file
    
    [xml]$ConfigFile = Get-Content "Settings.xml"
    #Write-Output $ConfigFile
    
    $emailTo = @([email protected], [email protected])
    # Create email content
    $smtpsettings = @{
    
        From = $ConfigFile.Settings.EmailSettings.MailFrom
        Subject = "TEST EMAIL"
        SmtpServer = $ConfigFile.Settings.EmailSettings.SMTPServer
        }
    
   
    
    [String]$messagebody = ""
    $variable=Get-Content -raw "output.json" | ConvertFrom-Json
    $logs=$variable | Where-Object { [double]$_.'Percentage Utilization' -gt 0.75}
    echo $logs
    
    
    } 
    foreach ($log in $logs )
    {
        $messagebody = $messagebody   $log   "`r`n"
    }
    
    $messagebody  = $logs | Out-String
    $messagebody = '<pre>'   $messagebody   '</pre>'
     
    
    #-------------------------------------------------
    #  Script
    #-------------------------------------------------
    
    try
    {
     Send-MailMessage @smtpsettings -To $emailTo  -Body $messagebody -BodyAsHtml -Encoding utf8 -verbose -ErrorAction Stop
     }
    
    catch
    {
        Write-Warning $_.Exception.Message
    }
    
    # MOVE THE JSON & CSV FILE TO AN ARCHIVED LOCATION
    
    Move-Item -Path $Jsonfile -Destination C:\Users\Siddhartha.S.Das2\Desktop -Force
    Move-Item -Path $Csvfile -Destination C:\Users\Siddhartha.S.Das2\Desktop -Force
    
    #-------------------------------------------------
    #  The End
    #-------------------------------------------------

CodePudding user response:

As commented, you can simplify the code by using the data from the CSV file and only if you really also need that in JSON format, convert that data and save it at the end of the script.

$CsvFile = 'C:\Somewhere\Workspacesize.csv'

$data = Import-Csv -Path $CsvFile
$logs = $data | Where-Object { [double]$_.'Percentage Utilization' -gt 0.75 }
# update the 'Percentage Utilization' property on each item
foreach ($item in $logs) {
    $item.'Percentage Utilization' = [Math]::Round(([double]$item.'Percentage Utilization' * 100), 2)
}
# format the mesage body as monospaced formatted list output
$messagebody = '<pre>{0}</pre>' -f ($logs | Format-List | Out-String)

# Import email settings from config file
[xml]$ConfigFile = Get-Content "Settings.xml"

# BTW. it is better to use:
# $ConfigFile = ([System.XML.XMLDocument]::new()).Load('X:\Path\To\Settings.xml')
# because that way you'll get the encoding right. 
# You need to load it using the absolute Full path and filename

# Create email splat hashtable
$smtpsettings = @{
    To         = '[email protected]', '[email protected]'
    From       = $ConfigFile.Settings.EmailSettings.MailFrom
    Subject    = "TEST EMAIL"
    SmtpServer = $ConfigFile.Settings.EmailSettings.SMTPServer
}
# try to send the email
try {
    Send-MailMessage @smtpsettings -Body $messagebody -BodyAsHtml -Encoding utf8 -Verbose -ErrorAction Stop
}
catch {
    Write-Warning $_.Exception.Message
}

# move the csv file to an archived location
Move-Item -Path $Csvfile -Destination 'C:\Users\Siddhartha.S.Das2\Desktop' -Force

# if you really also need a json file from the data retrieved from the Csv, convert and save it here:
$data | ConvertTo-Json | Set-Content -Path 'C:\Users\Siddhartha.S.Das2\Desktop\output.json'

CodePudding user response:

Quick example with format specifier p for percentage, see https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings:

echo 0.842093077,
0.792955,
0.8910225,
0.8724875,
0.852885333,
0.774708,
0.987243333,
0.87078,
0.9565,
0.839393333 | % tostring p

84.21%
79.30%
89.10%
87.25%
85.29%
77.47%
98.72%
87.08%
95.65%
83.94%
  • Related