diff --git a/foam_sync.ps1 b/foam_sync.ps1 index e502ce1..6ee4d96 100644 --- a/foam_sync.ps1 +++ b/foam_sync.ps1 @@ -52,8 +52,25 @@ $taskPrincipal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Int # Trigger configuration $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes $frequencyMinutes) -# Action configuration: run this script -$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$scriptPath`"" +# Action configuration: +# We use an indirection technique to ensure the window is truly hidden. +# The scheduled task launches an initial PowerShell. +# This initial PowerShell then uses Start-Process to launch the *actual* script in a new, hidden PowerShell process. + +# 1. Path to the script, with internal double quotes escaped as "" (for the -File parameter of the innermost PowerShell) +$scriptPathForInnermostFileParam = $scriptPath.Replace('"', '""') + +# 2. Argument string for the innermost PowerShell instance (the one executing the actual script) +$innermostPSArgs = "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \`"$scriptPathForInnermostFileParam\`"" + +# 3. The innermostPSArgs string needs its single quotes escaped (as '') because it will be wrapped in single quotes for Start-Process's -ArgumentList +$innermostPSArgsEscapedForStartProcess = $innermostPSArgs.Replace("'", "''") + +# 4. Command to be executed by the intermediate PowerShell (launched by Task Scheduler). This command uses Start-Process. +$commandForIntermediatePS = "Start-Process -FilePath powershell.exe -ArgumentList '$innermostPSArgsEscapedForStartProcess' -WindowStyle Hidden" +$taskActionArgument = "-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \`"$($commandForIntermediatePS.Replace('"', '`"'))\`"" # Escape " in command as `"` + +$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $taskActionArgument # Task settings $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 1) @@ -77,7 +94,7 @@ try { $actionMatches = $false if ($currentAction -is [Microsoft.Management.Infrastructure.CimInstance] ` -and $currentAction.Execute -eq "powershell.exe" ` - -and $currentAction.Argument -eq ("-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$scriptPath`"")) { + -and $currentAction.Argument -eq $taskActionArgument) { $actionMatches = $true }