Powershell - 某些命令不能与Invoke-Command一起运行

时间:2012-10-18 15:54:51

标签: powershell

我正在尝试从服务器向大约50个运行Powershell的客户端发送一些命令。大多数命令使用Invoke-Command工作。我使用了与其他命令完全相同的格式,但这个命令不起作用。基本上我想让每个客户端从我的服务器获取一个.xml文件,以便稍后导入它。我错过了我的代码示例中的$凭据和其他变量,但是我的脚本中的其他位置正确设置了它们。

权限明确,winrm中的TrustedHosts设置为*,脚本执行设置为Unrestricted。

        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
        }

我收到以下错误:

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

有什么想法吗?在本地运行时,相同的命令在客户端上完美运行。

1 个答案:

答案 0 :(得分:3)

您在脚本块中使用$webclient,而另一端不会定义$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参数从客户端向远程计算机提供一些变量。然后,那些提供的参数将映射到scriptblock中的param()语句。

相关问题