我正在开发一个PS脚本,它为每个机器执行以下操作,其中hostname是文件中的一行
我很难理解第3步的语法: 如果'ServerPort = 443',请将其更改为'ServerPort = 444' ElseIf'ServerPort = 444',将其更改为'ServerPort = 443'
这是我到目前为止的地方:
$servers = Get-Content 'C:\Servers.txt'
foreach ($server in $servers){
# stop service and wait.
(get-service -ComputerName $server -Name SERVICENAME).stop
# Logic to see string. Looking for "ServerPort=%". Detect if Server port is 444 or 443. If one, set to other
# Get Port from config file
$port = get-content C:\config.ini | Where-Object {$_ -like 'ServerPort=*'}
# Conditionally update port
IF ($port -eq "ServerPort=443")
{
# update to 444
}
ELSEIF ($port -eq "ServerPort=444")
{
# update to 443
}
ELSE
{
Write-Host "Value not detected within Param"
}
#start service
(get-service -ComputerName $server -Name SERVICENAME).start
}
基于我在这里发生的事情,我认为语法必须重新打开文件,重新搜索该行然后更新它...当通过网络时效率很低......也许有一个更合理,更简单的方法来解决这个问题?
非常感谢您的帮助!
-Wes
答案 0 :(得分:1)
我重写了一些你的脚本。看看这个:
# Define the name of the service to stop/start
$ServiceName = 'wuauserv';
# Get a list of server names from a text file
$ServerList = Get-Content -Path 'C:\Servers.txt';
foreach ($Server in $ServerList){
# Stop service and wait
Get-Service -ComputerName $Server -Name $ServiceName | Stop-Service;
# Logic to see string. Looking for "ServerPort=%". Detect if Server port is 444 or 443. If one, set to other
# Read the config.ini file into $ConfigFile variable
$ConfigFilePath = "\\$Server\c$\config.ini";
$ConfigFile = Get-Content -Path $ConfigFilePath -Raw;
if ($ConfigFile -match 'ServerPort=443')
{
# Change ServerPort to 444
Set-Content -Path $ConfigFilePath -Value ($ConfigFile -replace 'ServerPort=443', 'ServerPort=444');
}
elseif ($ConfigFile -match 'ServerPort=444') {
# Change ServerPort to 443
Set-Content -Path $ConfigFilePath -Value ($ConfigFile -replace 'ServerPort=444', 'ServerPort=443');
}
else {
Write-Host -Object ('Could not find matching ServerPort value in {0}' -f $ConfigFilePath);
}
Get-Service -ComputerName $server -Name $ServiceName | Start-Service;
}