Invoke-Command的scriptblock中的变量问题

时间:2017-05-05 12:27:51

标签: powershell

我似乎在Invoke-Command中获取变量时出现问题。无论我做什么,我都无法获得变量。当我想使用时:

Invoke-Command -ComputerName $servername  { new-item -Path "$RootPathDestination" -Name $version -Itemtype directory }

我收到错误:

Cannot bind argument to parameter 'Path' because it is an empty string.

我在这个剧本中声明了它们:

$version = 36
$RootPathDestination = "c:\scripts\"

有没有人有任何想法?我真的没有选择: - (

 $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() 
         }

2 个答案:

答案 0 :(得分:2)

您必须使用使用前缀:

Invoke-Command -ComputerName $servername  { new-item -Path "$using:RootPathDestination" -Name $using:version -Itemtype directory }

答案 1 :(得分:1)

您正在将脚本块传递给Invoke-Command。为了使用脚本块中