Using a Foreach loop with a single-object array

Tagged: 

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Brett Osiewicz Brett Osiewicz 7 months, 4 weeks ago.

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #34598
    Profile photo of Brett Osiewicz
    Brett Osiewicz
    Participant

    I use this function to input a string, search through every script module in my $pshome, and then offer up one or more finds for addition as an ISE script tab. Each function I write is a separate file with a name matching the function.

    However, it fails if only one matching file is found. Works fine if I select two or more files.

    If someone could just tell me what I am doing wrong.

    #requires -Version 2
    function Get-FunctionFileName 
    {
         Get-FunctionFileName -Name Get-NIC 
                .EXAMPLE
                PS C:\ref> Get-FunctionFileName -Name .\Get-NIC.ps1
    
                This works ok as well. The function removes '.\' and '.ps1' 
        
        #>
      
        [CmdletBinding()]
        param(
      
            [Parameter(ValueFromPipeline = $true,
                    ValueFromPipelineByPropertyName = $true)]
            [String]
        $Name = 'TBAppointment'
        #     $Name = 'functionfilename'
        #     $Name = 'Get-Diskspace'
        
        )
        
        $Start = $PWD
        $ArrayofPaths = @( $env:PSModulePath -split ';')
        $Collection = @()
        
        if ( $fn )  {Remove-Variable -Name fn -Scope Global -ea Continue}
        $fn =@()
    
        $Name = $Name -replace '\.\\', ''
        $Name = $Name -replace '\.ps1', ''
      
        foreach ($dir in $ArrayofPaths) 
        {
            Write-Verbose -Message $dir 
            $Collection += Get-ChildItem -Path $dir -Include "*$Name*" -Recurse | Where-Object -FilterScript {$_.PSIsContainer -eq $false}
        } #end foreach
        
        if (-not( $Collection)) 
        {
            Write-Warning -Message 'No Results were found!'
            break
        }
    
        [array]$Results = $Collection | Select-Object -Property BaseName, LastWriteTime, Length, Fullname, 
        @{ Name = 'Module'; Expression = {Split-Path -Path $_.Directory -Leaf}    }
    
        
        $Results | Format-Table -AutoSize -Property @{Name = 'Index';Expression = {[array]::IndexOf($Results, $_)}}, BaseName, LastWriteTime, Length, Fullname
      
        [array]$Choice = Read-Host -Prompt 'Please Choose by Index Number(s)' 
    
        $Choice = $Choice -split {$_ -eq ' ' -or $_ -eq ','} |
        Where-Object   -FilterScript {$_} |
        ForEach-Object -Process {$_.trim()} 
    
        Foreach ($Ch in $Choice) 
        {
            $fn = $fn+ $Results[$Ch].fullname
        }
    
        if ( -Not($fn)) {Write-Warning '$FN was not set'}
      
        foreach ($file in $fn ) {$file ; psEdit -filenames $file }
    }
    
    #34605
    Profile photo of Max Kozlov
    Max Kozlov
    Participant

    You forget to say in which line you get an error, what error and what version of PS you are using.
    line
    $Choice = $Choice -split {$_ -eq ' ' -or $_ -eq ','} | looks very strange. You should read more about -split
    tip1: $choice -split '[ ,]'
    tip2: try to output significant variable values just before line with error

    #34687
    Profile photo of Brett Osiewicz
    Brett Osiewicz
    Participant

    Well, there really is no error. It just fails to use the elements in the $Choice array

    Foreach ($Ch in $Choice)

    If $Choice has only one element (and I definitely define an array ) this foreach loop fails to build $fn. I had once defined it as $fn += $Results[$Ch].fullname. However, the different methods don't appear to matter.

    I see your point about the split, but I don't know why that would affect the above foreach loop. In the final line, I do output each element of $fn as '$file' in the last code line. The string is displayed in the host before it is opened in the script editor.

    #34699
    Profile photo of Max Kozlov
    Max Kozlov
    Participant

    sorry, I can't reproduce your problem.
    I try your code, find many files and choose one from them, find only one file and choose one successfully, find many and choose many...
    only the change I make – comment out #PSEdit
    but I get all chosen names with
    foreach ($file in $fn ) {$file}

    I use PSv5

    #34707
    Profile photo of Brett Osiewicz
    Brett Osiewicz
    Participant

    Max,

    Thanks for the effort. I forgot to mention that I was using this with v5 at home and v2 in the office. If i was above v3 everywhere, i would send everything to outgridview.

    Such as,

    $FN = $choices | out-gridview -passthrough | select -expandproperty Fullname

    and then send the contents $FN to a script tab(s) via psedit.

    I have run this without my profile and still get the same problem.

    Maybe, I will experiment with $psISE.CurrentPowerShellTab until I discover the true problem.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.