I seem to have a issue with getting variables in the 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
. 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.