在远程命令中使用局部变量的问题 [英] Problems using local variables in a remote commands

查看:74
本文介绍了在远程命令中使用局部变量的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个包含变量并在远程系统上共享的脚本.

这有效:

Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create("C:\test","test",0)}

但这不是:

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create($sharepath,$sharename,0)}

我需要一种以某种方式传递这些值的方法.

解决方案

远程会话无法读取您的局部变量,因此您需要使用命令发送它们.这里有一些选择.在PowerShell 2.0中,您可以:

1.将它们与-ArgumentList一起传递并使用$arg[i]

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create($args[0],$args[1],0)} -ArgumentList $sharepath, $sharename

2.将它们与-ArgumentList一起传递,并在脚本块中使用param()定义参数

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock { param($sharepath, $sharename) $a = [WMICLASS]"Win32_Share"; $a.Create($sharepath,$sharename,0)} -ArgumentList $sharepath, $sharename

在PowerShell 3.0中,引入了using -variable范围以使其更容易:

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock { $a = [WMICLASS]"Win32_Share"; $a.Create($using:sharepath,$using:sharename,0)}

您可以在 about_Remote_Variables @ TechNet 上了解有关此内容的更多信息

I need to write a script that takes in variables and makes a share on a remote system.

This works:

Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create("C:\test","test",0)}

But this doesn't:

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create($sharepath,$sharename,0)}

I need a way to pass those values somehow.

解决方案

The remote session can't read your local variables, so you need to send them with your command. There's a few options here. In PowerShell 2.0 you could:

1.Pass them along with -ArgumentList and use $arg[i]

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create($args[0],$args[1],0)} -ArgumentList $sharepath, $sharename

2.Pass them along with -ArgumentList and use param() in your scriptblock to define the arguments

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock { param($sharepath, $sharename) $a = [WMICLASS]"Win32_Share"; $a.Create($sharepath,$sharename,0)} -ArgumentList $sharepath, $sharename

In PowerShell 3.0, the using-variable scope was introduced to make it easier:

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock { $a = [WMICLASS]"Win32_Share"; $a.Create($using:sharepath,$using:sharename,0)}

You could read more about this on about_Remote_Variables @ TechNet

这篇关于在远程命令中使用局部变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆