Invoke-WebRequest question

We have a web based app that is able to show a user session log and I’m trying to automate this action using Invoke-WebRequest

While I can parse out several key peaces of key information needed to generate the uri, the Invoke-WebRequest does not initially return the content. I can take the same generated uri from the script and paste it into my web browser and it works. Once I do that manual step, the ps script will start to return the same content…

My guess is that it has something to do with my temporary internet files or something that is cached… Other actions within this web seem to work out just fine, only this piece has an issue…

How can I get this data to return from only the ps script?

Here is the simple logic, basically only the uri changes in my steps leading up to the final show log file step:

$UP='mypwd'|ConvertTo-SecureString -AsPlainText -Force
$UC=New-Object Management.Automation.PSCredential ($UN, $UP)

$WEBRESULT=(Invoke-WebRequest $URI-Credential $UC)

Once I do that manual step, the ps script will start to return the same content...

It sounds like you need a session cookie that persists between your requests. Try instantiating a web session first, then in subsequent requests, reference the session.

$session = new-object microsoft.powershell.commands.webrequestsession
$Request = Invoke-WebRequest -Uri $Uri -Credential $Creds -Session $Session

Also, don’t put plain text credentials in scripts. It’s bad practice and a security risk of course.
Always prompt for them for the user,

# This ...

$UN = 'username'
$UP = 'mypwd'|ConvertTo-SecureString -AsPlainText -Force
$UC = New-Object Management.Automation.PSCredential ($UN, $UP)

# Should be replaced with this ...

$SessionCreds = Get-Credential -Credential 'UserDomain\UserName'

# passing creds


# Retrieve the actual value, if needed


… or prompt for them and store them in the Windows Credential store, as a secure file or registry, then call from those resources as needed.

See these approaches:

Securely Store Credentials

Credential Manager

Thanks for the reply’s. Regarding the session object, it does not seem to help. I still get an invalid response from the invoke web request using the session ID. The process I have in place is meant to gather the web response for a specific application user session which is based on a previous / initial request to get the active user app session details which is gathered from a previous function call. The calls are similarly setup using invoke web request.

So process is like this:

  1. Get app user session details

  2. get app session log from input from step 1

also thanks for the security tip. I need to get a working product first then I was going to work on security.