1

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

2 Answers 2

2

You have to use the using prefix:

Invoke-Command -ComputerName $servername  { new-item -Path "$using:RootPathDestination" -Name $using:version -Itemtype directory }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Perfect, Thank you! For all other users with the same options: Invoke-Command -ComputerName $servername { new-item -Path $Using:destinationpath -name $Using:versionnumber -Itemtype directory }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.