gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:48:08 25 4
gpt4 key购买 nike

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

文本文件如下所示:

url1url2url3

Here is my code:

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中所有网站中的所有页面。请帮忙。

最佳答案

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

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

将命令生成为字符串后,只需调用静态[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;

关于powershell - 将每一行从文本文件发送到远程计算机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37837245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com