Automatically run PowerShell scripts on Windows startup

Configure Windows Task Scheduler to automatically run a script on logon Link to heading

Create the script Link to heading

This is a sample PowerShell script for backing up files (Copy-BackupFiles.ps1).

function Copy-BackupFile {
    param(
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [ValidateNotNull()]
        [string]$Path,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string[]]$Destination,

        [string]$Filter = '*.*',

        [int]$RetryCount = 2,

        [int]$RetryWaitSeconds = 5,

        [switch]$PurgeDestinationFiles
    )

    foreach ($sourcePath in $Path) {
        if (Test-Path -Path $sourcePath -PathType Container) {
            $sourceFiles = Get-ChildItem -Path $sourcePath -File -Recurse

            if (($sourceFiles | Measure-Object).Count -gt 0) {
                foreach ($destPath in $Destination) {
                    if (Test-Path -Path (Split-Path -Path $destPath -Parent) -PathType Container) {
                        try {
                            Write-Verbose "$($sourcePath) --> $($destPath)"
                            if ($PurgeDestinationFiles) {
                                robocopy $sourcePath $destPath $Filter /PURGE /S /R:$RetryCount /W:$RetryWaitSeconds
                            }
                            else {
                                robocopy $sourcePath $destPath $Filter /S /R:$RetryCount /W:$RetryWaitSeconds
                            }
                        }
                        catch {
                            Write-Error ('Failed to copy files from "{0}" to "{1}". {2}' -f $sourcePath, $destPath, $PSItem)
                        }
                    }
                    else {
                        Write-Error ('Cannot find the parent directory of destination path "{0}".' -f $destPath)
                    }
                }
            }
            else {
                Write-Error ('No files in "{0}".' -f $Path)
            }
        }
        else {
            Write-Error ('Cannot find the source path "{0}".' -f $sourcePath)
        }
    }
}

$params = @{
    Path = "$env:USERPROFILE\Documents\MyFolder"
    DestinationPath = @(
        '\\NAS\home\Backup\MyFolder'
        "$env:USERPROFILE\OneDrive - FirstName LastName\Backup\MyFolder"
    )
    PurgeDestinationFiles = $true
}
Copy-BackupFile @params

Create the scheduled task Link to heading

Open Task Scheduler and create a new task. Configure the following settings.

  • General:
    • Name: Enter a name for the task
    • Run only when user is logged on: Yes
  • Triggers > New:
    • Begin the task: At log on
    • Delay task for: 1 minute
    • Enabled: Yes
  • Actions > New:
    • Action: Start a program
    • Program/script: pwsh.exe
    • Add arguments: -Window Minimized -File "C:\Users\Username\Documents\Scripts\Copy-BackupFiles.ps1"