Search code examples
functionpowershellinvoke-command

Calling a function within a function with invoke-command Powershell


I am hoping to call a function within a function in invoke-command. It looks like I am not doing this properly. I get "get-group_users" is not recognized error. Everything is in one ps1 script.

Truncated Script:

function get-session {
$session = New-PSSession -ComputerName $ip -Credential $cred -Auth CredSSP
$ComputerName = $cred.Replace('\Admin',"")
$csv = "C:\Scripts\Serverlists\" + $ComputerName + ".txt"
$subcomps = import-csv $csv | foreach-object {$_.Name}

foreach ($ComputerName in $subcomps)
{
$ComputerName
$xmlWriter.WriteStartElement("Computer",$ComputerName)

Invoke-Command -Session $session -ScriptBlock { (get-groups_users -ComputerName $ComputerName) } -ArgumentList $ComputerName

$xmlWriter.WriteEndElement()
}
Remove-PSSession -ComputerName $ip
}



$ip = '172.16.24.11'
$ComputerName = "COMP1"
$user = '\Admin'
$cred = $ComputerName + $user

(get-groups_users -ComputerName $ComputerName)
(get-session -Credential $cred -ComputerName $ip)

So, I'm leaving out the get-groups_users function. I can post it if someone thinks it will help explain everything. It is a long one. Also i am leaving out the $xmlwriter definitions.

get-groups_users works when it runs on COMP1, but once I enter PSSession and try and use it in invoke-command for the sub comps it doesn't recognize it.

What am I forgetting?


Solution

  • You have to include the get-groups_users function definition inside the -ScriptBlock parameter when you call Invoke-Command. If you don't, the remote session has no knowledge of the get-groups_users function.

    Here's how to fix that:

    $ScriptBlock = {
        function get-groups_users {
             ############ Put your function's code here ############
        }
        (get-groups_users -ComputerName $ComputerName)
    };
    Invoke-Command -Session $session -ScriptBlock $ScriptBlock -ArgumentList $ComputerName