.net - PowerShell/获取枚举器

标签 .net powershell

我有一个简单的问题:

为什么下面的程序没有写入整个数组$lines?它永远循环。我真的很困惑..

function Get-Current ($enumerator) {
    $line = $enumerator.Current
    return $line
}

$lines = @('a', 'b', 'c')
$enumerator = $lines.GetEnumerator()
$enumerator.Reset()

while ($enumerator.MoveNext()) {
    $line = Get-Current $enumerator
    "$line"     
}

最佳答案

看起来好像是这样的表达式:

$enumerator

展开整个枚举器。例如:

PS C:\> $lines = @('a', 'b', 'c')
PS C:\> $enumerator = $lines.GetEnumerator()
PS C:\> $enumerator.Reset()
PS C:\> $enumerator
a
b
c

因此,当您尝试将表达式传递给函数时,它会变得无效。我能想到的唯一解决方法是将其作为 PSObject 传递,如下所示:

function Get-Current ($val) {
    $val.Value.Current
}

$lines = @('a', 'b', 'c')
$enumerator = $lines.GetEnumerator()
$enumerator.Reset()

while ($enumerator.MoveNext()) {
    $line = Get-Current $(get-variable -name enumerator)
    $line
}

关于.net - PowerShell/获取枚举器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2972615/

相关文章:

windows - 从 Powershell 调用 .exe 时如何防止出现 "Program has stopped working"对话框

azure - 在 powershell 或 azcli 中操作 az cli 命令的输出返回

c# - 线程中的 System.OutOfMemoryException

c# - PInvoke - 找不到指定的模块。如何检查缺少的依赖项?

c# - 我如何检测 List<string> 是否已更改?最后添加的项目是什么?

powershell - 使用-notlike在PowerShell中过滤出多个字符串

powershell - 使用 Powershell 的用户登录/注销信息

powershell - WinRM 访问被拒绝(Visual Studio Team Services 的生成定义中的 Azure 文件复制任务)

c# - 如何检测用户密码是否过期

c# - 通用方法存储在哪里?