Заменить строку на Powershell - PullRequest
       1

Заменить строку на Powershell

0 голосов
/ 10 октября 2018

У меня есть файл .properties, в котором я хочу заменить строку Compass на BBB.Мой вопрос: я хочу извлечь строку, которая принадлежит name, JDBC/, ds_name = '', java.lang.String, тогда я обновлю новую.Кстати, имя источника данных не является фиксированной его динамической переменной.Просто я написал это как пример строки.

Я пробовал следующий код PowerShell:

$DName = read-host -prompt "Please Enter Database Name"

ForEach ($client in (Get-Content Clients.txt)) {
    (Get-Content "\\$client\D$\Runtime\run.properties") -replace "$old database name which is extract","$DName" | 
        Out-File "\\$client\D$\Runtime\run.properties"
}

run.properties:

dsid = AdminTask.createDatasource(provider_id, '[-name Compass -jndiName jdbc/Compass 
-dataStoreHelperClassName com.ibm.websphere.rsadapter.MicrosoftSQLServerDataStoreHelper 
-componentManagedAuthenticationAlias TEMP-HRZEMM01Node01/PlatformDataSource -containerManagedPersistence true 
-xaRecoveryAuthAlias TEMP-HRZEMM01Node01/PlatformDataSource -configureResourceProperties [[databaseName java.lang.String Compass] [portNumber java.lang.Integer 1433] [serverName java.lang.String SQLSVR1]]]')

AdminConfig.create('MappingModule', dsid , '[[authDataAlias TEMP-HRZEMM01Node01/PlatformDataSource] [mappingConfigAlias ""]]')

ds_name = 'Compass' #Name copied from your question, update if required

1 Ответ

0 голосов
/ 10 октября 2018

Если я правильно понял вопрос, вы хотели бы сначала найти имя базы данных (которое может быть любым, Compass - это просто пример), сохраненное в файле .properties, и, если оно найдено, заменить его значением, введенным вconsole.

В этом случае, я думаю, что это следует сделать:

$newDbName = Read-Host -prompt "Please Enter Database Name"
$clientFile = "Clients.txt"

ForEach ($client in (Get-Content $clientFile)) {
    $content = Get-Content "\\$client\D$\Runtime\run.properties" -Raw
    # see if we can extract the database name from the file
    if ($content -match '(?:-name\s+|jdbc/|databaseName java\.lang\.String\s+|ds_name = '')(?<dbname>[^\s''\]]+)') {
        $oldDbName = $matches['dbname']

        Write-Host "Replacing '$oldDbName' with '$newDbName' for client '$client'" 
        ($content -replace $oldDbName, $newDbName) | 
            Out-File "\\$client\D$\Runtime\run.properties"
    } 
    else {
        Write-Warning "Could not parse the old database name from '\\$client\D$\Runtime\run.properties'.."
    }
}

Объяснение регулярного выражения

(?:                        Match the regular expression below
                           Match either the regular expression below (attempting the next alternative only if this one fails)
      -name                Match the characters “-name” literally
      \s                   Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
         +                 Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   |                       Or match regular expression number 2 below (attempting the next alternative only if this one fails)
      jdbc/                Match the characters “jdbc/” literally
   |                       Or match regular expression number 3 below (attempting the next alternative only if this one fails)
      databaseName\ java   Match the characters “databaseName java” literally
      \.                   Match the character “.” literally
      lang                 Match the characters “lang” literally
      \.                   Match the character “.” literally
      String               Match the characters “String” literally
      \s                   Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
         +                 Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   |                       Or match regular expression number 4 below (the entire group fails if this one fails to match)
      ds_name\ =\ '        Match the characters “ds_name = '” literally
)
(?<dbname>                 Match the regular expression below and capture its match into backreference with name “dbname”
   [^\s'\]]                Match a single character NOT present in the list below
                           A whitespace character (spaces, tabs, line breaks, etc.)
                           The character “'”
                           A ] character
      +                    Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...