|
Компьютерный форум OSzone.net » Программирование, базы данных и автоматизация действий » Скриптовые языки администрирования Windows » PowerShell - соединить три скрипта общим выводом. |
|
PowerShell - соединить три скрипта общим выводом.
|
Старожил Сообщения: 211 |
доброго времени суток. Есть три скрипта, которые написали участники данного форума. Первый снимает
мак-адрес
мониторах
$ofs = '' gwmi wmimonitorid -Namespace root\wmi | Select @{n='UserFriendlyName';e={([string][Char[]]$_.UserFriendlyName).SubString(0,$_.UserFriendlyNameLength)}}, @{n='SerialNumberID';e={[string][Char[]]$_.SerialNumberID}} | export-csv 'D:\PowerShell\monitor2.csv' -Delimiter ';' -Encoding utf8 -NoTypeInformation морд
[code]
param ( #[parameter(Mandatory=$true)] $encode = 65001, [string]$outfile = 'table.csv', [int]$number = 1 ) function convert ($from, $to){ begin{ $fenc = [text.encoding]::getencoding($from) $tenc = [text.encoding]::getencoding($to) } process{ $a = $tenc.getbytes($_) $fenc.getstring($a) } } [net.servicepointmanager]::securityprotocol = 'ssl3,tls,tls11,tls12' [array]$arr = $((Get-Netipaddress |? ipaddress -match "^10\.").ipaddress -replace "\d+$") $ips = 130..190 |%{$n=$_;$arr|%{"$_"+$n}}|sort|?{test-connection $_ -count 1 -q} $ips|%{ $html = iwr $_ $tables = $html.parsedhtml.getelementsbytagname("table") $tbl = ($tables|?{($_.getelementsbytagname('table')|%{$_}).count -eq 0})[$number]|%{ $headers = @(); $tr = $_|%{$_.getelementsbytagname("tr")} if($headers = $tr|?{$_.firstchild().tagname -eq 'th'}| %{$_.getelementsbytagname("th")}|select -exp innertext){ if ($headers -match [char]208){$headers=$headers|convert $encode 28591} $headers = $headers.trim() } else { $headers = 1..([linq.parallelenumerable]::max( [linq.parallelenumerable]::asparallel($tr.lastchild().cellindex) )+1)|%{"H$_"} } $rowind = ,1 * $headers.count $tr.where({$_.firstchild().tagname -eq 'td'})|%{ $row = $_.getelementsbytagname("td") |? innertext -ne $null| select innertext,rowspan,colspan if($row.innertext -match [char]208){ for($i=0;$i -lt $row.count;$i++){ $row[$i].innertext = $row[$i].innertext|convert $encode 28591 } } try { $str = [ordered]@{} $k=0 foreach ($item in $row){ if ($rowind[$k] -gt 1){ while ($rowind[$k] -gt 1){ $str[$headers[$k]] = $null $rowind[$k] -= 1 $k++ } } if (($colspan = $item.colspan) -gt 1) { $str[$headers[$k]] = if($item.innertext){ $item.innertext.trim() } else {$null} if ($item.rowspan -gt 1){$rowind[$k] = $item.rowspan} $k++ while ($colspan -gt 1){ $str[$headers[$k]] = $null $colspan -=1 if ($rowind[$k] -gt 1){$rowind[$k]-=1} $k++ } } else { $str[$headers[$k]] = if($item.innertext){ $item.innertext.trim() } else {$null} if ($item.rowspan -gt 1){$rowind[$k] = $item.rowspan} $k++ } } [pscustomobject]$str } catch { write-host Разметка заголовков не соответствует размерам строк -for red write-host $_ -for cyan } } } [pscustomobject]@{ 'IP' = $_ 'MAC-адрес' = $tbl[([array]::indexof($tbl.h1,'MAC-адрес'))].h2 'Номер телефона' = if ([array]::indexof($tbl.h1,'Номер телефона') -ne -1){ $tbl[([array]::indexof($tbl.h1,'Номер телефона'))].h2 } else { $tbl[([array]::indexof($tbl.h1,'Номер телефона 1'))].h2 } 'Серийный номер' = $tbl[([array]::indexof($tbl.h1,'Серийный номер'))].h2 'Номер модели' = $tbl[([array]::indexof($tbl.h1,'Номер модели'))].h2 } } |export-csv D:\PowerShell\123.csv -notype -enc utf8 -d ';' |
|
Отправлено: 07:39, 20-04-2020 |
Старожил Сообщения: 211
|
Профиль | Отправить PM | Цитировать было бы это в батнике, я бы просто слепил бы в один файл, а вывод настроил бы с помощью >, а второй и третий скрипт через >>. Тут оказалось сложнее как-то
|
Отправлено: 12:22, 21-04-2020 | #2 |
Для отключения данного рекламного блока вам необходимо зарегистрироваться или войти с учетной записью социальной сети. Если же вы забыли свой пароль на форуме, то воспользуйтесь данной ссылкой для восстановления пароля. |
Старожил Сообщения: 211
|
Профиль | Отправить PM | Цитировать нашел два параметра -NoClobber -Force, вроде они выполняют функцию > >> подобно bat, но пока со значениями непонятно. Получается, что можно подобно батнику просто скопировать три скрипта в одно тело, а вывод у каждого свой, но в один и тот же файл. Первый скрипт будет перезаписывать файл, а два другие только дописывать.
|
Отправлено: 12:49, 21-04-2020 | #3 |
Crazy Сообщения: 1218
|
Профиль | Отправить PM | Цитировать Цитата Griboed0ff:
|
|
------- Отправлено: 20:46, 21-04-2020 | #4 |
Старожил Сообщения: 211
|
Профиль | Отправить PM | Цитировать Цитата YuS_2:
слепил три вместе
Get-WmiObject Win32_NetworkAdapter -Filter 'AdapterTypeId = 0 and MACAddress is not null' | select @{n='Системный блок';e={$_.macaddress}}| Out-File 'D:\PowerShell\temp\общий.csv' $ofs = '' gwmi wmimonitorid -Namespace root\wmi | Select @{n='UserFriendlyName';e={([string][Char[]]$_.UserFriendlyName).SubString(0,$_.UserFriendlyNameLength)}}, @{n='SerialNumberID';e={[string][Char[]]$_.SerialNumberID}} | Out-File 'D:\PowerShell\temp\общий.csv' -Append param ( #[parameter(Mandatory=$true)] $encode = 65001, [string]$outfile = 'table.csv', [int]$number = 1 ) function convert ($from, $to){ begin{ $fenc = [text.encoding]::getencoding($from) $tenc = [text.encoding]::getencoding($to) } process{ $a = $tenc.getbytes($_) $fenc.getstring($a) } } [net.servicepointmanager]::securityprotocol = 'ssl3,tls,tls11,tls12' [array]$arr = gc 'D:\PowerShell\list_Net.txt' $ips = 130..190 |%{$n=$_;$arr|%{"$_"+$n}}|sort|?{test-connection $_ -count 1 -q} $ips|%{ if (test-connection $_ -count 1 -q){ try{ $html = iwr $_ $tables = $html.parsedhtml.getelementsbytagname("table") $tbl = ($tables|?{($_.getelementsbytagname('table')| %{$_}).count -eq 0})[$number]|%{ $headers = @(); $tr = $_|%{$_.getelementsbytagname("tr")} if($headers = $tr|?{$_.firstchild().tagname -eq 'th'}| %{$_.getelementsbytagname("th")}|select -exp innertext){ if ($headers -match [char]208){$headers=$headers|convert $encode 28591} $headers = $headers.trim() } else { $headers = 1..([linq.parallelenumerable]::max( [linq.parallelenumerable]::asparallel($tr.lastchild().cellindex) )+1)|%{"H$_"} } $rowind = ,1 * $headers.count $tr.where({$_.firstchild().tagname -eq 'td'})|%{ $row = $_.getelementsbytagname("td") |? innertext -ne $null| select innertext,rowspan,colspan if($row.innertext -match [char]208){ for($i=0;$i -lt $row.count;$i++){ $row[$i].innertext = $row[$i].innertext|convert $encode 28591 } } $str = [ordered]@{} $k=0 foreach ($item in $row){ if ($rowind[$k] -gt 1){ while ($rowind[$k] -gt 1){ $str[$headers[$k]] = $null $rowind[$k] -= 1 $k++ } } if (($colspan = $item.colspan) -gt 1) { $str[$headers[$k]] = if($item.innertext){ $item.innertext.trim() } else {$null} if ($item.rowspan -gt 1){$rowind[$k] = $item.rowspan} $k++ while ($colspan -gt 1){ $str[$headers[$k]] = $null $colspan -=1 if ($rowind[$k] -gt 1){$rowind[$k]-=1} $k++ } } else { $str[$headers[$k]] = if($item.innertext){ $item.innertext.trim() } else {$null} if ($item.rowspan -gt 1){$rowind[$k] = $item.rowspan} $k++ } } [pscustomobject]$str } } [pscustomobject]@{ 'IP' = $_ 'MAC-адрес' = $tbl[([array]::indexof($tbl.h1,'MAC-адрес'))].h2 'Номер телефона' = if ([array]::indexof($tbl.h1,'Номер телефона') -ne -1){ $tbl[([array]::indexof($tbl.h1,'Номер телефона'))].h2 } else { $tbl[([array]::indexof($tbl.h1,'Номер телефона 1'))].h2 } 'Серийный номер' = $tbl[([array]::indexof($tbl.h1,'Серийный номер'))].h2 'Номер модели' = $tbl[([array]::indexof($tbl.h1,'Номер модели'))].h2 } } catch { write-host Ошибка: $_ -for red } } } Out-File 'D:\PowerShell\temp\общий.csv' -Append Скрытый текст
строка:10 знак:12 + $encode = 65001, + ~~~~~ Недопустимое условие назначения. Входным значением оператора назначения должен быть объект, способный принимать назначения, такой как переменная или свойство. строка:11 знак:21 + [string]$outfile = 'table.csv', + ~~~~~~~~~~~ Недопустимое условие назначения. Входным значением оператора назначения должен быть объект, способный принимать назначения, такой как переменная или свойство. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : InvalidLeftHandSide Скрытый текст
write-host Ошибка: $_ -for red } } } Out-File 'D:\PowerShell\temp\общий.csv' -Append ForEach-Object : Не удается привязать параметр "RemainingScripts". Не удается преобразовать значение "Out-File" типа "System.String" в тип "System.Management.Automation.ScriptBlock". строка:22 знак:6 + $ips|%{ + ~~ + CategoryInfo : InvalidArgument: (:) [ForEach-Object], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ForEachObjectCommand |
||
Отправлено: 16:13, 22-04-2020 | #5 |
Crazy Сообщения: 1218
|
Профиль | Отправить PM | Цитировать Цитата Griboed0ff:
Цитата Griboed0ff:
В данном случае, это параметры скрипта: Цитата Griboed0ff:
Цитата Griboed0ff:
|
||||
------- Отправлено: 17:56, 22-04-2020 | #6 |
Старожил Сообщения: 211
|
Профиль | Отправить PM | Цитировать Спасибо, все получилось. Я так понимаю, чтобы сделать это таблицей .csv надо перед Out-File еще команду вставить с оператором конвейером?
|
Отправлено: 19:03, 22-04-2020 | #7 |
Crazy Сообщения: 1218
|
Профиль | Отправить PM | Цитировать Цитата Griboed0ff:
|
|
------- Отправлено: 20:25, 22-04-2020 | #8 |
Старожил Сообщения: 211
|
Профиль | Отправить PM | Цитировать Цитата YuS_2:
|
|
Отправлено: 22:32, 22-04-2020 | #9 |
Crazy Сообщения: 1218
|
Профиль | Отправить PM | Цитировать Цитата Griboed0ff:
Monster_Frankenstein
param ( #[parameter(Mandatory=$true)] [string]$outfile = 'D:\PowerShell\temp\общий.csv', [string]$list = 'D:\PowerShell\list_Net.txt', $enc1 = 65001, $enc2 = 28591, [int[]]$SelectTable = 1 ) Get-WmiObject Win32_NetworkAdapter -Filter 'AdapterTypeId = 0 and MACAddress is not null' | select @{n='Системный блок';e={$_.macaddress}}| convertto-csv -d ';' -notype| out-file $outfile -enc utf8 $ofs = '' gwmi wmimonitorid -Namespace root\wmi | Select @{n='UserFriendlyName';e={ ([string][Char[]]$_.UserFriendlyName).SubString(0,$_.UserFriendlyNameLength) }}, @{n='SerialNumberID';e={[string][Char[]]$_.SerialNumberID}} | convertto-csv -d ';' -notype| out-file $outfile -enc utf8 -app #---Эту секцию можно удалить после однократного запуска скрипта от имени админа ------------------ # Установка дополнительного модуля PowerHTML, для независимого парсинга HTML # Может потребоваться ручное подтверждение установки. if (!(get-module -list powerhtml)) { write-verbose "Installing PowerHTML module for the current user..." install-module powerhtml #-scope currentuser } #----------------------------------------------------------------------------------------- function convert ($from, $to){ begin{ $fenc = [text.encoding]::getencoding($from) $tenc = [text.encoding]::getencoding($to) } process{ $a = $tenc.getbytes($_) $fenc.getstring($a) } } [net.servicepointmanager]::securityprotocol = 'ssl3,tls,tls11,tls12' [array]$arr = gc $list $ips = 130..190 |%{$n=$_;$arr|%{"$_"+$n}}|sort|?{test-connection $_ -count 1 -q} $ips|%{ if (test-connection $_ -count 1 -q){ try { $a = (iwr $_).content $content = if ($a -match [char]208){ if ($a -match 'windows-1251'){$enc1,$enc2 = 1251,1252} $a|convert $enc1 $enc2 } else {$a} $html = [net.webutility]::htmldecode($content)|convertfrom-html [array]$tables = $html.selectnodes('//table') # Исключение вложенных таблиц: $tables = $tables|?{$_.innerhtml -notmatch 'table'} if ([string]::isnullorempty($selecttable)){ $number = 0..($tables.count-1) } else {$number = $selecttable} $tbl = $tables[$number]|%{$n=0}{ $tr = if($_.element('tbody')){ $_.element('tbody').elements('tr') } else {$_.elements('tr')} $headers = @() if($headers = $tr|?{$_.element('th') -ne $null}| %{$_.elements('th')}|select -exp innertext){ $headers=$headers.trim() } else { $headers = 1..( [linq.parallelenumerable]::max( [linq.parallelenumerable]::asparallel(($tr| %{($_.elements('td')|? innertext -ne ''|%{$_}).count})) ) )|%{"H$_"} } $rowind = ,1 * $headers.count $tr|?{$_.elements('td') -ne ''}|%{ $row = $_.elements('td')|? innertext -ne ''|%{ $attr = $_.attributes if ($attr){ $rowspan = ($attr|? name -eq 'rowspan'|select value).value $colspan = ($attr|? name -eq 'colspan'|select value).value } [pscustomobject]@{ 'InnerText' = $_.innertext 'RowSpan' = if($rowspan){[int]$rowspan} else {1} 'ColSpan' = if($colspan){[int]$colspan} else {1} } } $str = [ordered]@{} $k=0 foreach ($item in $row){ if ($rowind[$k] -gt 1){ while ($rowind[$k] -gt 1){ $str[$headers[$k]] = $null $rowind[$k] -= 1 $k++ } } if (($colspan = $item.colspan) -gt 1) { $str[$headers[$k]] = if($item.innertext){ $item.innertext.trim() } else {$null} if ($item.rowspan -gt 1){$rowind[$k] = $item.rowspan} $k++ while ($colspan -gt 1){ $str[$headers[$k]] = $null $colspan -=1 if ($rowind[$k] -gt 1){$rowind[$k]-=1} $k++ } } else { $str[$headers[$k]] = if($item.innertext){ $item.innertext.trim() } else {$null} if ($item.rowspan -gt 1){$rowind[$k] = $item.rowspan} $k++ } } [pscustomobject]$str } } [pscustomobject]@{ 'IP' = $_ 'MAC-адрес' = if ([array]::indexof($tbl.h1,'MAC-адрес') -ne -1){ $tbl[([array]::indexof($tbl.h1,'MAC-адрес'))].h2 } else {$tbl[([array]::indexof($tbl.h1,'MAC Address'))].h2} 'Номер телефона' = if ([array]::indexof($tbl.h1,'Номер телефона') -ne -1){ $tbl[([array]::indexof($tbl.h1,'Номер телефона'))].h2 } elseif ([array]::indexof($tbl.h1,'Номер телефона 1') -ne -1){ $tbl[([array]::indexof($tbl.h1,'Номер телефона 1'))].h2 } else { $tbl[([array]::indexof($tbl.h1,'Phone DN'))].h2 } 'Серийный номер' = if ([array]::indexof($tbl.h1,'Серийный номер') -ne -1){ $tbl[([array]::indexof($tbl.h1,'Серийный номер'))].h2 } else {$tbl[([array]::indexof($tbl.h1,'Serial Number'))].h2} 'Номер модели' = if ([array]::indexof($tbl.h1,'Номер модели') -ne -1){ $tbl[([array]::indexof($tbl.h1,'Номер модели'))].h2 } else {$tbl[([array]::indexof($tbl.h1,'Model Number'))].h2} } } catch { write-host Ошибка: $_ -for red } } } | convertto-csv -d ';' -notype|out-file $outfile -enc utf8 -app |
|
------- Последний раз редактировалось YuS_2, 23-04-2020 в 06:46. Отправлено: 06:29, 23-04-2020 | #10 |
![]() |
Участник сейчас на форуме |
![]() |
Участник вне форума |
![]() |
Автор темы |
![]() |
Сообщение прикреплено |
| |||||
Название темы | Автор | Информация о форуме | Ответов | Последнее сообщение | |
Router - Как соединить три компьютера на один модем (ZTE ZXDSL-831CII) | AzaTur | Сетевое оборудование | 4 | 11-03-2015 00:56 | |
Route/Bridge - [решено] Три выхода в интернет, три офиса с общей локальной сетью | Senja | Сетевые технологии | 14 | 15-12-2014 17:21 | |
Загрузка - [решено] Восстановление загрузки - три HDD, три ОС | Vitalijs | Microsoft Windows 7 | 19 | 30-04-2010 01:10 | |
[решено] Авторизация из скрипта для доступа к общим папкам на внешнем сервере | 0bject | Microsoft Windows NT/2000/2003 | 4 | 01-11-2005 09:30 | |
Мона соединить три модема для игры? | Liven | Хочу все знать | 4 | 17-08-2002 01:05 |
|