如何将整数输出函数求和为一个值

how to sum integer output function to a value

晚上好。我完全是 Powershell 的新手,我肯定有一个愚蠢的问题,但我自己找不到答案。

我有一个这样的txt文件

192.168.1.1|2
192.168.1.2|4
192.168.1.3|3

我的函数将 IP 作为参数,它 returns 管道后面的整数值。该函数有效,但我不知道如何将值与函数结果相加。

$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

我的错误是什么? 提前致谢。

在执行加法之前,您需要执行函数并 return 一个值。您可以简单地使用 () 来对函数调用进行分组。由于在找到客户端时您的函数 return 是 [string],因此您必须转换为数字类型以支持加法。在运算符 (+) 的左侧 (LHS) 有一个整数会自动将 RHS 值转换为 [int] if possible.

1 + (file-update $client)

您可以用不同的方式编写函数,以最大限度地减少提取整数值的工作量:

# 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