Search code examples
powershellwindows-task-scheduler

Scheduled Task succesfully completes but doesn't get past import-csv


I'm trying to run below code in an automated scheduled task. Whether I run this task manually or automated it is not working. When the option 'Run only when user is logged in' is set I at least see a PowerShell window opening, and I do see the jobs getting started. However, when the PS window closes the jobs are not visible (not completed, failed, nothing).

The logging shows the script runs till the import-csv command. I have put the CSV in the C: map, and I run the automated task as the logged in user and on highest privilege.

Why doesn't it get past import-csv? When I run this script in i.e Powershell ISE it works like a charm.

Running program

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Arguments: –NoProfile -ExecutionPolicy Unrestricted -File "C:\Users\usr\Desktop\Scripts\script.ps1"

Start-in: C:\Users\usr\Desktop\Scripts

Write-Host "Starting script"

$maxItems = 8
$iplist = import-csv "C:\Create.csv.txt"
Write-Host "Opened $($iplist[0])"
For ($i=0; $i -le $maxItems; $i++) {
    Write-Host $iplist[$i].DisplayName
    Start-Job -ScriptBlock {
        Param($displayName)
        try{
                Start-Transcript
                Write-Host "Found and started a job for $($displayName)"
            Stop-Transcript
        }
        Catch{
            
            Write-Host "Something went wrong "
            Stop-Transcript
        }
    } -ArgumentList $iplist[$i].DisplayName
}

UPDATE:

The PS window closed before it got to do anything. The answer in this page send me in the right direction. The full fix I used to get this working: Task Scheduling and Powershell's Start-Job


Solution

  • First, to prevent the powershell window from closing, run add the following line to the bottom of the script:

    Read-Host 'Press Any Key to exit'
    

    Second, if you run into issues with params, try explicitly naming the param with a flag:

    $iplist = Import-csv -LiteralPath "C:\Create.csv.txt"
    

    Third, make sure that you explicitly declare the delimiter being used if different than a comma.