Foreach 打印出整个数组 [英] Foreach printing out whole array

查看:46
本文介绍了Foreach 打印出整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好.

我可以就我在这里做错的地方获得一些帮助吗?无论出于何种原因,返回输出正在打印整个数组而不是遍历它.该函数假设允许用户在命令行语法中输入,如果没有提供任何内容,它会选择可供选择的内容.

好的,到目前为止,选择选择以及为函数提供参数是有效的,关于它获取正确的数组.它没有做的是遍历数组.

见下文:

$Group1 = @(第一组",第二组")$Group2 = @(第三组",第四组")$结果 = {新对象 System.Management.Automation.CompletionResult 'Group1', 'Group1', 'ParameterValue', 'this is Group 1'新对象 System.Management.Automation.CompletionResult 'Group2', 'Group2', 'ParameterValue', 'this is Group 2'}Microsoft.PowerShell.Core\Register-ArgumentCompleter -CommandName Test-Group -ParameterName GrpSelec -ScriptBlock $Resultss功能测试组{参数([字符串[]]$GrpSelec)if(!$PSBoundParameters.ContainsKey('GrpSelec')){$AllGroups = @("Group1", "Group2")for($i=0; $i -lt $AllGroups.Count; $i++){写主机$($i): $($AllGroups[$i])"}$GrpSelec = Read-Host -Prompt Select Group(s)";$GrpSelec = $GrpSelec -split ""}$swap = Switch -exact ($GrpSelec){{$_ -eq 0 -or $_ -eq Group1"} {$Group1"}{$_ -eq 1 -or $_ -eq Group2"} {$Group2"}}Foreach($swap 中的 $Group){$组"}}

输出:

PS C:\WINDOWS\system32>测试组 -GrpSelect Group1第一组 第二组PS C:\WINDOWS\system32>测试组0:第 1 组1:第2组选择组:0第一组 第二组

输出应该是什么样子:

第一组第二组

希望这对比我更聪明的人有意义!我还尝试将我的脚本与该脚本的回答方式相关联,但无法使其正常工作:这里

解决方案

继续我的评论.

对您的代码进行小幅更新,以允许在 -GrpSelec 参数上使用 IntelliSense/Tab-Completion 并保留您的参数竞争对手/帮助消息.

$Group1 = @(第一组",第二组")$Group2 = @(第三组",第四组")$结果 = {新对象 System.Management.Automation.CompletionResult 'Group1', 'Group1', 'ParameterValue', 'this is Group 1'新对象 System.Management.Automation.CompletionResult 'Group2', 'Group2', 'ParameterValue', 'this is Group 2'}Microsoft.PowerShell.Core\Register-ArgumentCompleter -CommandName Test-Group -ParameterName GrpSelec -ScriptBlock $Resultss功能测试组{参数([验证集('0','1','组1','组2','0: 组 1','1:组 2')][string[]]$GrpSelec)if(!$PSBoundParameters.ContainsKey('GrpSelec')){$AllGroups = @('Group1', 'Group2')for($i=0; $i -lt $AllGroups.Count; $i++){写主机"$($i): $($AllGroups[$i])"}$GrpSelec = Read-Host -Prompt 'Select Group(s)'$GrpSelec = $GrpSelec -split ' '}$swap = Switch -exact ($GrpSelec){{$PSItem -eq 0 -or $PSItem -eq 'Group1' -or $PSItem -eq '0: Group1'} {$Group1}{$PSItem -eq 1 -or $PSItem -eq 'Group2' -or $PSItem -eq '0: Group2'} {$Group2}}Foreach($swap 中的 $Group){$组}}测试组# 结果<#测试组0:第 1 组1:第2组选择组:选择组:1第三组第四组#>测试组 -GrpSelect 0<#一个空格或制表符为选择列表弹出 IntelliSense.测试组 -GrpSelect 0第一组第二组#>(Get-Command Test-Group).Parameters.Values.Attributes# 结果<#职位 : 0参数集名称:__AllParameterSets必填:错误ValueFromPipeline : FalseValueFromPipelineByPropertyName : FalseValueFromRemainingArguments : False帮助消息:帮助消息库名称:帮助消息资源 ID :不显示:错误TypeId : System.Management.Automation.ParameterAttribute忽略大小写:真有效值:{0, 1, Group1, Group2, 0: Group1, 1: Group2}TypeId : System.Management.Automation.ValidateSetAttributeTransformNullOptionalParameters : TrueTypeId : System.Management.Automation.ArgumentTypeConverterAttribute#>

<块引用>

根据我们关于动态完成者/验证集示例的评论交流进行更新.

function Test-DynamicArgumentCompleter{[CmdletBinding()][别名('tdac')]参数([参数(必填)][参数完成器({Get-ChildItem -Path 'C:\Scripts' -Name |ForEach-Object {if ($PSitem -like '* *'){"'$PSitem'"}否则 {$PSitem}}})][字符串]$文件名)选择的文件名:$FileName"}功能测试动态验证集{[CmdletBinding()][别名('tdvs')]参数 ()动态参数{$ParameterName = '路径'$RuntimeParameterDictionary = 新对象 System.Management.Automation.RuntimeDefinedParameterDictionary$AttributeCollection = 新对象 System.Collections.ObjectModel.Collection[System.Attribute]$ParameterAttribute = 新对象 System.Management.Automation.ParameterAttribute$ParameterAttribute.Mandatory = $true$ParameterAttribute.Position = 1$AttributeCollection.Add($ParameterAttribute)$arrSet = Get-ChildItem -Path '.\' -Directory |选择对象 -ExpandProperty 全名$ValidateSetAttribute = 新对象 System.Management.Automation.ValidateSetAttribute($arrSet)$AttributeCollection.Add($ValidateSetAttribute)$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)返回 $RuntimeParameterDictionary}开始{$Path = $PsBoundParameters[$ParameterName]}过程{dir -Path $Path}}

Good morning.

May I get some assistance on what I may be doing wrong here? For whatever reason, the return output is printing the whole array and not iterating through it. The function is suppose to allow user input at the command line syntax, and if nothing is provided, it makes a choice selection of whats available to select from.

Okay, so far the choice selection along with providing the parameter to the function works, in regards to it grabbing the correct array. What its not doing is iterating through the array.

See below:

$Group1 = @("1st Group", "2nd Group")
$Group2 = @("3rd Group", "4th Group")

$Resultss = {
    New-Object System.Management.Automation.CompletionResult 'Group1', 'Group1', 'ParameterValue', 'this is Group 1'
    New-Object System.Management.Automation.CompletionResult 'Group2', 'Group2', 'ParameterValue', 'this is Group 2'
    }
Microsoft.PowerShell.Core\Register-ArgumentCompleter -CommandName Test-Group -ParameterName GrpSelec -ScriptBlock $Resultss

Function Test-Group{
    param(
        
        [string[]]$GrpSelec)
  if(!$PSBoundParameters.ContainsKey('GrpSelec')){

$AllGroups = @("Group1", "Group2")

for($i=0; $i -lt $AllGroups.Count; $i++){
    Write-Host "$($i): $($AllGroups[$i])"}

$GrpSelec = Read-Host -Prompt "Select Group(s)" 
$GrpSelec = $GrpSelec -split " "}
$swap = Switch -exact ($GrpSelec){            
            {$_ -eq 0 -or $_ -eq "Group1"}  {"$Group1"}
            {$_ -eq 1 -or $_ -eq "Group2"}  {"$Group2"}
            }
Foreach($Group in $swap){
    "$Group"}      
    }

Output:

PS C:\WINDOWS\system32> Test-Group -GrpSelec Group1
1st Group 2nd Group

PS C:\WINDOWS\system32> Test-Group
0: Group1
1: Group2
Select Group(s): 0
1st Group 2nd Group

What the output is suppose to look like:

1st Group
2nd Group

Hopefully this makes sense to someone smarter than me! I also tried to correlate my script to how this script was answered but, couldn't get it to work: Here

解决方案

Continuing from my comments.

Small update to your code to allow for IntelliSense/Tab-Completion on the -GrpSelec parameter and keeping your argument competitor/help message.

$Group1 = @("1st Group", "2nd Group")
$Group2 = @("3rd Group", "4th Group")

$Resultss = {
    New-Object System.Management.Automation.CompletionResult 'Group1', 'Group1', 'ParameterValue', 'this is Group 1'
    New-Object System.Management.Automation.CompletionResult 'Group2', 'Group2', 'ParameterValue', 'this is Group 2'
}

Microsoft.PowerShell.Core\Register-ArgumentCompleter -CommandName Test-Group -ParameterName GrpSelec -ScriptBlock $Resultss

Function Test-Group
{
    param
    (
        [ValidateSet(
                        '0', 
                        '1', 
                        'Group1', 
                        'Group2', 
                        '0: Group1', 
                        '1: Group2' 
                    )]
        [string[]]$GrpSelec
    )

    if(!$PSBoundParameters.ContainsKey('GrpSelec'))
    {

    $AllGroups = @('Group1', 'Group2')

    for($i=0; $i -lt $AllGroups.Count; $i++)
    {Write-Host "$($i): $($AllGroups[$i])"}

    $GrpSelec = Read-Host -Prompt 'Select Group(s)'
    $GrpSelec = $GrpSelec -split ' '
    }

    $swap = Switch -exact ($GrpSelec)
            {            
                {$PSItem -eq 0 -or $PSItem -eq 'Group1' -or $PSItem -eq '0: Group1'}  {$Group1}
                {$PSItem -eq 1 -or $PSItem -eq 'Group2' -or $PSItem -eq '0: Group2'}  {$Group2}
            }

    Foreach($Group in $swap)
    {$Group}
}

Test-Group
# Results
<#
 Test-Group
0: Group1
1: Group2
Select Group(s): 

Select Group(s): 1
3rd Group
4th Group
#>

Test-Group -GrpSelec 0
<#
a space or tab pops IntelliSense for the selection list.

Test-Group -GrpSelec 0
1st Group
2nd Group
#> 

(Get-Command Test-Group).Parameters.Values.Attributes
# Results
<#
Position                        : 0
ParameterSetName                : __AllParameterSets
Mandatory                       : False
ValueFromPipeline               : False
ValueFromPipelineByPropertyName : False
ValueFromRemainingArguments     : False
HelpMessage                     : 
HelpMessageBaseName             : 
HelpMessageResourceId           : 
DontShow                        : False
TypeId                          : System.Management.Automation.ParameterAttribute

IgnoreCase  : True
ValidValues : {0, 1, Group1, Group2, 0: Group1, 1: Group2}
TypeId      : System.Management.Automation.ValidateSetAttribute

TransformNullOptionalParameters : True
TypeId                          : System.Management.Automation.ArgumentTypeConverterAttribute
#>

Update as per our comment exchange regarding the dynamic completer/validateset examples.

function Test-DynamicArgumentCompleter
{
    [CmdletBinding()]
    [Alias('tdac')]
    param
    (
        [Parameter(Mandatory)]
        [ArgumentCompleter(
        {
            Get-ChildItem -Path 'C:\Scripts' -Name |
            ForEach-Object {
                if ($PSitem -like '* *'){"'$PSitem'"}
                else {$PSitem}
            }
        })][string]$FileName
    )

    "Chosen file name: $FileName"
}



function Test-DynamicValidateSet 
{
    [CmdletBinding()]
    [Alias('tdvs')]
    Param ()
 
    DynamicParam {

            $ParameterName = 'Path'
            $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary

            $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
            
            $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
            $ParameterAttribute.Mandatory = $true
            $ParameterAttribute.Position = 1

            $AttributeCollection.Add($ParameterAttribute)

            $arrSet = Get-ChildItem -Path '.\' -Directory | 
            Select-Object -ExpandProperty FullName

            $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)

            $AttributeCollection.Add($ValidateSetAttribute)

            $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
            $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
            return $RuntimeParameterDictionary
    }

    begin 
    {$Path = $PsBoundParameters[$ParameterName]}

    process 
    {dir -Path $Path}
}

这篇关于Foreach 打印出整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆