How to enter new line to html with Powershell - html

I have a PowerShell script that opens an IE browser and fill a form.
I also have an csv file with phone numbers. how can I insert each phone number to new line on the value tag?
tried already:
$phoneBox = $IE.Document.getElementById($phonesID)
$phones = Get-Content -Path "c:\phones.csv"
foreach($p in $phones)
{
$phoneBox.value += "<br>" + $p + "<\br>"
}
and also:
$phoneBox = $IE.Document.getElementById($phoneID)
$phones = Get-Content -Path "c:\phones.csv"
foreach($p in $phones)
{
$phoneBox.value += $p + "\n"
}
and also:
$phoneBox = $IE.Document.getElementById($phoneID)
$phones = Get-Content -Path "c:\phones.csv"
foreach($p in $phones)
{
$phoneBox.value += $p + "
" + "
"
}
EDIT:
The Html element I AM REFERING TO IS:
<textarea name="ctl00$MainContent$reciSel$TabsContacts$tabFromFile$txtFromFile" tabIndex="0" id="ctl00_MainContent_reciSel_TabsContacts_tabFromFile_txtFromFile" style="width: 98%; height: 386px; overflow-x: hidden;" onkeyup="PhoneNumbersTxt_onChange(this.value);" onkeypress="AddNewLine(this,event);" rows="2" cols="20" wrap="off" autocomplete="off">Here I need to enter each number to new line</textarea>

Literal whitespace is not parsed as formatting information in HTML (all consecutive whitespace is collapsed to a single space in the output).
Either put each phone number in a separate paragraph
$phoneBox.value += '<p>' + $p + '</p>'
or (if you want it in a single block element with a linebreak after each entry) put a single <br> (or <br/> if you want valid XHTML) after the number:
$phoneBox.value += $p + '<br>'
That does not apply to the content of textareas, though. For those you add linebreaks like this (LF only):
$phoneBox.value += $p + "`n"
or like this (CR-LF):
$phoneBox.value += $p + "`r`n"
PowerShell escape sequences start with a backtick, not a backslash.

Related

Why my PowerShell script not run as expected

I have created a script to crawl the IMDB website. My script take a list of IMDB urls, run and extract the data like movie title, release year, plot summary and export it to a text file in CSV. I wrote the script as below.
$listToCrawl = "imdb_link_list.txt"
$pathOfFile = "K:\MY DOCUMENTS\POWERSHELL\IMDB FILE\"
$fileName = "plot_summary.txt"
New-Item ($pathOfFile + $fileName) -ItemType File
Set-Content ($pathOfFile + $fileName) '"Title","Year","URL","Plot Summary"'
Get-Content ($pathOfFile + $listToCrawl) | ForEach-Object {
$url = $_
$Result = Invoke-WebRequest -Uri $url
$movieTitleSelector = "#title-overview-widget > div.vital > div.title_block > div > div.titleBar > div.title_wrapper > h1"
$movieTitleNode = $Result.ParsedHtml.querySelector( $movieTitleSelector)
$movieTitle = $movieTitleNode.innerText
$movieYearSelector = "#titleYear"
$movieYearNode = $Result.ParsedHtml.querySelector($movieYearSelector)
$movieYear = $movieYearNode.innerText
$plotSummarySelector = "#titleStoryLine > div:nth-child(3) > p > span"
$plotSummaryNode = $Result.ParsedHtml.querySelector($plotSummarySelector)
$plotSummary = $plotSummary.innerText
$movieDataEntry = '"' + $movieTitle + '","' + $movieYear + '","' + $url + '","' + $plotSummary + '"'
Add-Content ($pathOfFile + $fileName) $movieDataEntry
}
The list of urls to extract from is saved in the "K:\MY DOCUMENTS\POWERSHELL\IMDB FILE\imdb_link_list.txt" file and the content is as below.
https://www.imdb.com/title/tt0472033/
https://www.imdb.com/title/tt0478087/
https://www.imdb.com/title/tt0285331/
https://www.imdb.com/title/tt0453562/
https://www.imdb.com/title/tt0120577/
https://www.imdb.com/title/tt0416449/
I just import and run the script. It does not run as expected. The error is threw.
Invalid argument.
At K:\MY DOCUMENTS\POWERSHELL\IMDB_Plot_Summar_ Extract.ps1:20 char:1
+ $plotSummaryNode = $Result.ParsedHtml.querySelector($plotSummarySelec ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
I think the problem is due to the CSS selector I use to select the data but I don't know what's wrong. I think I have followed the CSS selector rule.
$plotSummarySelector = "#titleStoryLine > div:nth-child(3) > p > span"
Does anyone know what's wrong with the thing.
The ParsedHtml property is specific to PowerShell for Windows and doesn't exist in PowerShell Core, so if you want to future-proof your code you're better off using something like the HTML Agility Pack.
# install the HTML Agility Pack nuget package
Invoke-WebRequest -Uri "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" -OutFile ".\nuget.exe";
.\nuget.exe install "HtmlAgilityPack" -Version "1.11.21";
# import the HTML Agility Pack
Add-Type -Path ".\HtmlAgilityPack.1.11.21\lib\Net40\HtmlAgilityPack.dll";
# get the web page content and load it into a HtmlDocument
$response = Invoke-WebRequest -Uri "https://www.imdb.com/title/tt0472033/" -UseBasicParsing;
$html = $response.Content;
$doc = new-object HtmlAgilityPack.HtmlDocument;
$doc.LoadHtml($html);
then you can extract nodes using XPath syntax - e.g. for the title:
# extract the title
$titleHtml = $doc.DocumentNode.SelectSingleNode("//div[#class='title_wrapper']/h1/text()[1]").InnerText;
$titleText = [System.Net.WebUtility]::HtmlDecode($titleHtml).Trim();
write-host "'$titleText'"; # '9'
I'll leave the rest of the document elements as an exercise for the reader :-).

Get Value of JSON Sting in PowerShell

First of all thank you in advance. I am trying to retrieve the following values from the JSON string below using PowerShell but am having issues.
ScheduleTitle,
Title,
Environment and Title
Resolution,
Width,
Height
JSON:
{"Id":"d52fb00e-8736-448c-a496-96db6bc2eb43","ScheduleId":"275726dc-09f2-4869-b1a0-54c71ef6a093","ScheduleTitle":"Resolution Testing","RunType":"RunNow","Timestamp":"2017-08-01T04:52:19.2039685","AutomationRunItems":[{"Id":"f7b731fb-cd96-4003-b95c-ef1594f1c86e","AutomationRunId":"d52fb00e-8736-448c-a496-96db6bc2eb43","Status":"Done","Case":{"Id":"c8a0b939-54ba-4b98-8ca9-101093aec26f","Title":"Resolution Test"},"Environment":{"Id":"e1783fb5-4001-45d0-9971-b49c31b374ab","Title":"Se Chrome"},"Keyframes":[{"Timestamp":"2017-08-01T04:52:03.0685609","Elapsed":"00:00:00","Level":"Info","Status":"Connecting","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Connecting to Se Chrome: Selenium Grid (localhost:5559) on Chrome with size 1280x1024"},{"Timestamp":"2017-08-01T04:52:03.0685609","Elapsed":"00:00:00.0000003","Level":"Info","Status":"Connected","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Connected"},{"Timestamp":"2017-08-01T04:52:03.0685609","Elapsed":"00:00:00.0000015","Level":"Info","Status":"Running","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Running"},{"Timestamp":"2017-08-01T04:52:03.0695642","Elapsed":"00:00:00.0003729","Level":"Trace","Status":"Running","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:03.5713896","Elapsed":"00:00:00.5020154","Level":"Trace","Status":"Running","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Block is executed."},{"Timestamp":"2017-08-01T04:52:03.5713896","Elapsed":"00:00:00.5021370","Level":"Trace","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:06.9793063","Elapsed":"00:00:03.9107459","Level":"Info","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Chrome was successfully started"},{"Timestamp":"2017-08-01T04:52:09.4641639","Elapsed":"00:00:06.3955903","Level":"Info","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Chrome loaded url https://dev.bamapplication.com/app/starke/npr/3BF6DA09C1/wizard"},{"Timestamp":"2017-08-01T04:52:09.7604882","Elapsed":"00:00:06.6925088","Level":"Trace","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Block is executed."},{"Timestamp":"2017-08-01T04:52:09.7604882","Elapsed":"00:00:06.6926471","Level":"Trace","Status":"Running","BlockId":"26382d5d-60a6-4343-b934-265c4e97186d","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:10.4639126","Elapsed":"00:00:07.3954580","Level":"Warning","Status":"Running","BlockId":"26382d5d-60a6-4343-b934-265c4e97186d","LogMessage":"Web screenshot is saved"},{"Timestamp":"2017-08-01T04:52:10.7666916","Elapsed":"00:00:07.6982198","Level":"Trace","Status":"Running","BlockId":"26382d5d-60a6-4343-b934-265c4e97186d","LogMessage":"Block is executed."},{"Timestamp":"2017-08-01T04:52:10.7666916","Elapsed":"00:00:07.6983727","Level":"Trace","Status":"Running","BlockId":"161e621f-bb7a-4f42-a5f1-67e07d1432f4","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:11.7677637","Elapsed":"00:00:08.6992111","Level":"Info","Status":"Done","BlockId":"161e621f-bb7a-4f42-a5f1-67e07d1432f4","LogMessage":"Case is stopped."}],"Resolution":{"Width":1280,"Height":1024},"Elapsed":"00:00:08.6992111","CreatedAt":"2017-08-01T04:52:19.2039685","ModifiedAt":"2017-08-01T04:52:19.2039685"}],"ProjectId":"275726dc-09f2-4869-b1a0-54c71ef6a093","ExecutionTotalTime":"00:00:08.6992111","FailedCount":0,"PassedCount":0,"DoneCount":1,"CreatedAt":"2017-08-01T04:52:03.0685609"}
Code:
Param( [string]$result, [string]$rootPath )
try{
$json = $result
$parsed = $json | ConvertFrom-Json
$output= ''
foreach ($line in $parsed | Get-Member) {
Write-Output $parsed.$($line.Resolution).property1
Write-Output $parsed.$($line.Resolution).property2
$output += $parsed.$($line.Resolution).property1 + " " + $parsed.$($line.Resolution).property1
}
}
With your $parsed data you can extract all the information you need.
For example to extract the width:
echo $parsed.AutomationRunItems.Resolution.Width
should print: 1280
I think these are all the fields you need extracted. Note, since you did not specify the output precisely I have simply used comma-delimited strings:
$output= ''
$output = $output + $parsed.ScheduleTitle + ','
$output = $output + $parsed.AutomationRunItems.Case.Title + ','
$output = $output + $parsed.AutomationRunItems.Environment.Title + ','
$output = $output + $parsed.AutomationRunItems.Resolution.Width + ','
$output = $output + $parsed.AutomationRunItems.Resolution.Height
Should Print: Resolution Testing,Resolution Test,Se Chrome,1280,1024

Powershell removing utf-8/ html formatting when combining files

This code is meant to combine 3 pieces of html the main is generated by ppowershell when the document is opened, it doesn't appear right and when opened in an html editor it doesn't support / improper format it looks like this.
��<!DOCTYPE HTML>
Here is the code used to combine the files, the head and tails are html files
$main += $tile
$html = $head + $main + $tail
$html > .\Report.html
I was able to figure it out I used set content to enforce UTF8
$main += $tile
$html = $head + $main + $tail
$html | Set-Content -Encoding UTF8 -Path test2.html
try this
$html | out-file "Report.html" -Encoding UTF8

post value in perl cgi and HTML not inserting properly

i am new to Perl and using Perl in my back end script and HTML in front end and CGI framework . Initially i am reading some details from flat file and displaying them . I am then trying to print the details in the form of checkboxes. i am using use Data::Dumper; module to check the values . however my input value of the last checkbox has an extra space as shown below
print '<form action="process.pl " method="POST" id="sel">';
print '<input type="checkbox" onClick="checkedAll()">Select All<br />';
foreach my $i (#robos) {
print '<input type="checkbox" name="sel" value="';
print $i;
print '">';
print $i;
print '<br />';
}
print '<input type="submit" value="submit">';
print '</form>';
print "response " . Dumper \$data;
however in Process.pl the selected value is retrieved using
#server = $q->param('sel');
but the response of selection is
print "response " . Dumper \#server; => is showing [ 'ar', 'br', 'cr ' ]; which is
showing an additional space after cr . I dont know whats is wrong .
In my flat file i have
RMCList:ar:br:cr
i am then reading the details into an array and splitting using
foreach my $ln (#lines)
{
if ($ln =~ /^RMCList/)
{
#robos = split (/:/,$ln);
}
} #### end of for statement
shift (#robos);
print "The robos are ", (join ',', map { '"' . $_ . '"' } #robos), "\n";
This is showing the robos are:
"ar","br","cr
"
While reading the file into #lines, you forgot to remove the newline. This newline is interpreted as a simple space in a HTML document.
Remove the newlines with the chomp function like
chomp #lines;
before looping over the lines.
Actually, don't read the file into an array at all, unless you have to access each line more than once. Otherwise, read one line at the time:
open my $infile, "<", $filename or die "Cannot open $filename: $!";
my #robos;
while (my $ln = <$infile>) {
chomp $ln;
#robos = split /:/, $ln if $ln =~ /^RMCList/;
}

Enterprise Architect code generation templates: import hierarchical package structure as a string

Problem
In Enterprise Architect 7.1.834 in the code generation templates it is possible to print all the parent packages that a class belongs to in the scope of the File template?
The reason this is needed is to generate multi-include guards compliant with my companies coding standard
What doesn't work
I have tried both:
%list="Namespace__Notes" #separator="-"%
and
%packageName%
The output of both only prints the top-level parent package (Package1) but I would like to see:
Package1-Package2-Package3
Has anyone found a way to do this?
Namepace__Notes
Namepace__Notes is a custom template with Namepace type, the contents are ar follows
%PI=""%
%packageName%
[Edit] Dirty Solution
My current (dirty) solution is to mangle the file-path. Am I missing something?
The code:
$l_backslash = %REPLACE("\z","z","")%
$filepath = %filePath%
$upper_filepath = %TO_UPPER($filepath)%
$upper_package_as_path = $l_backslash + %TO_UPPER(packageName)% + $l_backslash
$upper_package_base_len = %LENGTH(packageName)%
$package_path_pos = %FIND($upper_filepath,$upper_package_as_path)%
%if $package_path_pos != "-1" and $package_path_pos != "0"%
$upper_filepath = %MID($upper_filepath,$package_path_pos)%
%endIf%
$file_define = "_" + $upper_filepath + "__"
$file_define = %REPLACE($file_define,".","_")%
$file_define = %REPLACE($file_define,$l_backslash,"_")%
$file_define = %REPLACE($file_define,"/","_")%
$body += "/**************************************************************************//**"
$body += "\n * \file " + %fileName%
$body += "\n *"
$body += "\n * \brief " + %elemType% + " " + %className% + " header file"
$body += "\n *"
$body += "\n * \author " + %classAuthor ? value : "<unknown>"%
$body += "\n *"
$body += "\n *****************************************************************************/"
$body += "\n"
$body += "\n#ifndef " + $file_define
$body += "\n#define " + $file_define
$body += "\n"
%packagePath% gives you the dot-separated package hierarchy, while %classQualName% yields the ::-separated class hierarchy (for inner classes).
This is for the current version, I don't know whether these macros were present as far back as 7.1. You should seriously consider upgrading, as the current version is 9.3 and EA is backwards-compatible wrt project contents.
In EA 10 %packagePath% also gives only top level package in File template
[Edit] Another dirty and partial solution.
I'v made a new custom templates, Namespace__fullName:
$prevName = %list="Namespace__fullName"%
%if $prevName != ""%
%packageName%::$prevName
%else%
%packageName%
%endIf%
;
and Class__fullQualName:
%list="Namespace__fullName"%::%classQualName%
This will work in simple cases when the source file contains only 1 class (possibly with nested items) and, therefore, only 1 namespaces hierarchy.