Powershell:文件中的条件更改值

时间:2014-03-10 15:42:45

标签: powershell windows-services windows-server-2008-r2

我正在开发一个PS脚本,它为每个机器执行以下操作,其中hostname是文件中的一行

  1. 停止服务
  2. 检查.ini文件中的端口号
  3. 根据现有值
  4. 条件更新端口号
  5. 开始服务
  6. 我很难理解第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

1 个答案:

答案 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;
}