PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 16, 2022

[FIXED] how to sum integer output function to a value

 August 16, 2022     function, output, powershell     No comments   

Issue

Good evening. I'm totally newbie to powershell and I have surely a silly question but I can't find an answer on my own.

I have a txt file like this

192.168.1.1|2
192.168.1.2|4
192.168.1.3|3

My function takes an IP as a parameter and it returns the integer values after the pipe. The function works but I don't know how to sum a value to the function result.

$client = "192.168.1.2"
function file-update($client) {
$clientrow = gc "C:\clients.txt" | ? {$_ -match $client}
    if ($clientrow) {
            $filesupdated = $clientrow.Split("|")[1]
            return $filesupdated
        }
     else {
            return 0
     } 
}
file-update $client
# it returns 4
file-update $client + 1
# it returns 4 too instead of 5

What'is my mistake? Thanks in advance.


Solution

You need your function to execute and return a value before performing the addition. You can simply use () to group the function call. Since your function returns a [string] when a client is found, you will have to do a conversion to a numeric type to support addition. Having an integer on the left-hand side (LHS) of the operator (+) will convert the RHS value to [int] automatically if possible.

1 + (file-update $client)

You can write the function differently to minimize the amount of work done to extract the integer value:

# Best practice is to use verb-noun for naming functions
# Added file parameter (for file path) to not hard code it inside the function
function Update-File {
    Param(
    $client,
    $file
    )
    # Casting a null value to [int] returns 0
    # Delimiter | to override default ,
    # Named headers are needed since the file lacks them
    [int](Import-Csv $file -Delimiter '|' -Header IP,Number |
        Where IP -eq $client).Number
}

$client = '192.168.1.2'
$file = 'c:\clients.txt'
Update-File $client $file # returns 4
(Update-File $client $file) + 1 # returns 5


Answered By - AdminOfThings
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing