I am struggling with invoke-Command to execute custom function remotely and display the output at the local host. I’ve read many posts regarding invoke-Command online but I haven’t find a way to resolve this problem.
First the custom function is working. It’s called get-openfiles. The code is provided below:
function get-openfiles{ param( $computername=@($env:computername), $verbose=$false) $collection = @() foreach ($computer in $computername){ $netfile = [ADSI]"WinNT://$computer/LanmanServer" $netfile.Invoke("Resources") | foreach { try{ $collection += New-Object PsObject -Property @{ Id = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) itemPath = $_.GetType().InvokeMember("Path", 'GetProperty', $null, $_, $null) UserName = $_.GetType().InvokeMember("User", 'GetProperty', $null, $_, $null) LockCount = $_.GetType().InvokeMember("LockCount", 'GetProperty', $null, $_, $null) Server = $computer } } catch{ if ($verbose){write-warning $error[0]} } } } Return $collection }
I have used following methods but none of them working. Some of example below will work for built-in function but my condition is that I have to use the custom function.
NOT WORKING #1
$s = New-PSSession -ComputerName remote-STL
$CifServer = “fs-STL-01”
function get-openfiles{…}
invoke-command -Session $s -ScriptBlock ${function:get-openfiles} -ArgumentList $CifServer
NOT WORKING #2
$s = New-PSSession -ComputerName remote-STL
$CifServer = “fs-STL-01”
invoke-command -Session $s -ScriptBlock {Import-Module C:\scripts\grp-functions.psm1}
invoke-command -Session $s -ScriptBlock {get-openfiles -computername $args[0]} -ArgumentList $CifServer
Not working #3
$s = New-PSSession -ComputerName remote-STL
$CifServer = “fs-STL-01”
invoke-command -Session $s -ScriptBlock {Import-Module C:\scripts\grp-functions.psm1}
invoke-command -Session $s -ScriptBlock { param($CifServer) get-openfiles -computername $Cifserver } -ArgumentList $CifServer
Not working #4
$CifServer = “fs-STL-01”
function get-openfiles{…}
invoke-command -ComputerName remote-STL -ScriptBlock ${function:get-openfiles} -ArgumentList $CifServe
not working #5
$CifServer = “fs-STL-01”
invoke-command -ComputerName remote-STL -ScriptBlock {get-openfiles -computername $args[0]}