Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: write value in a input type=file Form.

Tags:

I have a input type=text inputboxes on a webpage I load and fill with values and click the submit button which works fine:

$ie=New-Object -comobject InternetExplorer.Application 
$ie.visible=$true 
$ie.Navigate("https://myurl/test.html") 
while($ie.busy){Start-Sleep 1} 
$ie.Document.getElementById("field_firstName").value="Firstname" 
$ie.Document.getElementById("field_lastName").value="Lastname" 
$ie.Document.getElementById("btn_upload").Click() 
while($ie.busy){Start-Sleep 1}

I'd also like to populate a input type=file box with c:\temp\test.txt and upload this. I read that because of security reasons the value= is not supported from the browsers.

Is there any workaround to do this with PowerShell? Maybe "click" the browse button and select the file or use sendkeys?

like image 353
icnivad Avatar asked Feb 04 '10 10:02

icnivad


People also ask

How do you assign a value to an input file?

In HTML, we will use the type attribute to take input in a form and when we have to take the file as an input, the file value of the type attribute allows us to define an element for the file uploads.

How do you write content to a file in PowerShell?

You can also use PowerShell to write to file by appending to an existing text file with Add-Content Cmdlet. To append “This will be appended beneath the second line” to our existing file, first-file. txt, enter this command and press enter.


1 Answers

Check Jaykul's post. He uses Watin for automation. Just download the assembly and try. I was able to set the value and then submit the form like this:

$WatinPath = 'c:\bin\watin\WatiN.Core.dll' #path with downloaded assembly
$watin     = [Reflection.Assembly]::LoadFrom( $WatinPath )

$ie        = new-object WatiN.Core.IE("https://myurl/test.html")
$file1 = $ie.FileUpload('file1') #id of the input
$file1.set('C:\temp\test.txt') # path to the file

# and now just find the button and click on it
$o = $ie.Button('send') #send is id of the submit button
$o.Click()

I understand your reasons to use IE instead of WebClient and similar classes, however use them in other cases if possible.

Edit:

In case you don't have ID of the element, but only the name, you can try

$f = $ie.FileUpload({param($fu) $fu.GetAttributeValue("name") -eq 'the name you have' })

or

$f = $ie.FileUploads | ? { $_.GetAttributeValue("name") -eq 'the name you have' }
like image 148
stej Avatar answered Oct 11 '22 16:10

stej