Home > database >  Outputting Invoke-WebRequest to a logfile with datetime (oneliner for task scheduler)
Outputting Invoke-WebRequest to a logfile with datetime (oneliner for task scheduler)

Time:01-06

I'm trying to run a process that needs to be reviewed in case of failure so I need to log the web content to a file but I'm fighting the Powershell syntax. The following line is what I attempted to write in the task scheduler as :

powershell.exe -noexit -Command "Invoke-WebRequest http://google.com -outfile C:\Users\user_gc$(get-date -Format 'yyyy-MM-dd HH:mm').txt"

Usually powershell or Invoke-WebREquest complains about the get-date command. "The given path format is not supported"

It's very important to me that the date and time are in the file.

CodePudding user response:

Script

Save below in script file TaskName.ps1 Make sure to change the variables to your needs

# Enter Your Path
$path = 'C:\Temp\'

# Enter Website You Want To Reach
$uri = 'https://google.com'

# For File Name
$timeStamp = (Get-Date).ToString('yyyy-MM-dd HHmm')

# Regex To Remove https://
$webSite = $uri -replace '^. ?(//)', '$`'

# Test If $path is Valid. If not, Create $path
switch (Test-Path $path) {
    'false' { mkdir -Path $path }
    Default { continue }
}

Invoke-WebRequest -Uri $uri |
    Out-File -FilePath "$path$webSite $timeStamp.txt" -Force

Task Scheduler

Action: Start a program

Settings:
Program/Script: Powershell.exe
Add arguments (optional):
-windowstyle hidden -executionpolicy bypass -File "C:\temp\TaskScheduler.ps1"
Note: This will require admin privileges

Results

File Name:
"C:\temp\google.com 2023-01-05 1341.txt"

CodePudding user response:

The : in the date format makes the path invalid (and the space may cause you problems down the line too). Try 'yyyy-MM-dd-HHmm' or some other "safe" format uses filesystem safe characters that suits you.

See Naming Conventions specifically:

Use any character in the current code page ... except for the following reserved characters:

  • < (less than)
  • > (greater than)
  • : (colon)
  • " (double quote)
  • / (forward slash)
  • \ (backslash)
  • | (vertical bar or pipe)
  • ? (question mark)
    • (asterisk)

You can trigger the same error by trying to create a file with a similar name and it will throw an error:

PS c:\temp> new-item -ItemType File -Path ".\2023-01-05 19:51.txt" -Value "is this file created?"
new-item : The given path's format is not supported.
At line:1 char:1
  new-item -ItemType File -Path ".\2023-01-05 19:51.txt" -Value "is thi ...
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : NotSpecified: (:) [New-Item], NotSupportedException
      FullyQualifiedErrorId : System.NotSupportedException,Microsoft.PowerShell.Commands.NewItemCommand
  • Related