Ricardo de Vries
Ricardo de Vries

Reputation: 63

Use a CSV file to parameterize commands executed on remote machines

I am working on this all night and now i think i need help :-) A am new to Powershell and i already did a lot of research but i cant find the right answer, i hope someone here can help me.

What i am trying to do is deploy a IIS Application to a couple of servers. I managed to add the application to a website, in my case i used the "Default Web Site" with the following code:

Get-Content c:\scripts\servers.txt | Foreach {  Invoke-Command -ComputerName $_ {Import-Module WebAdministration ; New-WebApplication -Site "Default Web Site" -Name TestRico2 -PhysicalPath C:\inetpub\wwwroot\} }

This is the content of the servers.txt:

WEB01
WEB02
WEB03

And that is actually working fine. But the thing i would like to achieve is that the other items are also dynamically:

-Site "Default Web Site"  
-Name TestRico2  
-PhysicalPath C:\inetpub\wwwroot\  

So, i want to have a CSV file like:

server,site,name,path  
WEB01,Default Web Site,Application-name,c:\inetpub\wwwroot\  
WEB02,Default Web Site,Application-name2,c:\inetpub\wwwroot2\  

I have no clue anymore, is there anyone out there who could help?

Upvotes: 1

Views: 537

Answers (1)

mklement0
mklement0

Reputation: 439767

Import-Csv reads CSV files and represents each input row as a custom object whose properties are named for the CSV column headers, and whose values are the respective rows' column values.

Therefore, use Import-Csv instead of Get-Content and access the values of interest as properties of the input object at hand, $_:

Import-Csv c:\scripts\servers.csv | ForEach-Object { 
  Invoke-Command ComputerName $_.server  { 
    param($site, $name, $path)
    Import-Module WebAdministration; 
    New-WebApplication -Site $site -Name $name -PhysicalPath $path
  } -Args $_.site, $_.name, $_.path
}

Note how properties $_.site, $_.name, $_.path are passed as arguments to the script block passed to Invoke-Command, because the script block is executed on the target machine, where the local variables aren't available.

In PSv3+ or higher, the alternative to passing arguments is to use the $using: scope to refer to local variables directly inside the script block - see
Get-Help about_Remote_Variables.

Upvotes: 1

Related Questions