[英]Issue with variables within the scriptblock of Invoke-Command
I seem to have a issue with getting variables in the Invoke-Command
. 我似乎遇到了在
Invoke-Command
获取变量的问题。 I can't get a variable in whatever I do. 无论我做什么,我都无法获得变量。 When I want to use:
当我想使用时:
Invoke-Command -ComputerName $servername { new-item -Path "$RootPathDestination" -Name $version -Itemtype directory }
I get the error: 我收到错误:
Cannot bind argument to parameter 'Path' because it is an empty string.
And I have declared them in this script: 我在这个脚本中声明了它们:
$version = 36
$RootPathDestination = "c:\scripts\"
Does anyone have any ideas? 有没有人有任何想法? I am really out of options here :-(
我真的没有选择:-(
$svr = "SQLSERVER"
$db = "0000 - INFRA"
$version = 36
$RootPathDestination = "c:\scripts\"
# connection
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=$svr;Database=$db;Integrated Security=True"
$sqlConnection.Open()
$cmd = $sqlConnection.CreateCommand()
$cmd.CommandText ="SELECT * from infrastructure"
$Serverinfo = $cmd.ExecuteReader()
try
{
while ($Serverinfo.Read())
{
$servername = $Serverinfo.GetValue(1)
Invoke-Command -ComputerName $servername { new-item -Path "$RootPathDestination" -Name $version -Itemtype directory }
#Invoke-Command -ComputerName $servername { Copy-Item c:\scripts\* c:\test }
#Invoke-Command -ComputerName $servername {Import-Module WebAdministration ; New-WebApplication -force -Site "Default Web Site" -Name 3.78 -PhysicalPath "c:\inetpub\"$version }
}
}
catch
{
echo "Hmm strange"
}
finally
{
echo "All good!"
echo $Version
$sqlConnection.Close()
}
你必须使用using前缀:
Invoke-Command -ComputerName $servername { new-item -Path "$using:RootPathDestination" -Name $using:version -Itemtype directory }
You are passing a scriptblock to Invoke-Command
. 您正在将脚本块传递给
Invoke-Command
。 In order to use the values of any variables defined outside that scriptblock within the scriptblock, you need to refer to them as $using:variablename
(in your example, $using:RootPathDestination
. See Get-Help about_Remote_Variables
. 为了使用scriptblock 中该scriptblock 之外定义的任何变量的值,您需要将它们称为
$using:variablename
(在您的示例中, $using:RootPathDestination
。请参阅Get-Help about_Remote_Variables
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.