我要做的就是创建它,这样我就可以创建数组并在单个函数中对其进行检查,就像在其他函数中调用它一样,因此添加$list = GetUserList
会更容易每当我计划调用$list
函数时,都要验证GetUserList
。
有效方法:
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循环,我也不知道为什么。
答案 0 :(得分:0)
问题不在$ulist | Format-Table -AutoSize -wrap
中,因为您也不是
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
的输出写入输出流。
进一步建议阅读: