Kazu
Kazu

Reputation: 137

How do I save a Notepad file automatically and close Notepad in Powershell

I am very new to Powershell. I have been struggling this project. I have been try to get and save this file in my computer. I tried to different ways and asked on Stack Overflow

When I execute this code

$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true
$ie.Navigate("https://idp.appery.io/idp/")

while ($ie.Busy -eq $true){Start-Sleep -seconds 1;}  

$usernamefield = $ie.Document.getElementByID('j_username')
$usernamefield.value= $username

$passwordfield = $ie.Document.getElementByID('j_password')
$passwordfield.value = $password

$Link=$ie.Document.getElementByID("loginBtn")
$Link.click()

while ($IE.Busy -eq $true)

{

Start-Sleep -Milliseconds 2000;

}

$ie.Navigate("https://appery.io/bttttn/rest/1/admin/databases")

When I execute above the code, Notepad will automatically pop up as "database.json", I looked for where is this json file in my C drive but I can not find it. It seems just opening file, so I would like to

  1. Save this "database.json" to my folder

  2. Close Notepad window,

How can I do that?

Thank you so much!!!

Upvotes: 1

Views: 1601

Answers (1)

Michael B
Michael B

Reputation: 12228

Unfortunately you can't automate notepad! (you might be able to send key strokes to it, but it will get very messy and prone to breakage)

A much better way would be to use invoke-webrequest to login and then download the file

$request = Invoke-WebRequest $loginpage -SessionVariable "session"
$form = $request.Forms[0]
$form = $request.form['username']
$form = $request.form['password']
$request = Invoke-WebRequest -Uri ('$downloadlink + $form.Action) `
                 -WebSession $session -Method POST `
                 -Body $form.Fields -OutFile $filepath

If the page doesn't return a form object, you could do

$form = @{ "username" = $username
           "password = $password} 

You will need to look at the login page and extract the variable names for username / password.

I've also not tested it! so its kind of from memory, but it should get you on a much more reliable track.

Upvotes: 1

Related Questions