将每行从文本文件发送到远程计算机?

时间:2016-06-15 13:43:05

标签: powershell

这是我在远程系统中将IP列入白名单的脚本。我希望我的脚本从我本地系统上的文本文件中读取数据,然后在foreach行我想在远程服务器上执行scriptblock。

文本文件如下所示:

url1
url2
url3

这是我的代码:

Invoke-Command -ComputerName $($server.text) -Credential ciqdev\riteshthakur {
  param($a, $b, $c, $url)

  Set-Location "C:\Windows\System32\inetsrv"
$url | foreach {
  .\appcmd.exe set config "$_" -section:system.webServer/security/ipSecurity /+"[ipAddress='$($a)',allowed='$($c)',subnetMask='$($b)']" /commit:apphost 
}
} -ArgumentList $ip.text, $mask.text, $allowed, (get-content "File location")

这会将提供的ip添加到IIS中所有网站的所有页面中。请帮忙。

2 个答案:

答案 0 :(得分:2)

编辑:通过动态生成命令并调用一次来提高效率。

我建议使用类似于以下的技术,在其中将文本文件作为行数组读入,然后遍历每一行,生成要在远程系统上运行的命令。

一旦您将命令生成为字符串,您只需调用静态[ScriptBlock]::Create()方法,根据命令字符串创建ScriptBlock对象,并将其传递给Invoke-Command

我建议你熟悉PowerShell Splatting的概念,我在这个YouTube视频中谈到了这个概念:https://www.youtube.com/watch?v=CkbSFXjTLOA。这是一个非常强大的概念,有助于使您的代码更易于阅读。下面的示例代码使用PowerShell Splatting(PowerShell 3.0及更高版本中提供)。

### Read the text file on the local system
$Whitelist = Get-Content -Path IPwhitelist.txt;

### Generate the stub for the remote command
$RemoteCommand = @'
param($a, $b, $c)

Set-Location -Path C:\Windows\System32\inetsrv
'@

### Add more commands to the remote command
foreach ($Line in $Whitelist) {
    $RemoteCommand += '{1}.\appcmd.exe set config "{0}" -section:system.webServer/security/ipSecurity /+"[ipAddress=''$($a)'',allowed=''$($c)'',subnetMask=''$($b)'']" /commit:apphost' -f $Line, "`n";
}

### Invoke the entire remote command (once)
$Command = @{
    ComputerName = $Server.Text
    Credential = Get-Credential -Credential ciqdev\riteshthakur
    ScriptBlock = [ScriptBlock]::Create($RemoteCommand);
    ArgumentList = @($ip.text, $mask.text, $allowed)
    }
Invoke-Command @Command;

答案 1 :(得分:2)

只需使用Get-Content cmdlet读取文件,然后使用Foreach-Object cmdlet迭代每个项目:

Invoke-Command -ComputerName $($server.text) -Credential ciqdev\riteshthakur {
  param($a, $b, $c, $urls)

  Set-Location "C:\Windows\System32\inetsrv"
  $urls | Foreach {
    .\appcmd.exe set config $_ -section:system.webServer/security/ipSecurity /+"[ipAddress='$($a)',allowed='$($c)',subnetMask='$($b)']" /commit:apphost
  }
} -ArgumentList $ip.text, $mask.text, $allowed, (Get-Content 'Path_to_your_file')
相关问题