【问题标题】:how to sum integer output function to a value如何将整数输出函数求和到一个值
【发布时间】:2021-04-14 20:34:42
【问题描述】:

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

我有一个这样的txt文件

192.168.1.1|2
192.168.1.2|4
192.168.1.3|3

我的函数将 IP 作为参数,并在管道之后返回整数值。该函数有效,但我不知道如何将值与函数结果相加。

$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

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

【问题讨论】:

  • 文件中的客户端 IP 是否总是唯一的,即可以有重复吗?
  • 客户端IP是唯一的,是的
  • 你可以简单地做(file-update $client) + 1
  • 非常感谢。它返回给我 41 但如果我输入函数 return [int]$filesupdated 它可以工作。感谢这个美好的社区
  • ( ) 中的所有内容都将首先在 powershell 中进行处理,记住这一点。

标签: function powershell output


【解决方案1】:

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

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

【讨论】:

  • 再次感谢您的详细回答和您为我付出的时间。我开始研究你的解决方案,P.S.看来我不能投票,因为我是新用户。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 2020-09-26
  • 1970-01-01
相关资源
最近更新 更多