2011-02-04 2 views
1

Я создал сценарий PS, который запрашивает журналы событий на моих серверах, затем записывает информацию в простой старый html-файл. Проблема заключается в том, что html-файл - это просто, plian. То, что я хочу сделать, это добавить к нему текстовые данные jquery, чтобы я мог сортировать и организовывать его.Как я могу отредактировать HTML-тег с помощью PowerShell?

Использование команды «ConvertTo-HTML -head» Я могу вставить код, который мне нужен, в голову документа до документ написан. После того, как файл написан, мне нужно открыть его и изменить.

Проблема у меня есть, когда сценарий получает тег на замену части, я получаю эту ошибку:

Set-Content : The process cannot access the file C:\users\norm\Documents\eventlogs\2011\02\System\04\tc2.html' because it is being used by another process.

Я подозреваю, что это потому, что труба используется, чтобы открыть файл до сих пор он открыт , Итак, как мне закрыть файл? или есть лучший способ сделать это?

Спасибо, Norm

# EventLog viewer 

# Head for the HTML document. Adds the CSS and JQuery DataTables to the document. 
$h = '<head> <meta http-equiv="pragma" content="no-cache" />' 
$h = $h + '<title>Celeste EventLog Viewer</title>' 
$h = $h + '<link type="text/css" rel="stylesheet" href="css/demo_table_jui.css" />' 
$h = $h + '<link type="text/css" rel="stylesheet" href="themes/base/jquery.ui.all.css" />' 
$h = $h + '<link type="text/css" rel="stylesheet" href="css/stdcst.css" />' 
$h = $h + '<script language="JavaScript" src="js/jquery.min.js"></script>' 
$h = $h + '<script language="JavaScript" src="js/jquery.dataTables.js"></script>' 
$h = $h + '</head>' 
$h = $h + '<script type="text/javascript"> $(document).ready(function() {$("#t1").dataTable({"bJQueryUI": true,"sPaginationType": "full_numbers", "bInfo" : true }); });</script>' 
$ServerNames = "s1","s2","s3","s4","s5","s6","s7","s8","s9" 
$outdir = 'C:\users\norm\Documents\eventlogs\' 
$year = get-date -uformat "%Y" 
$month = get-date -uformat "%m" 
$day = get-date -uformat "%d" 
$count = $ServerNames.length 

# Get the length of ServerNames, iterate through x until x is greater than ServerNames 

for ($x=0; $x -lt $count; $x++) 
    { 
     # Before writing the file can begin the output directory needs to exsist. Test that it does, if not create it. 
     if ((Test-Path -path $outdir$year\$month\System\$day\) -ne $True) 
      { 
       New-Item $outdir$year\$month\System\$day\ -type directory 
      } 
     if ((Test-Path -path $outdir$year\$month\Application\$day\) -ne $True) 
      { 
       New-Item $outdir$year\$month\Application\$day\ -type directory 
      } 
     echo "Getting System log from " $ServerNames[$x] 
     #Query the System Event log and write it to an html file 
     Get-EventLog -computername $ServerNames[$x] -LogName System | ConvertTo-HTML -head $h | Out-File -encoding utf8 $outdir$year\$month\System\$day\"$($ServerNames[$x]).html"; 
     # Query the Aplication Event log and write it to an html file 
     echo "Getting Application log from " $ServerNames[$x] 
     Get-EventLog -computername $ServerNames[$x] -LogName Application | ConvertTo-HTML -head $h | Out-File -encoding utf8 $outdir$year\$month\Application\$day\"$($ServerNames[$x]).html"; 
    } 

for ($x=0; $x -lt $count; $x++) 
    { 
     #Open the files and replace the table tag 
     Get-Content $outdir$year\$month\System\$day\"$($ServerNames[$x]).html" | ForEach-Object { $_ -replace '<table>', '<table id="t1">'} | Set-Content $outdir$year\$month\"$($ServerNames[$x]).html"; 
    } 

    #give me a message to let me know the script has completed. 
    echo "Done!" 

ответ

1

Я хотел бы использовать Handle исследовать, какой процесс обращается к файлу. Simiraly вы можете использовать ProcessExplorer (запустите, нажмите CTRL + F, введите имя файла, Enter).

Edit:

Посмотрев на свой код, я вижу проблему. Линия Get-Content | process something | Set-Content - ваша проблема. Измените его следующим образом:

$a = Get-Content ... | process ... 
$a | Set-Content 

Cmdlet Get-Content открывает файл, считывает одну строку и отправляет строку в трубу. Затем он обрабатывается и эта первая строка передается по трубопроводу на Set-Content. Set-Content хотел бы написать, но Get-Content еще не закончен, потому что он читает только первую строку.

+0

Как я и подозревал. Я попробовал ваше предложение, и скрипт завершен, но не вносит изменений. Я думаю, что мое регулярное выражение не является правильным сейчас. – Norm

+0

Или нет элемента '

'. Вы также можете прочитать весь файл сразу через 'Get-Content -readCount 0'. – stej

1

Не похоже, что это должно быть необходимо, чтобы записать его в файл, а затем прочитать его обратно только, чтобы заменить этот тег:

Get-EventLog -computername $ServerNames[$x] -LogName System | 
    ConvertTo-HTML -head $h | 
    foreach-object { $_ -replace '<table>', '<table id="t1">'} | 
    Out-File -encoding utf8 $outdir$year\$month\System\$day\"$($ServerNames[$x]).html" 
+0

У кого-то есть «мыслящая шляпа» сегодня. :) Собираюсь проверить это. – Norm

+0

Итак, теперь это оставляет меня с пустым файлом. Arrggg more reading .. – Norm

+0

Исправлено и работает как шарм. Спасибо – Norm

1

В то время как ваши на него:

$h = @" 
    <title>Celeste EventLog Viewer</title> 
    <link type="text/css" rel="stylesheet" href="css/demo_table_jui.css" /> 
    <link type="text/css" rel="stylesheet" "href="themes/base/jquery.ui.all.css" /> 
    <link type="text/css" rel="stylesheet" href="css/stdcst.css" /> 
    <script language="JavaScript" src="js/jquery.min.js"></script> 
    <script language="JavaScript" src="js/jquery.dataTables.js"></script> 
    </head> 
    <script type="text/javascript"> $(document).ready(function() {$("#t1").dataTable({"bJQueryUI": true,"sPaginationType": "full_numbers", "bInfo" : true }); });</script> 
    "@ 
Смежные вопросы