【发布时间】:2016-09-10 02:26:06
【问题描述】:
我正在努力使用 invoke-Command 远程执行自定义功能并在本地主机上显示输出。我在网上阅读了很多关于 invoke-Command 的帖子,但我还没有找到解决这个问题的方法。
首先自定义功能正在工作。它被称为get-openfiles。代码如下:
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
}
我使用了以下方法,但没有一个有效。下面的一些示例适用于内置函数,但我的条件是我必须使用自定义函数。
# 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]} -ArgumentList $CifServer
感谢您的调查!
【问题讨论】:
-
带有 ${function:get-openfiles} 的两个(可能)正在发送函数定义,但是在这样做之后您不会调用该函数。我认为您需要将其与为 cifserver 获取参数然后调用 get-openfiles 的脚本块结合起来
-
如果您从第一个示例中删除
-Session $s(并首先创建会话),并将其换成-ComputerName 'fs-STL-01',它很可能会起作用。这种语法对我有用。 -
嗨,罗宾。为了清楚起见,你能给我完整的语法吗?我不明白你是如何进行交换并为你工作的。
-
嗨,TessellatingHeckler,我想看看你的脚本如何让它工作。谢谢,莱昂
标签: powershell powershell-remoting invoke-command