2

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

So do I have to put the get-groups_users function inside while it will have to remain outside as well? (for running separately from the session function)
You'll have to leave it outside as well, otherwise the local session won't know about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.