-1

I have following Powershell script file sumdigits.ps1 which outputs number to a log file every 10 seconds. The scripts work properly when executed manually. Execution Policy is set to RemoteSigned.

$logfile = "C:\Users/username/logger.log"

Function Log {
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$True)]
    [string]
    $Message
    )

    $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss.fff")
    $Line = "$Stamp $Message"
    Add-Content $logfile -Value $Line
}

$i=0

while($true)
{
    $i++
    Log “We have counted up to $i”
    Start-Sleep -s 10
}

I have added it to Startup folder and its showing in task manager as follows. So it seems its getting executed at startup.

enter image description here

However, when I see log file, nothing is getting written to that. Is the script not actually running or it got some error? How to find the error in latter case?

Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66
  • 1
    If it runs in your interactive context and not in Task Scheduler, then the task is not properly configured. [There are lots of articles and videos showing how to set up TS to run PS scripts](https://duckduckgo.com/?q=%27task+scheduler+to+run+powershell+script%27&t=h_&ia=web). – postanote Mar 21 '21 at 08:23
  • @postanote I only have powershell access to the machine. Can open any user interface. Any references for this use-case? – Shashwat Kumar Mar 21 '21 at 08:40
  • 1
    Did you set it up as `powershell.exe -executionpolicy bypass -file "scriptpath\script.ps1"` ? – Santiago Squarzon Mar 21 '21 at 15:21
  • 1
    As Santiago's comment hints at, `*.ps1` files by default aren't _executed_, they are _opened for editing_, by default in Notepad (see [this answer](https://stackoverflow.com/a/58245206/45375)). Either place a shortcut file with a `powershell.exe` command line in your Startup folder (unverified), or use an aux. _batch file_ to launch that PowerShell command line. – mklement0 Mar 21 '21 at 19:49

1 Answers1

0

The issue was that ps1 file was getting opened in notepad instead of getting executed. To resolve this, I created batch file to launch powershell script.

Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66