PowerShell - 有些命令无法使用Invoke-Command运行

3
我正在试图从服务器向约50个运行Powershell的客户端发送一些指令。大多数指令使用Invoke-Command可以工作。我使用了与其他指令完全相同的格式,但这一个却无法正常工作。基本上,我希望每个客户端从我的服务器获取一个 .xml 文件以后导入它。在这里,我的代码示例中缺少 $credentials 和其他变量,但它们已经在我的脚本的其他地方正确设置了。
在权限方面,winrm中的TrustedHosts已设置为*,并且脚本执行已设置为无限制。
        clear
    $temp = RetrieveStatus

    $results = $temp.up  #Contains pinged hosts that successfully replied.

    $profileName = Read-Host "Enter the profile name(XML file must be present in c:\share\profiles\)"
    $File = "c:\profiles\profile.xml"
    $webclient = New-Object System.Net.WebClient
    $webclient.Proxy = $NULL
    $ftp = "ftp://anonymous:anonymous@192.168.2.200/profiles/$profileName"
    $uri = New-Object System.Uri($ftp)
    $command = {write-host (hostname) $webclient.DownloadFile($uri, $File)}

    foreach($result in $results)
        {           
    # download profile from C:\share\profiles
    Invoke-Command $result.address -ScriptBlock $command -Credential $credentials
    # add profile to wireless networks
    # Invoke-Command $result.address -ScriptBlock {write-host (hostname) (netsh wlan add profile filename="c:\profiles\$args[0].xml")} -argumentlist $profileName -Credential $credentials
        }

I get the following error:

You cannot call a method on a null-valued expression.
+ CategoryInfo          : InvalidOperation: (DownloadFile:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

有什么想法吗?当在客户端本地运行时,相同的命令可以完美地运行。
1个回答

3
您在一个脚本块中使用了$webclient,但是在另一端它不会被定义。为什么不在脚本块中创建Web客户端,例如:

$command = {
    param($profileName)
    $File = "c:\profiles\profile.xml"
    $webclient = New-Object System.Net.WebClient
    $webclient.Proxy = $NULL
    $ftp = "ftp://anonymous:anonymous@192.168.2.200/profiles/$profileName"
    $uri = New-Object System.Uri($ftp)
    Write-Host (hostname)
    $webclient.DownloadFile($uri, $File)}
}

$profileName = Read-Host "Enter the profile name(XML file must be present in c:\share\profiles\)"

Invoke-Command $result.address -ScriptBlock $command -Credential $credentials -Arg $profileName

这将需要您通过-ArgumentList参数在Invoke-Command上向远程机器提供一些客户端变量。然后,这些提供的参数将映射到脚本块中的param()语句。

非常感谢!它完美地运行了。我以为我可以在客户端之外构建工作程序,但似乎不行。 - Frederic Portaria-Janicki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接