G
G
genbachae2020-05-12 03:23:34
PowerShell
genbachae, 2020-05-12 03:23:34

Why doesn't Power Shell see the feature?

I run the code:

[xml]$inputs = New-Object system.Xml.XmlDocument
$inputs.Load('.\inputs.xml') 

$matrix = New-Object System.Collections.ArrayList

$hostname = 'ya.ru'

$r = Start-Job {getMyPing $hostname}
[int]$id = $r.Id
$matrix.Add(($id))
$matrix

Start-Sleep -Sec 12

Get-Job
Receive-Job $id


function global:getMyPing($hostname) {
    [string]$resPing = ''
    if (Test-Connection $hostname -Quiet)
  {
    $resPing += "Ping to " + $hostname + " success`r`n"      #   формируем содержимое файла report.txt
    $port = $server.port
    $sock = new-object System.Net.Sockets.Socket -ArgumentList $([System.Net.Sockets.AddressFamily]::InterNetwork),$([System.Net.Sockets.SocketType]::Stream),$([System.Net.Sockets.ProtocolType]::Tcp)
      try {
        $sock.Connect($hostname,$Port) | Out-Null        #   попытка соединения
        $resPing += "port " + $port + " connect success`r`n"
        $resPing += "`r`n"
        $sock.Close()
        }
      catch {
      $resPing += "port " + $port + " connect fail`r`n"
      $resPing += "`r`n"
      } 
  }
  else
  {
    $resPing += "Ping to " + $hostname + " fail`r`n"         #   формируем содержимое файла report.txt
  }
    $events = $resPing
    return $events
}

on line:

Receive-Job $id

an error pops up:

The name "getMyPing" is not recognized as the name of a cmdlet, function, script file, or executable program. Check the spelling of the name and the presence and correctness of the path, then try again.

Question: what, in the code, am I doing wrong?
5eb9ec82be550642150927.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MaxKozlov, 2020-05-12
@genbachae

All for the same reason - Job is a separate process, it does not know about your functions.
There are three options:
1. the function should be placed right inside your script block
2. the function should be placed in a module
3. use an alternative - PoshRSJob , which you can specify which functions to import

A
azarij, 2020-05-12
@azarij

This is how I got it to work:

$hostname = "ya.ru"

$funcs = {function myfunction($hostname){
    Test-NetConnection $hostname
    }
}

Start-Job -InitializationScript $funcs -ScriptBlock {myfunction $using:hostname}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question