Home > Enterprise >  ForEach-Object -Parallel can't see defined cmdlet
ForEach-Object -Parallel can't see defined cmdlet

Time:11-29

I'm strugling with powershell (first time working in this evn). And found that when I'm trying to user ForEach with Parallel option, loop can't see cmdlet defined few lines later. Can you please point to me any documentation that will help me solve this problem? Below my test script and output

1..10 | ForEach-Object -Parallel {
    hi $_
    sleep 2
}

function hi {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true)]
        [String]$name
    )

    Begin {
        function sayHi {
            param (
                [Parameter(Position=0)]
                $name
            )

            Write-Host ">>>>"
            Write-Host "Say hi $($name)"
            Write-Host ">>>>"
        }
    }

    Process {
        hi $name
    }
    End{}
}

Output:

Desktop> .\test_paralell.ps1
hi: 
Line |
   2 |      hi $_
     |      ~~
     | The term 'hi' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
hi: 
Line |
   2 |      hi $_
     |      ~~
     | The term 'hi' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
hi: 

CodePudding user response:

When you use -parallel, what is happening under the hood is that Powershell is creating another 'namespace', which means that the function you defined is not available inside this scope. You're not the first one with this question -> please have a look for example here: How to pass a custom function inside a ForEach-Object -Parallel

  • Related