powershell invoke-webrequest to log into website

35,962

Don't put a $ for the session variable argument. Try this -

$c = $host.UI.PromptForCredential('Your Credentials', 'Enter Credentials', '', '')
$r = Invoke-WebRequest 'http://1.2.3.4/' -SessionVariable my_session
$form = $r.Forms[0]
$form.fields['username'] = $c.UserName
$form.fields['password'] = $c.GetNetworkCredential().Password
$r = Invoke-WebRequest -Uri ('http://1.2.3.4' + $form.Action) -WebSession $my_session -Method POST -Body $form.Fields
Share:
35,962
Mike
Author by

Mike

Updated on August 07, 2022

Comments

  • Mike
    Mike over 1 year

    I have been having a lot of success using invoke-webrequest to log in to websites but I'm stumped. I am trying to log into https:// ctslink.com or https:// direct.ctslink.com. The login form has a hidden token field which changes every time I try to login, I believe is what is causing the problem. Another thing I noticed was the session variable $fb is null after the first call to invoke-webrequest.

    $r=Invoke-WebRequest www.ctslink.com -SessionVariable $fb
    
    $form = $r.Forms[0]
    
    
    $form.Fields["userId"] = "MyUsername"
    $form.Fields["passwd"] = "MyPassword"
    
    $r=Invoke-WebRequest 'https://ctslink.com/login.do' -WebSession $fb  -Body $form.Fields 
    

    Any help would be greatly appreciated, Mike