创建数组并将其从一个函数传递给另一个函数

时间:2019-08-16 02:30:02

标签: powershell

我要做的就是创建它,这样我就可以创建数组并在单个函数中对其进行检查,就像在其他函数中调用它一样,因此添加$list = GetUserList会更容易每当我计划调用$list函数时,都要验证GetUserList

https://pastebin.com/6h4MJH9n

有效方法:

function GetUserList {
    $name = Read-Host "Please enter the users name (multiple users can be separated by commas)"
    $names = $name.Split(",")
    for ( $i = 0; $i -lt $names.Count; $i++ ) {
        $firstn = $names[$i].Trim().Split(" ")[0]
        $lastn = $names[$i].Trim().Split(" ")[-1]
        $ulist += @([PSCustomObject]@{
            First = "$firstn";
            Last  = "$lastn"
        })
    }
    return $ulist
}

function UserList {
    do {
        $userlist = GetUserList
        $userlist | Format-Table -AutoSize -Wrap
        $again = Read-Host  "Is this correct? (y/n)"
    } until ( $again -eq "y" )
    $userlist | ForEach-Object {
        "First: $($_.First)"
        "Last: $($_.Last)"
    }
}

UserList

什么不起作用:

function GetUserList {
    do {
        $ulist = @()
        $name = Read-Host "Please enter the users name (multiple users can be separated by commas)"
        $names = $name.Split(",")
        for ( $i = 0; $i -lt $names.Count; $i++ ) {
            $firstn = $names[$i].Trim().Split(" ")[0]
            $lastn = $names[$i].Trim().Split(" ")[-1]
            $ulist += @([PSCustomObject]@{
                First = "$firstn";
                Last  = "$lastn"
            })
        }
        $ulist | Format-Table -AutoSize -Wrap
        $again = Read-Host "Is this correct? (y/n)"
    } until ( $again -eq "y" )
    return $ulist
}

function UserList {
    $userlist = GetUserList
    $userlist | ForEach-Object {
        "First: $($_.First)"
        "Last: $($_.Last)"
    }
}

UserList

我没有收到错误,只是代码无法完全跳过for循环,我也不知道为什么。

1 个答案:

答案 0 :(得分:0)

问题不在$ulist | Format-Table -AutoSize -wrap中,因为您也不是

  • 将格式化后的内容存储在变量中,
  • 不将格式化的内容发送到PowerShell主机进行打印(如OP中@Lee_Daily的评论所述)

PowerShell将格式化的内容返回到输出流。除了格式化的内容外,您还将$ulist的内容发送到输出流(通过Return $ulist语句)。基于$userlist(通过$userlist = GetUserList)包含$ulist内容加上格式化的$ulist内容。

在调试代码时也可以看到这些(请参见Set-PsBreakPoint

[DBG]:> $userlist

First Last
----- ----
user  1
user  2
user  3


First Last
----- ----
user  1
user  2
user  3

正如@Lee_Daily建议的那样,将行$ulist | Format-Table -AutoSize -wrap更改为$ulist | Format-Table -AutoSize -wrap | Out-Host。用管道输送到Out-Host将阻止Format-Table的输出写入输出流。

进一步建议阅读: