<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0"
     xmlns:atom="http://www.w3.org/2005/Atom"
     xmlns:content="http://purl.org/rss/1.0/modules/content/"
     xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Unattended · Loosely Decoupled</title>
    <link>https://looselydecoupled.com/topics/unattended/</link>
    <description>A script that runs with nobody watching, as a scheduled task or at boot, fails in ways your own session never shows, and reports success while it does.</description>
    <language>en-us</language>
    
    <copyright>© 2026 Emmanuel Tsouris</copyright>
    <lastBuildDate>Mon, 09 Nov 2026 00:00:00 +0000</lastBuildDate>
    <atom:link href="https://looselydecoupled.com/topics/unattended/index.xml" rel="self" type="application/rss+xml" />
    
    <item>
      <title>Scheduled Job vs. Scheduled Task in PowerShell 7</title>
      <link>https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/</guid>
      <pubDate>Mon, 09 Nov 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>PowerShell</category>
      <category>Unattended</category>
      
      <description>PowerShell 7 can register a scheduled task but not a scheduled job. The job cmdlets load only in Windows PowerShell, where a job saves each run&#39;s output.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>Use <code>Register-ScheduledTask</code> for a new script. Its module, <code>ScheduledTasks</code>, loads in Windows PowerShell 5.1 and in PowerShell 7. <code>Register-ScheduledJob</code> works only in Windows PowerShell 5.1. PowerShell 7 blocks its module, <code>PSScheduledJob</code>, from loading, so the cmdlet fails there. Choose <code>Register-ScheduledJob</code> only when the script stays in Windows PowerShell and you want <code>Receive-Job</code> to return each run&rsquo;s output. A scheduled task keeps no output, so a script run as a task writes its own log.</p>

</div>

<p>With PowerShell 7 and Windows PowerShell, there are often two commands that seem similar. <code>Register-ScheduledJob</code> and <code>Register-ScheduledTask</code> are one of those pairs. Both schedule a script, both show up in Task Scheduler, and in Windows PowerShell you can pick either.</p>
<p>Microsoft&rsquo;s pages say the scheduled job module no longer ships with PowerShell 7, and none of them says what happens when you call its cmdlets there. So I registered the same script both ways on Windows Server 2025, then tried each cmdlet in Windows PowerShell 5.1 and in PowerShell 7. Here&rsquo;s what happened, and which one to use.</p>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2025 Datacenter 24H2</dd></div>
    <div class="tested__row"><dt>Windows PowerShell</dt> <dd>5.1</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>7.6.10 and 7.7.0</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>November 2026</dd></div>
  </dl>
</div>
<h2 id="how-a-scheduled-job-differs-from-a-scheduled-task">How a scheduled job differs from a scheduled task<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#how-a-scheduled-job-differs-from-a-scheduled-task"
     aria-label="Link to section: How a scheduled job differs from a scheduled task" data-pagefind-ignore></a>
</h2>
<p>The two cmdlets differ in four ways that decide which one you pick: which PowerShell loads them, what you register, where the output goes and where you see it.</p>
<h3 id="module-and-powershell-version">Module and PowerShell version<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#module-and-powershell-version"
     aria-label="Link to section: Module and PowerShell version" data-pagefind-ignore></a>
</h3>
<p><code>Register-ScheduledJob</code> comes from the <code>PSScheduledJob</code> module. Its <a href="https://learn.microsoft.com/en-us/powershell/module/psscheduledjob/register-scheduledjob" rel="external noopener" target="_blank">reference page<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> says the module is &ldquo;included in Windows PowerShell&rdquo; and that the cmdlet &ldquo;was introduced in Windows PowerShell 3.0&rdquo;. Microsoft&rsquo;s <a href="https://learn.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell" rel="external noopener" target="_blank">differences between Windows PowerShell and PowerShell 7<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> page lists <code>PSScheduledJob</code> under &ldquo;Modules no longer shipped with PowerShell&rdquo;.</p>
<p>On my server the module is still on disk, in the Windows PowerShell module folder, marked for the <code>Desktop</code> edition only. Windows PowerShell 5.1 loads it. PowerShell 7.6 and 7.7 don&rsquo;t, and <code>Register-ScheduledJob</code> fails there. The exact errors are in <a href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#what-powershell-7-does-with-a-scheduled-job">What PowerShell 7 does with a scheduled job</a>.</p>
<p><code>Register-ScheduledTask</code> comes from the <code>ScheduledTasks</code> module. Its <a href="https://learn.microsoft.com/powershell/module/scheduledtasks/register-scheduledtask" rel="external noopener" target="_blank">reference page<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> says the cmdlet &ldquo;registers a scheduled task definition on a local computer&rdquo;. The module sits in the same folder, marked for both the <code>Desktop</code> and <code>Core</code> editions. Windows PowerShell 5.1 loads it, and so do PowerShell 7.6 and 7.7. PowerShell 7 loads it directly. It doesn&rsquo;t need the compatibility feature, which runs a module in a separate Windows PowerShell session.</p>
<h3 id="what-you-register">What you register<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#what-you-register"
     aria-label="Link to section: What you register" data-pagefind-ignore></a>
</h3>
<p>Microsoft defines a scheduled job as &ldquo;a Windows PowerShell background job that can be started automatically on a one-time or recurring schedule&rdquo;. You give <code>Register-ScheduledJob</code> a script block with <code>-ScriptBlock</code> or a <code>.ps1</code> file with <code>-FilePath</code>.</p>
<p>A scheduled task runs an action. The <code>Register-ScheduledTask</code> page says you can register a task to run &ldquo;executable files (<code>.exe</code> and <code>.com</code>), batch files (<code>.bat</code> and <code>.cmd</code>), or any registered file type&rdquo;. <code>New-ScheduledTaskAction</code> builds the action. To run a script, the action starts <code>powershell.exe</code> or <code>pwsh.exe</code>, and <code>-Argument</code> carries the script&rsquo;s path.</p>
<h3 id="where-the-output-goes">Where the output goes<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#where-the-output-goes"
     aria-label="Link to section: Where the output goes" data-pagefind-ignore></a>
</h3>
<p>A scheduled job saves each run on disk, in the profile of the account that registered the job:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs\&lt;JobName&gt;\Output\&lt;Timestamp&gt;</span></span></code></pre></div></div>
  </div>
</div><p>After one run, that folder holds <code>Results.xml</code> and <code>Status.xml</code>. In Windows PowerShell, <code>Get-Job</code> lists the run as a completed job of type <code>PSScheduledJob</code>. <code>Receive-Job</code> returns what the script wrote: in my run, an object with its properties, a string and a warning. Microsoft&rsquo;s <a href="https://learn.microsoft.com/en-us/powershell/module/psscheduledjob/about/about_scheduled_jobs" rel="external noopener" target="_blank">about_Scheduled_Jobs<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> page says &ldquo;the results of the job are saved on disk until you delete them or the maximum number of results are exceeded.&rdquo;</p>
<p>A scheduled task keeps none of that. After the task runs the same script, <code>Get-ScheduledTaskInfo</code> gives you the last run time, the last result code, the next run time and a count of missed runs. <code>Get-Job</code> doesn&rsquo;t list the task&rsquo;s run. To keep what the script prints, send it to a file yourself.</p>
<h3 id="where-you-see-it">Where you see it<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#where-you-see-it"
     aria-label="Link to section: Where you see it" data-pagefind-ignore></a>
</h3>
<p>Microsoft says scheduled jobs &ldquo;appear in Task Scheduler in the Task Scheduler <code>Library\Microsoft\Windows\PowerShell\ScheduledJobs</code> folder&rdquo;. My job appeared there. Its action starts <code>powershell.exe</code>, which imports <code>PSScheduledJob</code> and loads <code>ScheduledJobDefinition.xml</code> from the job&rsquo;s folder under <code>ScheduledJobs</code>, beside <code>Output</code>. A scheduled job is a scheduled task that Windows PowerShell wrote for you.</p>
<p>A scheduled task appears in Task Scheduler wherever you registered it. Mine had no <code>-TaskPath</code>, so it went in the root of the library.</p>
<h2 id="register-the-same-script-each-way">Register the same script each way<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#register-the-same-script-each-way"
     aria-label="Link to section: Register the same script each way" data-pagefind-ignore></a>
</h2>
<p>To see those differences rather than read about them, I registered one script both ways. I ran both of these in Windows PowerShell 5.1, as a local administrator. The script is <code>C:\Scripts\nightly.ps1</code>. Neither registration has a trigger, so each one runs only when you start it. To put either on a schedule, add <code>-Trigger</code> with a trigger from <code>New-JobTrigger</code> for the job or <code>New-ScheduledTaskTrigger</code> for the task.</p>
<p>Registering a scheduled job:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Register-ScheduledJob</span> <span class="n">-Name</span> <span class="n">Nightly</span> <span class="n">-FilePath</span> <span class="n">C:</span><span class="p">\</span><span class="n">Scripts</span><span class="p">\</span><span class="n">nightly</span><span class="p">.</span><span class="n">ps1</span></span></span></code></pre></div></div>
  </div>
</div><p>Starting it the way I did, through its Task Scheduler entry:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Start-ScheduledTask</span> <span class="n">-TaskName</span> <span class="n">Nightly</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-TaskPath</span> <span class="s1">&#39;\Microsoft\Windows\PowerShell\ScheduledJobs\&#39;</span></span></span></code></pre></div></div>
  </div>
</div><p><code>Start-Job -DefinitionName Nightly</code> runs it as an ordinary background job, and that run&rsquo;s output isn&rsquo;t saved with the job.</p>
<p>Reading its output after the run finishes:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Import-Module</span> <span class="n">PSScheduledJob</span>
</span></span><span class="line"><span class="cl"><span class="nb">Get-Job</span>
</span></span><span class="line"><span class="cl"><span class="nb">Receive-Job</span> <span class="n">-Name</span> <span class="n">Nightly</span> <span class="n">-Keep</span></span></span></code></pre></div></div>
  </div>
</div><p>Registering a scheduled task that runs the script as SYSTEM:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$action</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskAction</span> <span class="n">-Execute</span> <span class="s1">&#39;powershell.exe&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Argument</span> <span class="s1">&#39;-NoProfile -ExecutionPolicy Bypass -File C:\Scripts\nightly.ps1&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Register-ScheduledTask</span> <span class="n">-TaskName</span> <span class="nb">Nightly-Task</span> <span class="n">-Action</span> <span class="nv">$action</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-User</span> <span class="s1">&#39;NT AUTHORITY\SYSTEM&#39;</span> <span class="n">-RunLevel</span> <span class="n">Highest</span></span></span></code></pre></div></div>
  </div>
</div><p>Starting the task:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Start-ScheduledTask</span> <span class="n">-TaskName</span> <span class="nb">Nightly-Task</span></span></span></code></pre></div></div>
  </div>
</div><p>The same registration runs in PowerShell 7.6 and 7.7. There, set <code>-Execute</code> to <code>&quot;$PSHOME\pwsh.exe&quot;</code>, the <code>pwsh.exe</code> of the PowerShell you&rsquo;re in. My task finished with result 0.</p>
<h3 id="send-a-tasks-output-to-a-log-file">Send a task&rsquo;s output to a log file<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#send-a-tasks-output-to-a-log-file"
     aria-label="Link to section: Send a task’s output to a log file" data-pagefind-ignore></a>
</h3>
<p>A task hands you no output, so the fix is an action that sends every stream to a log file. I registered this one from PowerShell 7, under its own name so the first task stays as it was. The log&rsquo;s folder has to exist first:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">New-Item</span> <span class="n">-ItemType</span> <span class="n">Directory</span> <span class="n">-Force</span> <span class="n">C:</span><span class="p">\</span><span class="n">Logs</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl"><span class="nv">$command</span> <span class="p">=</span> <span class="s2">&#34;&amp; &#39;C:\Scripts\nightly.ps1&#39; *&gt; &#39;C:\Logs\nightly.log&#39;&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$action</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskAction</span> <span class="n">-Execute</span> <span class="s2">&#34;</span><span class="nv">$PSHOME</span><span class="s2">\pwsh.exe&#34;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Argument</span> <span class="s2">&#34;-NoProfile -ExecutionPolicy Bypass -Command </span><span class="se">`&#34;</span><span class="nv">$command</span><span class="se">`&#34;</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Register-ScheduledTask</span> <span class="n">-TaskName</span> <span class="nb">Nightly-Logged</span> <span class="n">-Action</span> <span class="nv">$action</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-User</span> <span class="s1">&#39;NT AUTHORITY\SYSTEM&#39;</span> <span class="n">-RunLevel</span> <span class="n">Highest</span></span></span></code></pre></div></div>
  </div>
</div><p>The log holds the object as a formatted table, then the string and the warning text. The object&rsquo;s <code>Edition</code> is <code>Core</code>. That&rsquo;s text, not the objects <code>Receive-Job</code> returns. Under <code>-Command</code>, a script that exits with a code other than 0 or 1 reports 1 to Task Scheduler. <a href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/">PowerShell -File vs. -Command: Which Exit Code Does the Caller Get?</a> has the cases.</p>
<h2 id="what-powershell-7-does-with-a-scheduled-job">What PowerShell 7 does with a scheduled job<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#what-powershell-7-does-with-a-scheduled-job"
     aria-label="Link to section: What PowerShell 7 does with a scheduled job" data-pagefind-ignore></a>
</h2>
<p>If you move a script to PowerShell 7 and reach for the job cmdlets, this is what you get. PowerShell 7.6.10 and 7.7.0 behave the same way.</p>
<h3 id="register-scheduledjob-fails-in-powershell-7"><code>Register-ScheduledJob</code> fails in PowerShell 7<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#register-scheduledjob-fails-in-powershell-7"
     aria-label="Link to section: Register-ScheduledJob fails in PowerShell 7" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">The</span> <span class="console__token">&#39;Register-ScheduledJob&#39;</span> <span class="console__token">command</span> <span class="console__token">was</span> <span class="console__token">found</span> <span class="console__token">in</span> <span class="console__token">the</span> <span class="console__token">module</span> <span class="console__token">&#39;PSScheduledJob&#39;,</span> <span class="console__token">but</span> <span class="console__token">the</span> <span class="console__token">module</span> <span class="console__token">could</span> <span class="console__token">not</span> <span class="console__token">be</span> <span class="console__token">loaded.</span> <span class="console__token">For</span> <span class="console__token">more</span> <span class="console__token">information,</span> <span class="console__token">run</span> <span class="console__token">&#39;Import-Module</span> <span class="console__token">PSScheduledJob&#39;.</span></span></code></pre>
    </div>
  </div></div><p>PowerShell 7 finds the module in the Windows PowerShell folder and refuses to load it. <code>Get-ScheduledJob</code> fails the same way. Nothing I tried in PowerShell 7 loaded it. Register the script as a scheduled task:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$action</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskAction</span> <span class="n">-Execute</span> <span class="s2">&#34;</span><span class="nv">$PSHOME</span><span class="s2">\pwsh.exe&#34;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Argument</span> <span class="s1">&#39;-NoProfile -ExecutionPolicy Bypass -File C:\Scripts\nightly.ps1&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Register-ScheduledTask</span> <span class="n">-TaskName</span> <span class="nb">Nightly-Pwsh</span> <span class="n">-Action</span> <span class="nv">$action</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-User</span> <span class="s1">&#39;NT AUTHORITY\SYSTEM&#39;</span> <span class="n">-RunLevel</span> <span class="n">Highest</span></span></span></code></pre></div></div>
  </div>
</div><h3 id="import-module-psscheduledjob-is-blocked"><code>Import-Module PSScheduledJob</code> is blocked<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#import-module-psscheduledjob-is-blocked"
     aria-label="Link to section: Import-Module PSScheduledJob is blocked" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Module</span> <span class="console__token">&#39;PSScheduledJob&#39;</span> <span class="console__token">is</span> <span class="console__token">blocked</span> <span class="console__token">from</span> <span class="console__token">loading</span> <span class="console__token">using</span> <span class="console__token">Windows</span> <span class="console__token">PowerShell</span> <span class="console__token">compatibility</span> <span class="console__token">feature</span> <span class="console__token">by</span> <span class="console__token">a</span> <span class="console__token">&#39;WindowsPowerShellCompatibilityModuleDenyList&#39;</span> <span class="console__token">setting</span> <span class="console__token">in</span> <span class="console__token">PowerShell</span> <span class="console__token">configuration</span> <span class="console__token">file.</span></span></code></pre>
    </div>
  </div></div><p>PowerShell 7 can load some Windows PowerShell modules through the compatibility feature. Microsoft&rsquo;s <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_windows_powershell_compatibility" rel="external noopener" target="_blank">Windows PowerShell compatibility<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> page puts <code>PSScheduledJob</code> on the default deny list for that feature. Adding <code>-UseWindowsPowerShell</code> gives the same error.</p>
<p>Never force the import with <code>-SkipEditionCheck</code>. The import appears to work, and then <code>Get-ScheduledJob</code> and every <code>Get-Job</code> in that session fail:</p>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Could</span> <span class="console__token">not</span> <span class="console__token">load</span> <span class="console__token">type</span> <span class="console__token">&#39;System.Runtime.Serialization.NetDataContractSerializer&#39;</span> <span class="console__token">from</span> <span class="console__token">assembly</span> <span class="console__token">&#39;System.Runtime.Serialization,</span> <span class="console__token">Version=4.0.0.0,</span> <span class="console__token">Culture=neutral,</span> <span class="console__token">PublicKeyToken=b77a5c561934e089&#39;.</span></span></code></pre>
    </div>
  </div></div><p>To register, change or list a scheduled job, open Windows PowerShell and run the cmdlets there.</p>
<h3 id="registered-jobs-keep-running-in-windows-powershell">Registered jobs keep running in Windows PowerShell<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#registered-jobs-keep-running-in-windows-powershell"
     aria-label="Link to section: Registered jobs keep running in Windows PowerShell" data-pagefind-ignore></a>
</h3>
<p>Having PowerShell 7 on the server doesn&rsquo;t stop a job you registered from Windows PowerShell. Its Task Scheduler entry starts <code>powershell.exe</code>, so when I started the job, the script still ran in Windows PowerShell 5.1 and saved its results as before.</p>
<p>PowerShell 7 can&rsquo;t read those results. In a new PowerShell 7 session, <code>Get-Job</code> returns nothing for a job that Windows PowerShell lists as completed. Open Windows PowerShell to read them:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Import-Module</span> <span class="n">PSScheduledJob</span>
</span></span><span class="line"><span class="cl"><span class="nb">Receive-Job</span> <span class="n">-Name</span> <span class="n">Nightly</span> <span class="n">-Keep</span></span></span></code></pre></div></div>
  </div>
</div><h2 id="choose-register-scheduledjob-for-results-you-read-in-windows-powershell">Choose <code>Register-ScheduledJob</code> for results you read in Windows PowerShell<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#choose-register-scheduledjob-for-results-you-read-in-windows-powershell"
     aria-label="Link to section: Choose Register-ScheduledJob for results you read in Windows PowerShell" data-pagefind-ignore></a>
</h2>
<p>Choose a scheduled job when the script stays on Windows PowerShell 5.1 and you want each run&rsquo;s output back as objects. <code>Get-Job</code> lists the runs, and <code>Receive-Job</code> returns what each one produced. You write no log file.</p>
<p>The cost is that the job is tied to Windows PowerShell. The script runs in 5.1 whatever else is installed, and you register, change and read the job from 5.1. To run the script in PowerShell 7, you register it again as a scheduled task and <a href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#send-a-tasks-output-to-a-log-file">add the logging yourself</a>.</p>
<h2 id="choose-register-scheduledtask-for-a-program-on-a-schedule">Choose <code>Register-ScheduledTask</code> for a program on a schedule<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#choose-register-scheduledtask-for-a-program-on-a-schedule"
     aria-label="Link to section: Choose Register-ScheduledTask for a program on a schedule" data-pagefind-ignore></a>
</h2>
<p>Choose a scheduled task when the action is a program, or when the script runs in PowerShell 7 now or may later. A task can start <code>powershell.exe</code>, <code>pwsh.exe</code> or any other executable. You register it with the same cmdlets from either PowerShell.</p>
<p>The cost is the output. Nothing hands you the run&rsquo;s results afterward, so you <a href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#send-a-tasks-output-to-a-log-file">redirect them to a log</a> or the script writes its own. Whether the task reports success is a separate question: <a href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/">Task Scheduler Falsely Reports Success for a PowerShell Script That Works Manually</a> covers the result code Task Scheduler records.</p>
<h2 id="what-i-didnt-test">What I didn&rsquo;t test<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#what-i-didnt-test"
     aria-label="Link to section: What I didn’t test" data-pagefind-ignore></a>
</h2>
<ul>
<li><strong>Editing the deny list.</strong> I didn&rsquo;t remove <code>PSScheduledJob</code> from <code>WindowsPowerShellCompatibilityModuleDenyList</code> in <code>powershell.config.json</code>. Microsoft put it there by default.</li>
<li><strong>PowerShell 7 from the MSI or the Store.</strong> I unpacked 7.6.10 and 7.7.0 from their release zips and left the configuration file alone.</li>
</ul>
<h2 id="sources">Sources<a class="heading-anchor" href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#sources"
     aria-label="Link to section: Sources" data-pagefind-ignore></a>
</h2>
<ul>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/psscheduledjob/register-scheduledjob" rel="external noopener" target="_blank">Register-ScheduledJob (Microsoft Learn)<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/psscheduledjob/about/about_scheduled_jobs" rel="external noopener" target="_blank">about_Scheduled_Jobs (Microsoft Learn)<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a></li>
<li><a href="https://learn.microsoft.com/powershell/module/scheduledtasks/register-scheduledtask" rel="external noopener" target="_blank">Register-ScheduledTask (Microsoft Learn)<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtaskaction" rel="external noopener" target="_blank">New-ScheduledTaskAction (Microsoft Learn)<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell" rel="external noopener" target="_blank">Differences between Windows PowerShell 5.1 and PowerShell 7 (Microsoft Learn)<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_windows_powershell_compatibility" rel="external noopener" target="_blank">about_Windows_PowerShell_Compatibility (Microsoft Learn)<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/register-scheduledjob-vs-register-scheduledtask/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a></li>
</ul>
]]></content:encoded>
    </item>
    
    <item>
      <title>PowerShell LTS vs. Stable: Which Release to Install</title>
      <link>https://looselydecoupled.com/powershell-lts-vs-stable/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/powershell-lts-vs-stable/</guid>
      <pubDate>Sun, 08 Nov 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>PowerShell</category>
      <category>Unattended</category>
      
      <description>LTS lets your scripts run for years on security fixes alone, while Stable trades that stability for new features and an upgrade every time a new LTS ships.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>Install the LTS release for any script that runs unattended. Pick the Stable release only if you need a feature your LTS release lacks and you can upgrade on time. Stable support ends about six months after the next LTS release. Microsoft&rsquo;s end-of-support table gives the date.</p>

</div>

<p>Microsoft sorts PowerShell 7 releases into two types, LTS and Stable. The difference decides what an update can change on a machine you don&rsquo;t watch, and how soon you have to move to a newer release. The definitions here come from Microsoft&rsquo;s <a href="https://learn.microsoft.com/powershell/scripting/install/powershell-support-lifecycle" rel="external noopener" target="_blank">PowerShell support lifecycle<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-lts-vs-stable/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> page.</p>
<h2 id="release-types">Release types<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lts-vs-stable/#release-types"
     aria-label="Link to section: Release types" data-pagefind-ignore></a>
</h2>
<p>An LTS release of PowerShell is an LTS release of .NET. Microsoft&rsquo;s page says &ldquo;a stable release is a release that occurs between LTS releases.&rdquo;</p>
<h2 id="find-out-which-type-you-have">Find out which type you have<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lts-vs-stable/#find-out-which-type-you-have"
     aria-label="Link to section: Find out which type you have" data-pagefind-ignore></a>
</h2>
<p>Microsoft&rsquo;s page gives one command that shows the version of .NET your PowerShell was built on. In the PowerShell 7 session you want to check, run:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="p">[</span><span class="no">System.Runtime.InteropServices.RuntimeInformation</span><span class="p">]::</span><span class="n">FrameworkDescription</span></span></span></code></pre></div></div>
  </div>
</div><p>Match the .NET version it prints against the .NET Version column of the two end-of-support tables on the lifecycle page, one for current versions and one for retired versions. A row marked LTS is an LTS release. A row marked preview is a preview release, which Microsoft doesn&rsquo;t officially support. A row with neither mark is a Stable release. The same row gives the date its support ends.</p>
<p>Windows PowerShell 5.1 is neither type. Microsoft&rsquo;s page says Windows PowerShell is a component of Windows and is subject to the Windows support lifecycle, so it has no row in these tables.</p>
<h2 id="what-an-update-contains">What an update contains<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lts-vs-stable/#what-an-update-contains"
     aria-label="Link to section: What an update contains" data-pagefind-ignore></a>
</h2>
<p>Updates to an LTS release contain only critical security updates and servicing fixes. Microsoft designs them to minimize the impact on existing workloads.</p>
<p>Stable releases can contain critical fixes, innovations and new features.</p>
<h2 id="how-long-support-lasts">How long support lasts<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lts-vs-stable/#how-long-support-lasts"
     aria-label="Link to section: How long support lasts" data-pagefind-ignore></a>
</h2>
<p>An LTS release follows the .NET support policy for the version of .NET it was built on.</p>
<p>Microsoft supports a Stable release for about six months after the next LTS release.</p>
<p>The dates change with every release. Read them in the end-of-support table on Microsoft&rsquo;s lifecycle page, not in a copy of it.</p>
<h2 id="what-you-must-do-to-stay-supported">What you must do to stay supported<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lts-vs-stable/#what-you-must-do-to-stay-supported"
     aria-label="Link to section: What you must do to stay supported" data-pagefind-ignore></a>
</h2>
<p>Apply updates to either type. Microsoft only supports the latest update of a release.</p>
<p>On LTS, that&rsquo;s all you must do until the end-of-support date in the table.</p>
<p>On Stable, you must also plan a move to a newer release, because support ends about six months after the next LTS release.</p>
<p>Before either type reaches its end-of-support date, move to the current LTS release that Microsoft&rsquo;s lifecycle page names. While the previous LTS release is still supported, the page names it too, with the date its support ends.</p>
<h2 id="choose-lts-for-scripts-that-run-unattended">Choose LTS for scripts that run unattended<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lts-vs-stable/#choose-lts-for-scripts-that-run-unattended"
     aria-label="Link to section: Choose LTS for scripts that run unattended" data-pagefind-ignore></a>
</h2>
<p>Choose LTS when a host should go untouched between updates. An update to an LTS release adds security updates and servicing fixes, not new features, so it changes as little as possible on a machine nobody watches. The catch is that a feature your release lacks doesn&rsquo;t arrive until you move to the next LTS release.</p>
<h2 id="choose-stable-when-you-need-a-new-feature">Choose Stable when you need a new feature<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lts-vs-stable/#choose-stable-when-you-need-a-new-feature"
     aria-label="Link to section: Choose Stable when you need a new feature" data-pagefind-ignore></a>
</h2>
<p>Choose Stable when you need a feature your LTS release doesn&rsquo;t have, and you can plan a move to a newer release. Stable support ends about six months after the next LTS release, so a host you rarely touch will outlive the support window.</p>
<p>Whichever type you pick, check what your caller sees after an upgrade. <a href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/">PowerShell -File vs. -Command: Which Exit Code Does the Caller Get?</a> covers what a scheduled task receives from your script.</p>
<h2 id="sources">Sources<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lts-vs-stable/#sources"
     aria-label="Link to section: Sources" data-pagefind-ignore></a>
</h2>
<ul>
<li><a href="https://learn.microsoft.com/powershell/scripting/install/powershell-support-lifecycle" rel="external noopener" target="_blank">PowerShell support lifecycle (Microsoft Learn)<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-lts-vs-stable/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a></li>
</ul>
]]></content:encoded>
    </item>
    
    <item>
      <title>Schedule an Azure VM to Start Daily and Deallocate Itself When Idle</title>
      <link>https://looselydecoupled.com/azure-vm-daily-maintenance-window/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/azure-vm-daily-maintenance-window/</guid>
      <pubDate>Mon, 02 Nov 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>Game servers</category>
      <category>Azure</category>
      <category>PowerShell</category>
      <category>Unattended</category>
      
      <description>Configure an Azure server VM to start itself daily, update Windows, and deallocate when idle, so it runs about an hour or two a day instead of 24/7.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>A <a href="https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-overview" rel="external noopener" target="_blank">Logic App<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> starts the Azure VM. Its Recurrence trigger POSTs to the VM&rsquo;s <code>start</code> endpoint as the Logic App&rsquo;s system-assigned identity.</p>
<p>The VM turns itself off. A scheduled task gets a token from the instance metadata service. Then it POSTs to the <code>deallocate</code> endpoint as the VM&rsquo;s own identity.</p>
<p>Both identities get one custom role with three actions: <code>virtualMachines/read</code>, <code>start/action</code> and <code>deallocate/action</code>. Assign it on that one VM.</p>
<p>Do not shut Windows down to turn the VM off. Azure leaves it Stopped, and a stopped VM still bills for compute. Only a deallocate stops the billing. The task deallocates only when the schedule started this boot. The game must also be stopped, or the server&rsquo;s <code>lp</code> command must report zero players. Any other answer leaves the VM on.</p>
<p>Give the trigger a <code>startTime</code> one minute in the past. Without one, the Logic App fires the moment you save it. Set it to the scheduled minute and it skips the first day. With <code>timeZone</code> set to <code>UTC</code>, the <code>startTime</code> must end in <code>Z</code>, or the service refuses it. On a subscription that has never had a Logic App, run <code>az provider register --namespace Microsoft.Logic --wait</code> first.</p>

</div>

<p>What do zombies and servers have in common? I play a game called <a href="https://store.steampowered.com/app/251570/7_Days_to_Die/" rel="external noopener" target="_blank">7 Days to Die<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>, and I&rsquo;ve run a private test server for it for years. It has lived in a few places. When I had recurring Azure credits, I moved it there. The problem was that I kept burning through all of them. I needed the server on when I wanted to play and when it needed updates, and off the rest of the time, so some credits were left for trying other Azure features.</p>
<p>On Halloween morning, my server&rsquo;s nightly update failed. SteamCMD printed <code>Error! App '294420' state is 0x606 after update job.</code> in my update script&rsquo;s log. The script did what I&rsquo;d built it to do: it left the game stopped rather than start it on a half-installed build. I didn&rsquo;t notice for two days. The game was dead the whole time, and the VM didn&rsquo;t know it. It kept running, and billing, until I found it and turned it off by hand.</p>
<p>That VM had no reason to be on most of the day. It ran around the clock so that a backup at 11:00 and an update at 11:30 could each take a few minutes. So I gave it a daily window instead: it starts itself, runs those tasks and the Windows updates, and turns itself off again when nobody is playing. A failed update can still happen, but now the VM goes off afterward instead of billing, and the next morning&rsquo;s boot starts the game again. Every piece is built here, so you don&rsquo;t need my module.</p>
<!-- style-check: procedure -->
<h2 id="1-confirm-the-prerequisites">1. Confirm the prerequisites<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#1-confirm-the-prerequisites"
     aria-label="Link to section: 1. Confirm the prerequisites" data-pagefind-ignore></a>
</h2>
<p>You need:</p>
<ul>
<li>An Azure VM running Windows with a 7 Days to Die server on it. I tested on Windows Server 2019.</li>
<li>The Azure CLI on your own machine, signed in as someone who can create role definitions and role assignments. Creating the role and its assignments takes Owner or User Access Administrator on the subscription. The other steps also change the VM and create a Logic App, which Owner covers.</li>
<li>Telnet enabled in the server&rsquo;s <code>serverconfig.xml</code> (<code>TelnetEnabled</code> set to <code>true</code>, with a <code>TelnetPort</code>). The player check in step 7 asks the server over telnet, and telnet is also how the script stops the server cleanly. <a href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/">Start a 7 Days to Die Dedicated Server at Boot on Windows and Stop It Cleanly</a> covers both.</li>
<li>A task that starts the server at boot, a daily backup task and a daily update task. The articles on <a href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/">backing up the server to S3</a> and on <a href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/">updating it only on a new build</a> build the last two. The script in step 11 waits for <code>7DaysToDieServerS3Backup</code> and <code>7DaysToDieServerAutoUpdate</code>, named in <code>$WaitFor</code>. If yours are named differently, change <code>$WaitFor</code> to match. A name that doesn&rsquo;t match is skipped, so the VM can deallocate under a running backup or update.</li>
</ul>
<h2 id="2-lay-out-the-window">2. Lay out the window<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#2-lay-out-the-window"
     aria-label="Link to section: 2. Lay out the window" data-pagefind-ignore></a>
</h2>
<p>Five things happen in the window, in this order. Each one starts only after the one before it has had time to finish.</p>
<div class="table-wrap" data-scrollable data-label="Table: UTC">
  <table>
    <thead>
      <tr><th scope="col">UTC</th><th scope="col">What runs</th></tr>
    </thead>
    <tbody>
      <tr><td>10:45</td><td>The Logic App starts the VM.</td></tr>
      <tr><td>After boot</td><td>The autostart task brings the game up.</td></tr>
      <tr><td>11:00</td><td>The backup task runs.</td></tr>
      <tr><td>11:30</td><td>The update task runs.</td></tr>
      <tr><td>12:00</td><td>The maintenance task installs Windows updates, then deallocates the VM.</td></tr>
    </tbody>
  </table>
</div>
<p>If you move one time, keep the same order. Keep the start before the backup by enough to cover the boot and the game&rsquo;s startup. Keep the maintenance task after the update task, so it never stops the game under an update. The maintenance task also waits for the backup and update tasks if they are still running, but it gives up after 60 minutes and leaves the VM on.</p>
<p>The window runs about an hour or two a day instead of 24, depending on the work. A game update to download or Windows updates to install make it longer.</p>
<p>When a log line ends &ldquo;VM left on&rdquo;, the VM stays on, and tomorrow&rsquo;s run doesn&rsquo;t turn it off either, because the schedule didn&rsquo;t start that boot. Read the log and deallocate it by hand.</p>
<h2 id="3-create-the-custom-role">3. Create the custom role<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#3-create-the-custom-role"
     aria-label="Link to section: 3. Create the custom role" data-pagefind-ignore></a>
</h2>
<p>The role lets an identity read a VM, start it and deallocate it, and nothing else. Virtual Machine Contributor would work, but it also lets an identity resize the VM, swap its disks and reset its password, which neither of these identities needs.</p>
<p>Steps 3 to 6 and 13 share variables. Run the commands meant for your own machine in one PowerShell session, starting with your subscription ID, which step 5 needs too:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$subscription</span> <span class="p">=</span> <span class="n">az</span> <span class="n">account</span> <span class="n">show</span> <span class="p">-</span><span class="n">-query</span> <span class="n">id</span> <span class="n">-o</span> <span class="n">tsv</span></span></span></code></pre></div></div>
  </div>
</div><p>Before you create the role, check whether it already exists with <code>az role definition list --name 'Game Server VM Power' --custom-role-only true</code>. If that returns the role, skip the create. Otherwise this makes the role definition in your subscription:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$definition</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">Name</span>             <span class="p">=</span> <span class="s1">&#39;Game Server VM Power&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="n">Description</span>      <span class="p">=</span> <span class="s1">&#39;Read, start and deallocate a virtual machine. Nothing else.&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="n">Actions</span>          <span class="p">=</span> <span class="vm">@</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="s1">&#39;Microsoft.Compute/virtualMachines/read&#39;</span>
</span></span><span class="line"><span class="cl">        <span class="s1">&#39;Microsoft.Compute/virtualMachines/start/action&#39;</span>
</span></span><span class="line"><span class="cl">        <span class="s1">&#39;Microsoft.Compute/virtualMachines/deallocate/action&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">AssignableScopes</span> <span class="p">=</span> <span class="vm">@</span><span class="p">(</span><span class="s2">&#34;/subscriptions/</span><span class="nv">$subscription</span><span class="s2">&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nv">$definition</span> <span class="p">|</span> <span class="nb">ConvertTo-Json</span> <span class="p">|</span> <span class="nb">Set-Content</span> <span class="n">role</span><span class="p">.</span><span class="py">json</span> <span class="n">-Encoding</span> <span class="n">ascii</span>
</span></span><span class="line"><span class="cl"><span class="n">az</span> <span class="n">role</span> <span class="n">definition</span> <span class="n">create</span> <span class="p">-</span><span class="n">-role-definition</span> <span class="s2">&#34;@role.json&#34;</span> <span class="n">-o</span> <span class="n">none</span></span></span></code></pre></div></div>
  </div>
</div><p>The role is assignable anywhere in the subscription, so one definition serves every VM you add later.</p>
<h2 id="4-enable-the-vms-identity-and-assign-the-role">4. Enable the VM&rsquo;s identity and assign the role<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#4-enable-the-vms-identity-and-assign-the-role"
     aria-label="Link to section: 4. Enable the VM’s identity and assign the role" data-pagefind-ignore></a>
</h2>
<p>Your VM needs a system-assigned managed identity: an Azure identity that belongs to the VM itself, with credentials Azure keeps for you. With it, the VM can ask Azure to deallocate it. This turns the identity on and grants it the role on that one VM:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$rg</span> <span class="p">=</span> <span class="s1">&#39;&lt;resource-group&gt;&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$vmName</span> <span class="p">=</span> <span class="s1">&#39;&lt;vm-name&gt;&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$vm</span> <span class="p">=</span> <span class="n">az</span> <span class="n">vm</span> <span class="n">show</span> <span class="n">-g</span> <span class="nv">$rg</span> <span class="n">-n</span> <span class="nv">$vmName</span> <span class="n">-o</span> <span class="n">json</span> <span class="p">|</span> <span class="nb">ConvertFrom-Json</span>
</span></span><span class="line"><span class="cl"><span class="nv">$vmPrincipal</span> <span class="p">=</span> <span class="p">(</span><span class="n">az</span> <span class="n">vm</span> <span class="n">identity</span> <span class="n">assign</span> <span class="n">-g</span> <span class="nv">$rg</span> <span class="n">-n</span> <span class="nv">$vmName</span> <span class="n">-o</span> <span class="n">json</span> <span class="p">|</span> <span class="nb">ConvertFrom-Json</span><span class="p">).</span><span class="py">systemAssignedIdentity</span>
</span></span><span class="line"><span class="cl"><span class="n">az</span> <span class="n">role</span> <span class="n">assignment</span> <span class="n">create</span> <span class="p">-</span><span class="n">-assignee-object-id</span> <span class="nv">$vmPrincipal</span> <span class="p">-</span><span class="n">-assignee-principal-type</span> <span class="n">ServicePrincipal</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="p">-</span><span class="n">-role</span> <span class="s1">&#39;Game Server VM Power&#39;</span> <span class="p">-</span><span class="n">-scope</span> <span class="nv">$vm</span><span class="p">.</span><span class="py">id</span> <span class="n">-o</span> <span class="n">none</span></span></span></code></pre></div></div>
  </div>
</div><p><code>--assignee-object-id</code> with <code>--assignee-principal-type</code> skips the directory lookup that <code>--assignee</code> does in Microsoft Graph. That lookup fails for a few minutes after you create an identity. See <a href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#cannot-find-user-or-service-principal-in-graph-database">Cannot find user or service principal in graph database</a>.</p>
<h2 id="5-create-the-logic-app-that-starts-the-vm">5. Create the Logic App that starts the VM<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#5-create-the-logic-app-that-starts-the-vm"
     aria-label="Link to section: 5. Create the Logic App that starts the VM" data-pagefind-ignore></a>
</h2>
<p>The start half is a Logic App, Azure&rsquo;s hosted workflow service, on the pay-per-run Consumption plan. It has a Recurrence trigger and one HTTP action. The action POSTs to the VM&rsquo;s <code>start</code> endpoint and authenticates as the Logic App&rsquo;s own system-assigned identity. Use a Logic App rather than Azure Automation, which needs a script (a runbook) that you keep up to date. A Logic App is only a timer and one web request.</p>
<p>Other clouds have their own timer for the start half. On AWS, an <a href="https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html" rel="external noopener" target="_blank">EventBridge Scheduler universal target<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> can call the EC2 <code>StartInstances</code> API directly. On Google Cloud, a Compute Engine <a href="https://docs.cloud.google.com/compute/docs/instances/schedule-instance-start-stop" rel="external noopener" target="_blank">instance schedule<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> starts and stops a VM at set times.</p>
<p>First check that your subscription is registered for the Logic App resource provider. If it has never had a Logic App, it isn&rsquo;t, and Azure refuses the create with <code>MissingSubscriptionRegistration</code>:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">az</span> <span class="n">provider</span> <span class="n">show</span> <span class="p">-</span><span class="n">-namespace</span> <span class="n">Microsoft</span><span class="p">.</span><span class="py">Logic</span> <span class="p">-</span><span class="n">-query</span> <span class="n">registrationState</span> <span class="n">-o</span> <span class="n">tsv</span></span></span></code></pre></div></div>
  </div>
</div><p>If that prints anything other than <code>Registered</code>, register it. This took under two minutes for me:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">az</span> <span class="n">provider</span> <span class="n">register</span> <span class="p">-</span><span class="n">-namespace</span> <span class="n">Microsoft</span><span class="p">.</span><span class="py">Logic</span> <span class="p">-</span><span class="n">-wait</span></span></span></code></pre></div></div>
  </div>
</div><p>This creates the Logic App and turns on its identity. It starts the VM at 10:45 UTC. Change <code>hours</code> and <code>minutes</code> for another time:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$appName</span> <span class="p">=</span> <span class="s2">&#34;</span><span class="nv">$vmName</span><span class="s2">-daily-start&#34;</span>
</span></span><span class="line"><span class="cl"><span class="c"># One minute in the past, with the Z. See Common failures for why each part matters.</span>
</span></span><span class="line"><span class="cl"><span class="nv">$first</span> <span class="p">=</span> <span class="p">[</span><span class="no">datetime</span><span class="p">]::</span><span class="n">UtcNow</span><span class="p">.</span><span class="py">AddMinutes</span><span class="p">(</span><span class="mf">-1</span><span class="p">).</span><span class="py">ToString</span><span class="p">(</span><span class="s2">&#34;yyyy-MM-dd&#39;T&#39;HH:mm:ss&#39;Z&#39;&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="nv">$uri</span> <span class="p">=</span> <span class="s2">&#34;https://management.azure.com/subscriptions/</span><span class="nv">$subscription</span><span class="s2">/resourceGroups/</span><span class="nv">$rg</span><span class="s2">/providers/Microsoft.Logic/workflows/</span><span class="p">$(</span><span class="nv">$appName</span><span class="p">)</span><span class="s2">?api-version=2019-05-01&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$workflow</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">location</span>   <span class="p">=</span> <span class="nv">$vm</span><span class="p">.</span><span class="py">location</span>
</span></span><span class="line"><span class="cl">    <span class="n">identity</span>   <span class="p">=</span> <span class="vm">@</span><span class="p">{</span> <span class="nb">type </span><span class="p">=</span> <span class="s1">&#39;SystemAssigned&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="n">properties</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">state</span>      <span class="p">=</span> <span class="s1">&#39;Enabled&#39;</span>
</span></span><span class="line"><span class="cl">        <span class="n">definition</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="s1">&#39;$schema&#39;</span>      <span class="p">=</span> <span class="s1">&#39;https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#&#39;</span>
</span></span><span class="line"><span class="cl">            <span class="n">contentVersion</span> <span class="p">=</span> <span class="s1">&#39;1.0.0.0&#39;</span>
</span></span><span class="line"><span class="cl">            <span class="n">triggers</span>       <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">Daily</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">                    <span class="nb">type </span>      <span class="p">=</span> <span class="s1">&#39;Recurrence&#39;</span>
</span></span><span class="line"><span class="cl">                    <span class="n">recurrence</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">                        <span class="n">frequency</span> <span class="p">=</span> <span class="s1">&#39;Day&#39;</span>
</span></span><span class="line"><span class="cl">                        <span class="n">interval</span>  <span class="p">=</span> <span class="mf">1</span>
</span></span><span class="line"><span class="cl">                        <span class="n">timeZone</span>  <span class="p">=</span> <span class="s1">&#39;UTC&#39;</span>
</span></span><span class="line"><span class="cl">                        <span class="n">startTime</span> <span class="p">=</span> <span class="nv">$first</span>
</span></span><span class="line"><span class="cl">                        <span class="n">schedule</span>  <span class="p">=</span> <span class="vm">@</span><span class="p">{</span> <span class="n">hours</span> <span class="p">=</span> <span class="vm">@</span><span class="p">(</span><span class="mf">10</span><span class="p">);</span> <span class="n">minutes</span> <span class="p">=</span> <span class="vm">@</span><span class="p">(</span><span class="mf">45</span><span class="p">)</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">                    <span class="p">}</span>
</span></span><span class="line"><span class="cl">                <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="n">actions</span>        <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">Start_VM</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">                    <span class="nb">type </span>  <span class="p">=</span> <span class="s1">&#39;Http&#39;</span>
</span></span><span class="line"><span class="cl">                    <span class="n">inputs</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">                        <span class="n">method</span>         <span class="p">=</span> <span class="s1">&#39;POST&#39;</span>
</span></span><span class="line"><span class="cl">                        <span class="n">uri</span>            <span class="p">=</span> <span class="s2">&#34;https://management.azure.com</span><span class="p">$(</span><span class="nv">$vm</span><span class="p">.</span><span class="n">id</span><span class="p">)</span><span class="s2">/start?api-version=2024-07-01&#34;</span>
</span></span><span class="line"><span class="cl">                        <span class="n">authentication</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{</span> <span class="nb">type </span><span class="p">=</span> <span class="s1">&#39;ManagedServiceIdentity&#39;</span><span class="p">;</span> <span class="n">audience</span> <span class="p">=</span> <span class="s1">&#39;https://management.azure.com/&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">                    <span class="p">}</span>
</span></span><span class="line"><span class="cl">                <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nv">$workflow</span> <span class="p">|</span> <span class="nb">ConvertTo-Json</span> <span class="n">-Depth</span> <span class="mf">20</span> <span class="p">|</span> <span class="nb">Set-Content</span> <span class="n">workflow</span><span class="p">.</span><span class="py">json</span> <span class="n">-Encoding</span> <span class="n">ascii</span>
</span></span><span class="line"><span class="cl"><span class="nv">$app</span> <span class="p">=</span> <span class="n">az</span> <span class="n">rest</span> <span class="p">-</span><span class="n">-method</span> <span class="n">put</span> <span class="p">-</span><span class="n">-uri</span> <span class="nv">$uri</span> <span class="p">-</span><span class="n">-body</span> <span class="s2">&#34;@workflow.json&#34;</span> <span class="n">-o</span> <span class="n">json</span> <span class="p">|</span> <span class="nb">ConvertFrom-Json</span></span></span></code></pre></div></div>
  </div>
</div><p>Because <code>startTime</code> is in the past, nothing runs when you save it. Without a <code>startTime</code>, it runs at once and fails with <code>Forbidden</code>, because its identity holds no role until the next step.</p>
<h2 id="6-assign-the-role-to-the-logic-apps-identity">6. Assign the role to the Logic App&rsquo;s identity<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#6-assign-the-role-to-the-logic-apps-identity"
     aria-label="Link to section: 6. Assign the role to the Logic App’s identity" data-pagefind-ignore></a>
</h2>
<p>The Logic App can&rsquo;t start the VM until its own identity holds the role. List the assignments on the VM by scope and role and filter on <code>principalId</code>. That form works on an identity that is seconds old; <code>--assignee</code> doesn&rsquo;t.</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$appPrincipal</span> <span class="p">=</span> <span class="nv">$app</span><span class="p">.</span><span class="py">identity</span><span class="p">.</span><span class="py">principalId</span>
</span></span><span class="line"><span class="cl"><span class="nv">$held</span> <span class="p">=</span> <span class="n">az</span> <span class="n">role</span> <span class="n">assignment</span> <span class="n">list</span> <span class="p">-</span><span class="n">-scope</span> <span class="nv">$vm</span><span class="p">.</span><span class="py">id</span> <span class="p">-</span><span class="n">-role</span> <span class="s1">&#39;Game Server VM Power&#39;</span> <span class="n">-o</span> <span class="n">json</span> <span class="p">|</span> <span class="nb">ConvertFrom-Json</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Where-Object</span> <span class="p">{</span> <span class="nv">$_</span><span class="p">.</span><span class="py">principalId</span> <span class="o">-eq</span> <span class="nv">$appPrincipal</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$held</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">az</span> <span class="n">role</span> <span class="n">assignment</span> <span class="n">create</span> <span class="p">-</span><span class="n">-assignee-object-id</span> <span class="nv">$appPrincipal</span> <span class="p">-</span><span class="n">-assignee-principal-type</span> <span class="n">ServicePrincipal</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">        <span class="p">-</span><span class="n">-role</span> <span class="s1">&#39;Game Server VM Power&#39;</span> <span class="p">-</span><span class="n">-scope</span> <span class="nv">$vm</span><span class="p">.</span><span class="py">id</span> <span class="n">-o</span> <span class="n">none</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><h2 id="7-check-the-player-count-over-telnet">7. Check the player count over telnet<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#7-check-the-player-count-over-telnet"
     aria-label="Link to section: 7. Check the player count over telnet" data-pagefind-ignore></a>
</h2>
<p>From here you work on the VM. Steps 7 to 11 build one script, <code>maintenance.ps1</code>, which runs there in Windows PowerShell 5.1. Step 11 gives the order you assemble it in.</p>
<p>While the game is running, the decision to turn the machine off rests on what the server reports, not on the time of day. The server&rsquo;s <code>lp</code> command lists connected players and ends with a line such as <code>Total of 1 in the game</code>. The function returns that number. For anything else it returns <code>$null</code>: telnet off, no connection, a wrong password, or no <code>Total of</code> line. Your script treats <code>$null</code> as &ldquo;someone might be on&rdquo;.</p>
<p>The function takes the last <code>Total of</code> line in the reply, because the console can echo an earlier listing that was still in its buffer. It connects to <code>127.0.0.1</code> and sends <code>exit</code>, which closes only the telnet session. It never sends <code>shutdown</code>.</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">ConvertFrom-PlayerListing</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">([</span><span class="n">AllowEmptyString</span><span class="p">()][</span><span class="no">string</span><span class="p">]</span><span class="nv">$Text</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$Text</span> <span class="o">-or</span> <span class="nv">$Text</span> <span class="o">-match</span> <span class="s1">&#39;Password incorrect&#39;</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="vm">$null</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$found</span> <span class="p">=</span> <span class="p">[</span><span class="no">regex</span><span class="p">]::</span><span class="n">Matches</span><span class="p">(</span><span class="nv">$Text</span><span class="p">,</span> <span class="s1">&#39;Total of (\d+) in the game&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$found</span><span class="p">.</span><span class="py">Count</span> <span class="o">-eq</span> <span class="mf">0</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="vm">$null</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$found</span><span class="p">[</span><span class="nv">$found</span><span class="p">.</span><span class="py">Count</span> <span class="p">-</span> <span class="mf">1</span><span class="p">].</span><span class="n">Groups</span><span class="p">[</span><span class="mf">1</span><span class="p">].</span><span class="py">Value</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Get-ServerPlayerCount</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$Port</span> <span class="p">=</span> <span class="mf">8081</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$Password</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$TimeoutSeconds</span> <span class="p">=</span> <span class="mf">15</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$client</span> <span class="p">=</span> <span class="p">[</span><span class="no">Net.Sockets.TcpClient</span><span class="p">]::</span><span class="n">new</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$client</span><span class="p">.</span><span class="py">ConnectAsync</span><span class="p">(</span><span class="s1">&#39;127.0.0.1&#39;</span><span class="p">,</span> <span class="nv">$Port</span><span class="p">).</span><span class="py">Wait</span><span class="p">(</span><span class="nv">$TimeoutSeconds</span> <span class="p">*</span> <span class="mf">1000</span><span class="p">))</span> <span class="p">{</span> <span class="k">return</span> <span class="vm">$null</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$stream</span> <span class="p">=</span> <span class="nv">$client</span><span class="p">.</span><span class="py">GetStream</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$writer</span> <span class="p">=</span> <span class="p">[</span><span class="no">IO.StreamWriter</span><span class="p">]::</span><span class="n">new</span><span class="p">(</span><span class="nv">$stream</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$writer</span><span class="p">.</span><span class="py">AutoFlush</span> <span class="p">=</span> <span class="vm">$true</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="nb">Start-Sleep</span> <span class="n">-Milliseconds</span> <span class="mf">500</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="nv">$Password</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$writer</span><span class="p">.</span><span class="py">WriteLine</span><span class="p">(</span><span class="nv">$Password</span><span class="p">);</span> <span class="nb">Start-Sleep</span> <span class="n">-Milliseconds</span> <span class="mf">500</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$writer</span><span class="p">.</span><span class="py">WriteLine</span><span class="p">(</span><span class="s1">&#39;lp&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="nv">$buffer</span>   <span class="p">=</span> <span class="nb">New-Object</span> <span class="n">byte</span><span class="p">[]</span> <span class="mf">4096</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$text</span>     <span class="p">=</span> <span class="s1">&#39;&#39;</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$count</span>    <span class="p">=</span> <span class="vm">$null</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$deadline</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Get-Date</span><span class="p">).</span><span class="py">AddSeconds</span><span class="p">(</span><span class="nv">$TimeoutSeconds</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">while</span> <span class="p">((</span><span class="nb">Get-Date</span><span class="p">)</span> <span class="o">-lt</span> <span class="nv">$deadline</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">while</span> <span class="p">(</span><span class="nv">$stream</span><span class="p">.</span><span class="n">DataAvailable</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">                <span class="nv">$read</span>  <span class="p">=</span> <span class="nv">$stream</span><span class="p">.</span><span class="py">Read</span><span class="p">(</span><span class="nv">$buffer</span><span class="p">,</span> <span class="mf">0</span><span class="p">,</span> <span class="nv">$buffer</span><span class="p">.</span><span class="n">Length</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">                <span class="nv">$text</span> <span class="p">+=</span> <span class="p">[</span><span class="no">Text.Encoding</span><span class="p">]::</span><span class="n">UTF8</span><span class="p">.</span><span class="py">GetString</span><span class="p">(</span><span class="nv">$buffer</span><span class="p">,</span> <span class="mf">0</span><span class="p">,</span> <span class="nv">$read</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="k">if</span> <span class="p">(</span><span class="nv">$text</span> <span class="o">-match</span> <span class="s1">&#39;Password incorrect&#39;</span><span class="p">)</span> <span class="p">{</span> <span class="k">break</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$count</span> <span class="p">=</span> <span class="nb">ConvertFrom-PlayerListing</span> <span class="n">-Text</span> <span class="nv">$text</span>
</span></span><span class="line"><span class="cl">            <span class="k">if</span> <span class="p">(</span><span class="vm">$null</span> <span class="o">-ne</span> <span class="nv">$count</span><span class="p">)</span> <span class="p">{</span> <span class="k">break</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="nb">Start-Sleep</span> <span class="n">-Milliseconds</span> <span class="mf">250</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="k">try</span> <span class="p">{</span> <span class="nv">$writer</span><span class="p">.</span><span class="py">WriteLine</span><span class="p">(</span><span class="s1">&#39;exit&#39;</span><span class="p">)</span> <span class="p">}</span> <span class="k">catch</span> <span class="p">{</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$count</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="vm">$null</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span> <span class="k">finally</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$client</span><span class="p">.</span><span class="py">Dispose</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>On my server with nobody connected, my module&rsquo;s version of this function returned <code>0</code>.</p>
<h2 id="8-test-whether-the-schedule-started-this-boot">8. Test whether the schedule started this boot<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#8-test-whether-the-schedule-started-this-boot"
     aria-label="Link to section: 8. Test whether the schedule started this boot" data-pagefind-ignore></a>
</h2>
<p>The task turns the VM off only when the schedule started this boot. A VM you start by hand to play stays on. The test checks whether the boot falls in a window that opens at the scheduled start time. The script in step 11 sets that window to 30 minutes.</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Test-ScheduledBoot</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="nb">Parameter</span><span class="p">(</span><span class="na">Mandatory</span><span class="p">)][</span><span class="no">datetime</span><span class="p">]</span><span class="nv">$BootTimeUtc</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="nb">Parameter</span><span class="p">(</span><span class="na">Mandatory</span><span class="p">)][</span><span class="no">string</span><span class="p">]</span><span class="nv">$StartAtUtc</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="nb">Parameter</span><span class="p">(</span><span class="na">Mandatory</span><span class="p">)][</span><span class="no">int</span><span class="p">]</span><span class="nv">$WindowMinutes</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$time</span>  <span class="p">=</span> <span class="p">[</span><span class="no">datetime</span><span class="p">]::</span><span class="n">ParseExact</span><span class="p">(</span><span class="nv">$StartAtUtc</span><span class="p">,</span> <span class="s1">&#39;HH:mm&#39;</span><span class="p">,</span> <span class="p">[</span><span class="no">Globalization.CultureInfo</span><span class="p">]::</span><span class="n">InvariantCulture</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$start</span> <span class="p">=</span> <span class="nv">$BootTimeUtc</span><span class="p">.</span><span class="py">Date</span><span class="p">.</span><span class="py">Add</span><span class="p">(</span><span class="nv">$time</span><span class="p">.</span><span class="n">TimeOfDay</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$BootTimeUtc</span> <span class="o">-ge</span> <span class="nv">$start</span> <span class="o">-and</span> <span class="nv">$BootTimeUtc</span> <span class="o">-lt</span> <span class="nv">$start</span><span class="p">.</span><span class="py">AddMinutes</span><span class="p">(</span><span class="nv">$WindowMinutes</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>With a start of <code>10:45</code> and a window of 30, a boot at 10:47 counts as scheduled. Boots at 10:44, 11:15 and 19:30 don&rsquo;t. A boot you start by hand at 11:00 counts as scheduled, because the function sees only the time. Keep your own play sessions outside that window.</p>
<h2 id="9-search-for-and-install-windows-updates">9. Search for and install Windows updates<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#9-search-for-and-install-windows-updates"
     aria-label="Link to section: 9. Search for and install Windows updates" data-pagefind-ignore></a>
</h2>
<p>A VM that is deallocated most of the day never reaches the operating system&rsquo;s own update schedule, so the window installs them itself. PowerShell can call the Windows Update Agent, the update component built into Windows, directly. The task runs as SYSTEM, and you install no extra module.</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Test-PendingReboot</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$keys</span> <span class="p">=</span> <span class="vm">@</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="s1">&#39;HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired&#39;</span>
</span></span><span class="line"><span class="cl">        <span class="s1">&#39;HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">foreach</span> <span class="p">(</span><span class="nv">$key</span> <span class="k">in</span> <span class="nv">$keys</span><span class="p">)</span> <span class="p">{</span> <span class="k">if</span> <span class="p">(</span><span class="nb">Test-Path</span> <span class="nv">$key</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="vm">$true</span> <span class="p">}</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="vm">$false</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Install-PendingWindowsUpdate</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">([</span><span class="no">switch</span><span class="p">]</span><span class="nv">$SearchOnly</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$session</span> <span class="p">=</span> <span class="nb">New-Object</span> <span class="n">-ComObject</span> <span class="n">Microsoft</span><span class="p">.</span><span class="py">Update</span><span class="p">.</span><span class="py">Session</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$search</span>  <span class="p">=</span> <span class="nv">$session</span><span class="p">.</span><span class="py">CreateUpdateSearcher</span><span class="p">().</span><span class="py">Search</span><span class="p">(</span><span class="s2">&#34;IsInstalled=0 and IsHidden=0 and Type=&#39;Software&#39;&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$titles</span> <span class="p">=</span> <span class="vm">@</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="p">(</span><span class="nv">$i</span> <span class="p">=</span> <span class="mf">0</span><span class="p">;</span> <span class="nv">$i</span> <span class="o">-lt</span> <span class="nv">$search</span><span class="p">.</span><span class="py">Updates</span><span class="p">.</span><span class="n">Count</span><span class="p">;</span> <span class="nv">$i</span><span class="p">++)</span> <span class="p">{</span> <span class="nv">$titles</span> <span class="p">+=</span> <span class="nv">$search</span><span class="p">.</span><span class="py">Updates</span><span class="p">.</span><span class="py">Item</span><span class="p">(</span><span class="nv">$i</span><span class="p">).</span><span class="py">Title</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$result</span> <span class="p">=</span> <span class="p">[</span><span class="no">pscustomobject</span><span class="p">]</span><span class="vm">@</span><span class="p">{</span> <span class="n">Found</span> <span class="p">=</span> <span class="nv">$titles</span><span class="p">;</span> <span class="n">Installed</span> <span class="p">=</span> <span class="vm">@</span><span class="p">();</span> <span class="n">Failed</span> <span class="p">=</span> <span class="vm">@</span><span class="p">();</span> <span class="n">RebootRequired</span> <span class="p">=</span> <span class="vm">$false</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$titles</span><span class="p">.</span><span class="py">Count</span> <span class="o">-eq</span> <span class="mf">0</span> <span class="o">-or</span> <span class="nv">$SearchOnly</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$result</span><span class="p">.</span><span class="py">RebootRequired</span> <span class="p">=</span> <span class="nb">Test-PendingReboot</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="nv">$result</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c"># Untested from here to the end of the function: no update was offered.</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$collection</span> <span class="p">=</span> <span class="nb">New-Object</span> <span class="n">-ComObject</span> <span class="n">Microsoft</span><span class="p">.</span><span class="py">Update</span><span class="p">.</span><span class="py">UpdateColl</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="p">(</span><span class="nv">$i</span> <span class="p">=</span> <span class="mf">0</span><span class="p">;</span> <span class="nv">$i</span> <span class="o">-lt</span> <span class="nv">$search</span><span class="p">.</span><span class="py">Updates</span><span class="p">.</span><span class="n">Count</span><span class="p">;</span> <span class="nv">$i</span><span class="p">++)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$update</span> <span class="p">=</span> <span class="nv">$search</span><span class="p">.</span><span class="py">Updates</span><span class="p">.</span><span class="py">Item</span><span class="p">(</span><span class="nv">$i</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$update</span><span class="p">.</span><span class="n">EulaAccepted</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$update</span><span class="p">.</span><span class="py">AcceptEula</span><span class="p">()</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">void</span><span class="p">]</span><span class="nv">$collection</span><span class="p">.</span><span class="py">Add</span><span class="p">(</span><span class="nv">$update</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$downloader</span> <span class="p">=</span> <span class="nv">$session</span><span class="p">.</span><span class="py">CreateUpdateDownloader</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$downloader</span><span class="p">.</span><span class="py">Updates</span> <span class="p">=</span> <span class="nv">$collection</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">void</span><span class="p">]</span><span class="nv">$downloader</span><span class="p">.</span><span class="py">Download</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$installer</span> <span class="p">=</span> <span class="nv">$session</span><span class="p">.</span><span class="py">CreateUpdateInstaller</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$installer</span><span class="p">.</span><span class="py">Updates</span> <span class="p">=</span> <span class="nv">$collection</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$outcome</span> <span class="p">=</span> <span class="nv">$installer</span><span class="p">.</span><span class="py">Install</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c"># ResultCode 2 is succeeded and 3 is succeeded with errors; 3 counts as installed.</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="p">(</span><span class="nv">$i</span> <span class="p">=</span> <span class="mf">0</span><span class="p">;</span> <span class="nv">$i</span> <span class="o">-lt</span> <span class="nv">$collection</span><span class="p">.</span><span class="n">Count</span><span class="p">;</span> <span class="nv">$i</span><span class="p">++)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$code</span> <span class="p">=</span> <span class="nv">$outcome</span><span class="p">.</span><span class="py">GetUpdateResult</span><span class="p">(</span><span class="nv">$i</span><span class="p">).</span><span class="py">ResultCode</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="nv">$code</span> <span class="n">-in</span> <span class="mf">2</span><span class="p">,</span> <span class="mf">3</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$result</span><span class="p">.</span><span class="py">Installed</span> <span class="p">+=</span> <span class="nv">$collection</span><span class="p">.</span><span class="py">Item</span><span class="p">(</span><span class="nv">$i</span><span class="p">).</span><span class="py">Title</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="k">else</span> <span class="p">{</span> <span class="nv">$result</span><span class="p">.</span><span class="py">Failed</span> <span class="p">+=</span> <span class="s2">&#34;</span><span class="p">$(</span><span class="nv">$collection</span><span class="p">.</span><span class="py">Item</span><span class="p">(</span><span class="nv">$i</span><span class="p">).</span><span class="n">Title</span><span class="p">)</span><span class="s2"> (result </span><span class="nv">$code</span><span class="s2">)&#34;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$result</span><span class="p">.</span><span class="py">RebootRequired</span> <span class="p">=</span> <span class="nv">$outcome</span><span class="p">.</span><span class="py">RebootRequired</span> <span class="o">-or</span> <span class="p">(</span><span class="nb">Test-PendingReboot</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$result</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>The function never restarts the machine.</p>
<h2 id="10-deallocate-the-vm-from-inside">10. Deallocate the VM from inside<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#10-deallocate-the-vm-from-inside"
     aria-label="Link to section: 10. Deallocate the VM from inside" data-pagefind-ignore></a>
</h2>
<p>Shutting Windows down from inside leaves an Azure VM in the Stopped state, which still bills for compute. Only Azure can deallocate it, releasing its hardware so compute billing stops. So the VM asks Azure, using its managed identity. The first two calls go to the instance metadata service at <code>169.254.169.254</code>, a local endpoint that tells a VM about itself and answers only from inside it. The last goes to Azure itself:</p>
<ol>
<li>Read the VM&rsquo;s resource ID from the compute metadata.</li>
<li>Get a token for <code>management.azure.com</code>.</li>
<li>POST to the resource&rsquo;s <code>deallocate</code> endpoint with that token.</li>
</ol>
<p>Windows PowerShell 5.1 sends a POST with no body and no <code>Content-Length</code> header, so the deallocate call always sends a body, even an empty <code>{}</code>.</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Get-AzureResourceId</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="p">(</span><span class="nb">Invoke-RestMethod</span> <span class="n">-Headers</span> <span class="vm">@</span><span class="p">{</span> <span class="n">Metadata</span> <span class="p">=</span> <span class="s1">&#39;true&#39;</span> <span class="p">}</span> <span class="n">-TimeoutSec</span> <span class="mf">5</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">            <span class="n">-Uri</span> <span class="s1">&#39;http://169.254.169.254/metadata/instance/compute?api-version=2021-02-01&#39;</span><span class="p">).</span><span class="py">resourceId</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="vm">$null</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Invoke-AzureSelfDeallocate</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">([</span><span class="nb">Parameter</span><span class="p">(</span><span class="na">Mandatory</span><span class="p">)][</span><span class="no">string</span><span class="p">]</span><span class="nv">$ResourceId</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">Net.ServicePointManager</span><span class="p">]::</span><span class="n">SecurityProtocol</span> <span class="p">=</span> <span class="p">[</span><span class="no">Net.ServicePointManager</span><span class="p">]::</span><span class="n">SecurityProtocol</span> <span class="o">-bor</span> <span class="p">[</span><span class="no">Net.SecurityProtocolType</span><span class="p">]::</span><span class="n">Tls12</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$token</span> <span class="p">=</span> <span class="nb">Invoke-RestMethod</span> <span class="n">-Headers</span> <span class="vm">@</span><span class="p">{</span> <span class="n">Metadata</span> <span class="p">=</span> <span class="s1">&#39;true&#39;</span> <span class="p">}</span> <span class="n">-TimeoutSec</span> <span class="mf">10</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">        <span class="n">-Uri</span> <span class="s1">&#39;http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&amp;resource=https%3A%2F%2Fmanagement.azure.com%2F&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$response</span> <span class="p">=</span> <span class="nb">Invoke-WebRequest</span> <span class="n">-UseBasicParsing</span> <span class="n">-Method</span> <span class="n">Post</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">        <span class="n">-Uri</span> <span class="s2">&#34;https://management.azure.com</span><span class="nv">$ResourceId</span><span class="s2">/deallocate?api-version=2024-07-01&#34;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">        <span class="n">-Headers</span> <span class="vm">@</span><span class="p">{</span> <span class="n">Authorization</span> <span class="p">=</span> <span class="s2">&#34;Bearer </span><span class="p">$(</span><span class="nv">$token</span><span class="p">.</span><span class="n">access_token</span><span class="p">)</span><span class="s2">&#34;</span> <span class="p">}</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">        <span class="n">-ContentType</span> <span class="s1">&#39;application/json&#39;</span> <span class="n">-Body</span> <span class="s1">&#39;{}&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$response</span><span class="p">.</span><span class="py">StatusCode</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>Azure answers <code>202</code> when it accepts the request. Azure shuts the operating system down a few seconds later, so write anything you still need before you call it.</p>
<h2 id="11-chain-the-checks-in-one-script">11. Chain the checks in one script<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#11-chain-the-checks-in-one-script"
     aria-label="Link to section: 11. Chain the checks in one script" data-pagefind-ignore></a>
</h2>
<p>The order of the file is what makes the pieces safe. Build one file, saved as <code>C:\7DaysToDieServer\maintenance.ps1</code> or wherever your tasks live, in this order:</p>
<ol>
<li>The <code>param([switch]$DryRun)</code> line from the top of the script below. It must be the first line of the file: PowerShell reads <code>param</code> as the script&rsquo;s parameters only when nothing but comments comes before it. Anywhere else, PowerShell ignores <code>-DryRun</code> and your rehearsal runs for real.</li>
<li>The functions from steps 7 to 10.</li>
<li>The <code>Stop-GameServer</code> function from step 4 of <a href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/">Start a 7 Days to Die Dedicated Server at Boot on Windows and Stop It Cleanly</a>. The task starts a fresh <code>powershell.exe</code> as SYSTEM, so a function defined only in your own session isn&rsquo;t there when the task runs.</li>
<li>The rest of the script below, starting at <code>$ErrorActionPreference</code>.</li>
</ol>
<p>Set the values at the top of the script to match your server and your tasks. When it runs, the script does this, in order:</p>
<ul>
<li>Exit if the machine booted under 15 minutes ago. That is the startup trigger&rsquo;s run in step 12.</li>
<li>Wait for the backup and update tasks.</li>
<li>Check the players.</li>
<li>Search for and install Windows updates.</li>
<li>Stop if the schedule didn&rsquo;t start this boot.</li>
<li>Check the players again, because someone could have joined during the updates.</li>
<li>Stop the server over telnet, so the world is saved.</li>
<li>Deallocate.</li>
</ul>
<p>This script leaves out one branch that my own module has: restarting the machine to finish updates that need it, and resuming the run afterward. When Windows reports a pending restart, this script logs that and carries on. The startup trigger exists for that branch, so without it the trigger does nothing.</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="k">param</span><span class="p">([</span><span class="no">switch</span><span class="p">]</span><span class="nv">$DryRun</span><span class="p">)</span>   <span class="c"># the first line of the file, above the functions</span>
</span></span><span class="line"><span class="cl"><span class="nv">$ErrorActionPreference</span> <span class="p">=</span> <span class="s1">&#39;Stop&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nv">$StartAtUtc</span>     <span class="p">=</span> <span class="s1">&#39;10:45&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$WindowMinutes</span>  <span class="p">=</span> <span class="mf">30</span>
</span></span><span class="line"><span class="cl"><span class="nv">$TelnetPort</span>     <span class="p">=</span> <span class="mf">8081</span>
</span></span><span class="line"><span class="cl"><span class="nv">$TelnetPassword</span> <span class="p">=</span> <span class="s1">&#39;&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$GameTask</span>       <span class="p">=</span> <span class="s1">&#39;7DaysToDieServer&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$WaitFor</span>        <span class="p">=</span> <span class="s1">&#39;7DaysToDieServerS3Backup&#39;</span><span class="p">,</span> <span class="s1">&#39;7DaysToDieServerAutoUpdate&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$LogFile</span>        <span class="p">=</span> <span class="s1">&#39;C:\ProgramData\MaintenanceWindow\maintenance.log&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">New-Item</span> <span class="n">-ItemType</span> <span class="n">Directory</span> <span class="n">-Force</span> <span class="p">(</span><span class="nb">Split-Path</span> <span class="nv">$LogFile</span><span class="p">)</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Write-Log([string]$Message</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Add-Content</span> <span class="n">-Path</span> <span class="nv">$LogFile</span> <span class="n">-Value</span> <span class="s2">&#34;</span><span class="p">$(</span><span class="nb">Get-Date</span> <span class="n">-Format</span> <span class="s1">&#39;yyyy-MM-dd HH:mm:ss&#39;</span><span class="p">)</span><span class="s2"> </span><span class="nv">$Message</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$os</span> <span class="p">=</span> <span class="nb">Get-CimInstance</span> <span class="n">Win32_OperatingSystem</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(((</span><span class="nb">Get-Date</span><span class="p">)</span> <span class="p">-</span> <span class="nv">$os</span><span class="p">.</span><span class="n">LastBootUpTime</span><span class="p">).</span><span class="py">TotalMinutes</span> <span class="o">-lt</span> <span class="mf">15</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Write-Log</span> <span class="s1">&#39;Under 15 minutes since boot: the startup run. Nothing to do.&#39;</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$bootUtc</span>   <span class="p">=</span> <span class="nv">$os</span><span class="p">.</span><span class="py">LastBootUpTime</span><span class="p">.</span><span class="py">ToUniversalTime</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$scheduled</span> <span class="p">=</span> <span class="nb">Test-ScheduledBoot</span> <span class="n">-BootTimeUtc</span> <span class="nv">$bootUtc</span> <span class="n">-StartAtUtc</span> <span class="nv">$StartAtUtc</span> <span class="n">-WindowMinutes</span> <span class="nv">$WindowMinutes</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s2">&#34;Booted </span><span class="p">$(</span><span class="nv">$bootUtc</span><span class="p">.</span><span class="py">ToString</span><span class="p">(</span><span class="s1">&#39;yyyy-MM-dd HH:mm&#39;</span><span class="p">))</span><span class="s2"> UTC. Started by: </span><span class="p">$(</span><span class="k">if</span> <span class="p">(</span><span class="nv">$scheduled</span><span class="p">)</span> <span class="p">{</span> <span class="s1">&#39;the schedule&#39;</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="s1">&#39;hand&#39;</span> <span class="p">})</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c"># The backup must finish before the machine goes away.</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$waitEnd</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Get-Date</span><span class="p">).</span><span class="py">AddMinutes</span><span class="p">(</span><span class="mf">60</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">while</span> <span class="p">(</span><span class="vm">$true</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$busy</span> <span class="p">=</span> <span class="vm">@</span><span class="p">(</span><span class="nv">$WaitFor</span> <span class="p">|</span> <span class="nb">Where-Object</span> <span class="p">{</span> <span class="p">(</span><span class="nb">Get-ScheduledTask</span> <span class="n">-TaskName</span> <span class="nv">$_</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span><span class="p">).</span><span class="py">State</span> <span class="o">-eq</span> <span class="s1">&#39;Running&#39;</span> <span class="p">})</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$busy</span><span class="p">)</span> <span class="p">{</span> <span class="k">break</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">((</span><span class="nb">Get-Date</span><span class="p">)</span> <span class="o">-gt</span> <span class="nv">$waitEnd</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Write-Log</span> <span class="s2">&#34;Still running after 60 minutes: </span><span class="p">$(</span><span class="nv">$busy</span> <span class="n">-join</span> <span class="s1">&#39;, &#39;</span><span class="p">)</span><span class="s2">. VM left on.&#34;</span><span class="p">;</span> <span class="k">return</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Write-Log</span> <span class="s2">&#34;Waiting for </span><span class="p">$(</span><span class="nv">$busy</span> <span class="n">-join</span> <span class="s1">&#39;, &#39;</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Start-Sleep</span> <span class="n">-Seconds</span> <span class="mf">30</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c"># Anything but a clean 0 counts as occupied.</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$running</span> <span class="p">=</span> <span class="p">[</span><span class="no">bool</span><span class="p">](</span><span class="nb">Get-Process</span> <span class="n">-Name</span> <span class="s1">&#39;7DaysToDieServer&#39;</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$players</span> <span class="p">=</span> <span class="mf">0</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$running</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$players</span> <span class="p">=</span> <span class="nb">Get-ServerPlayerCount</span> <span class="n">-Port</span> <span class="nv">$TelnetPort</span> <span class="n">-Password</span> <span class="nv">$TelnetPassword</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s2">&#34;Players online: </span><span class="p">$(</span><span class="k">if</span> <span class="p">(</span><span class="vm">$null</span> <span class="o">-eq</span> <span class="nv">$players</span><span class="p">)</span> <span class="p">{</span> <span class="s1">&#39;unknown&#39;</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="nv">$players</span> <span class="p">})</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$players</span> <span class="o">-ne</span> <span class="mf">0</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Write-Log</span> <span class="s1">&#39;Someone is or may be playing. VM left on.&#39;</span><span class="p">;</span> <span class="k">return</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="p">{</span> <span class="nv">$updates</span> <span class="p">=</span> <span class="nb">Install-PendingWindowsUpdate</span> <span class="n">-SearchOnly:</span><span class="nv">$DryRun</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Write-Log</span> <span class="s2">&#34;WARNING: Windows Update did not run: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$updates</span> <span class="p">=</span> <span class="p">[</span><span class="no">pscustomobject</span><span class="p">]</span><span class="vm">@</span><span class="p">{</span> <span class="n">Found</span> <span class="p">=</span> <span class="vm">@</span><span class="p">();</span> <span class="n">Installed</span> <span class="p">=</span> <span class="vm">@</span><span class="p">();</span> <span class="n">Failed</span> <span class="p">=</span> <span class="vm">@</span><span class="p">();</span> <span class="n">RebootRequired</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Test-PendingReboot</span><span class="p">)</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s2">&#34;Windows Update offered: </span><span class="p">$(</span><span class="nv">$updates</span><span class="p">.</span><span class="py">Found</span><span class="p">.</span><span class="n">Count</span><span class="p">)</span><span class="s2">. Restart required: </span><span class="p">$(</span><span class="nv">$updates</span><span class="p">.</span><span class="n">RebootRequired</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">foreach</span> <span class="p">(</span><span class="nv">$title</span> <span class="k">in</span> <span class="nv">$updates</span><span class="p">.</span><span class="n">Installed</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Write-Log</span> <span class="s2">&#34;  installed: </span><span class="nv">$title</span><span class="s2">&#34;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">foreach</span> <span class="p">(</span><span class="nv">$title</span> <span class="k">in</span> <span class="nv">$updates</span><span class="p">.</span><span class="n">Failed</span><span class="p">)</span>    <span class="p">{</span> <span class="nb">Write-Log</span> <span class="s2">&#34;  FAILED: </span><span class="nv">$title</span><span class="s2">&#34;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$scheduled</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Write-Log</span> <span class="s1">&#39;Started by hand, so it stays on.&#39;</span><span class="p">;</span> <span class="k">return</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nv">$resourceId</span> <span class="p">=</span> <span class="nb">Get-AzureResourceId</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$resourceId</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Write-Log</span> <span class="s1">&#39;No Azure instance metadata. Nothing to deallocate.&#39;</span><span class="p">;</span> <span class="k">return</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$running</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$late</span> <span class="p">=</span> <span class="nb">Get-ServerPlayerCount</span> <span class="n">-Port</span> <span class="nv">$TelnetPort</span> <span class="n">-Password</span> <span class="nv">$TelnetPassword</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="nv">$late</span> <span class="o">-ne</span> <span class="mf">0</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Write-Log</span> <span class="s1">&#39;A player may have joined. VM left on.&#39;</span><span class="p">;</span> <span class="k">return</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$DryRun</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Write-Log</span> <span class="s2">&#34;Dry run: would stop the server and deallocate </span><span class="nv">$resourceId</span><span class="s2">.&#34;</span><span class="p">;</span> <span class="k">return</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c"># Stop-GameServer, pasted into this file from the start-at-boot article,</span>
</span></span><span class="line"><span class="cl">    <span class="c"># throws unless exactly one server process is running. A game that is</span>
</span></span><span class="line"><span class="cl">    <span class="c"># already down has nothing to save, so go straight to the deallocate.</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nb">Get-Process</span> <span class="n">-Name</span> <span class="s1">&#39;7DaysToDieServer&#39;</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$secure</span> <span class="p">=</span> <span class="vm">$null</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="nv">$TelnetPassword</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$secure</span> <span class="p">=</span> <span class="nb">ConvertTo-SecureString</span> <span class="nv">$TelnetPassword</span> <span class="n">-AsPlainText</span> <span class="n">-Force</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Write-Log</span> <span class="p">(</span><span class="nb">Stop-GameServer</span> <span class="n">-Port</span> <span class="nv">$TelnetPort</span> <span class="n">-Password</span> <span class="nv">$secure</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s2">&#34;Deallocating </span><span class="nv">$resourceId</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$status</span> <span class="p">=</span> <span class="nb">Invoke-AzureSelfDeallocate</span> <span class="n">-ResourceId</span> <span class="nv">$resourceId</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Write-Log</span> <span class="s2">&#34;Azure accepted the deallocate (HTTP </span><span class="nv">$status</span><span class="s2">).&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="c"># Bring the game back rather than leave a running VM with nothing on it.</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Write-Log</span> <span class="s2">&#34;ERROR: deallocate refused: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Start-ScheduledTask</span> <span class="n">-TaskName</span> <span class="nv">$GameTask</span>
</span></span><span class="line"><span class="cl">        <span class="k">throw</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s2">&#34;ERROR: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">exit</span> <span class="mf">1</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="n">exit</span> <span class="mf">0</span></span></span></code></pre></div></div>
  </div>
</div><h2 id="12-register-the-maintenance-task">12. Register the maintenance task<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#12-register-the-maintenance-task"
     aria-label="Link to section: 12. Register the maintenance task" data-pagefind-ignore></a>
</h2>
<p>This registers the task on the VM. It runs daily at 12:00 and again 5 minutes after startup, as SYSTEM, with a three-hour limit. <code>MultipleInstances IgnoreNew</code> stops a second copy starting while one runs. It leaves out <code>StartWhenAvailable</code> on purpose. If the VM is off at 12:00, you don&rsquo;t want that missed run to fire when you boot it at 20:00 to play.</p>
<p>The machine clock on my VM was UTC. If yours isn&rsquo;t, <code>-At '12:00'</code> means 12:00 on its clock, so convert the time.</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$script</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer\maintenance.ps1&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$daily</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskTrigger</span> <span class="n">-Daily</span> <span class="n">-At</span> <span class="s1">&#39;12:00&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$startup</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskTrigger</span> <span class="n">-AtStartup</span>
</span></span><span class="line"><span class="cl"><span class="nv">$startup</span><span class="p">.</span><span class="py">Delay</span> <span class="p">=</span> <span class="s1">&#39;PT5M&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$action</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskAction</span> <span class="n">-Execute</span> <span class="s1">&#39;powershell.exe&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Argument</span> <span class="s2">&#34;-NoProfile -ExecutionPolicy RemoteSigned -File </span><span class="se">`&#34;</span><span class="nv">$script</span><span class="se">`&#34;</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$settings</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskSettingsSet</span> <span class="n">-ExecutionTimeLimit</span> <span class="p">(</span><span class="nb">New-TimeSpan</span> <span class="n">-Hours</span> <span class="mf">3</span><span class="p">)</span> <span class="n">-MultipleInstances</span> <span class="n">IgnoreNew</span>
</span></span><span class="line"><span class="cl"><span class="nb">Register-ScheduledTask</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServerMaintenance&#39;</span> <span class="n">-Action</span> <span class="nv">$action</span> <span class="n">-Trigger</span> <span class="vm">@</span><span class="p">(</span><span class="nv">$daily</span><span class="p">,</span> <span class="nv">$startup</span><span class="p">)</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Settings</span> <span class="nv">$settings</span> <span class="n">-User</span> <span class="s1">&#39;SYSTEM&#39;</span> <span class="n">-RunLevel</span> <span class="n">Highest</span></span></span></code></pre></div></div>
  </div>
</div><p>Both triggers run the same action, so the script can&rsquo;t tell which one fired. It uses uptime instead: under 15 minutes since boot means the startup run, and the script exits. It skips a daily run that lands within 15 minutes of a boot the same way, such as when you start the VM by hand at 11:58.</p>
<h2 id="13-confirm-the-window-works">13. Confirm the window works<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#13-confirm-the-window-works"
     aria-label="Link to section: 13. Confirm the window works" data-pagefind-ignore></a>
</h2>
<p>Run these in order. Each proves one claim.</p>
<p><strong>A hand-started VM stays on.</strong> Start the VM yourself outside the 30-minute window, wait more than 15 minutes, then run the task on the VM and read the log:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Start-ScheduledTask</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServerMaintenance&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Get-Content</span> <span class="s1">&#39;C:\ProgramData\MaintenanceWindow\maintenance.log&#39;</span> <span class="n">-Tail</span> <span class="mf">5</span></span></span></code></pre></div></div>
  </div>
</div><p>The log ends with <code>Started by hand, so it stays on.</code> and the VM keeps running. To rehearse a run without installing or deallocating anything, run <code>maintenance.ps1 -DryRun</code> from an elevated session instead.</p>
<p><strong>A scheduled boot deallocates.</strong> Use a VM that has been on and idle for more than 15 minutes. Set <code>$StartAtUtc</code> in <code>maintenance.ps1</code> to two minutes before the VM&rsquo;s boot time in UTC, so the boot counts as scheduled, and run the task. Read the boot time on the VM with <code>(Get-CimInstance Win32_OperatingSystem).LastBootUpTime.ToUniversalTime()</code>. Then poll from your own machine:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">az</span> <span class="n">vm</span> <span class="nb">get-instance</span><span class="n">-view</span> <span class="n">-g</span> <span class="nv">$rg</span> <span class="n">-n</span> <span class="nv">$vmName</span> <span class="p">-</span><span class="n">-query</span> <span class="s2">&#34;instanceView.statuses[1].displayStatus&#34;</span> <span class="n">-o</span> <span class="n">tsv</span></span></span></code></pre></div></div>
  </div>
</div><p>The log shows <code>Azure accepted the deallocate (HTTP 202).</code> and the status reads <code>VM deallocated</code>. For me that took under a minute from the start of the run. Put <code>$StartAtUtc</code> back afterward.</p>
<p><strong>The Logic App starts the VM.</strong> With the VM deallocated, fire the trigger by hand instead of waiting for 10:45. This boots the VM outside the window, so the maintenance task leaves it on. Deallocate it by hand with <code>az vm deallocate -g $rg -n $vmName</code> when the test is done.</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">az</span> <span class="n">rest</span> <span class="p">-</span><span class="n">-method</span> <span class="n">post</span> <span class="p">-</span><span class="n">-uri</span> <span class="s2">&#34;https://management.azure.com</span><span class="p">$(</span><span class="nv">$app</span><span class="p">.</span><span class="n">id</span><span class="p">)</span><span class="s2">/triggers/Daily/run?api-version=2019-05-01&#34;</span></span></span></code></pre></div></div>
  </div>
</div><p>In the Logic App&rsquo;s run history in the Azure portal, the <code>Start_VM</code> action shows Running, then Accepted, and the VM boots.</p>
<p><strong>The right identities did it.</strong> Open the VM&rsquo;s activity log in the Azure portal. The deallocate shows the VM&rsquo;s own identity as its caller and the start shows the Logic App&rsquo;s.</p>
<p><strong>The schedule runs on its own.</strong> The next morning, read the logs instead of firing anything. My first scheduled window went the way the table in step 2 lays out. The Logic App started the VM a minute after 10:45, the backup uploaded, and the update found the server already on the published build. At 12:00 my module&rsquo;s maintenance log read <code>Started by: the schedule (10:45 UTC)</code>, <code>Players online: 0</code>, <code>Offered: 0</code>, then <code>Azure accepted the deallocate (HTTP 202).</code>, and the VM deallocated. Those lines come from my module&rsquo;s log; the script in step 11 words the update line as <code>Windows Update offered: 0</code>.</p>
<!-- style-check: end procedure -->
<p>Now the VM rises at 10:45, does its chores, and is back in the ground by lunch.</p>
<h2 id="tested-on">Tested on<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#tested-on"
     aria-label="Link to section: Tested on" data-pagefind-ignore></a>
</h2>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>VM size</dt> <dd>Standard_B4ls_v2</dd></div>
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2019 Datacenter, image 17763.5206.231202</dd></div>
    <div class="tested__row"><dt>PowerShell on the VM</dt> <dd>Windows PowerShell 5.1</dd></div>
    <div class="tested__row"><dt>Machine clock</dt> <dd>UTC</dd></div>
    <div class="tested__row"><dt>Azure CLI</dt> <dd>on the admin machine</dd></div>
    <div class="tested__row"><dt>Game</dt> <dd>7 Days to Die dedicated server (294420)</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>November 2026</dd></div>
  </dl>
</div>
<h2 id="what-i-didnt-test">What I didn&rsquo;t test<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#what-i-didnt-test"
     aria-label="Link to section: What I didn’t test" data-pagefind-ignore></a>
</h2>
<p>My own server runs a module version of this logic, not the single script in step 11, so run the confirmation steps in step 13 before you trust your copy with the schedule.</p>
<p>Three things matter if your server differs from mine:</p>
<ul>
<li><strong>Installing updates.</strong> No update was waiting on the mornings I ran this, so only the search has run. The first morning one is offered, read the maintenance log afterward.</li>
<li><strong>A player online.</strong> I only ever saw a count of 0. If people play during your window, test that the VM stays on before you rely on it.</li>
<li><strong>A telnet password.</strong> I didn&rsquo;t run it with one set. If your server has one, check that the player count and the stop both still work.</li>
</ul>
<h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="logic-app-run-at-creation-failed-with-forbidden">Logic App run at creation failed with <code>Forbidden</code><a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#logic-app-run-at-creation-failed-with-forbidden"
     aria-label="Link to section: Logic App run at creation failed with Forbidden" data-pagefind-ignore></a>
</h3>
<p>The run history shows a run at the moment you created the Logic App, with status Failed and the <code>Start_VM</code> action returning <code>Forbidden</code>. You created the Logic App without a <code>startTime</code>, so it ran once on save, before its identity held a role. Assign the role in step 6 and set <code>startTime</code> as in step 5. The scheduled runs after that aren&rsquo;t affected.</p>
<h3 id="invalidworkflowtriggerrecurrence-invalid-start-time">InvalidWorkflowTriggerRecurrence: invalid start time<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#invalidworkflowtriggerrecurrence-invalid-start-time"
     aria-label="Link to section: InvalidWorkflowTriggerRecurrence: invalid start time" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">InvalidWorkflowTriggerRecurrence</span> <span class="console__token">...</span> <span class="console__token">invalid</span> <span class="console__token">start</span> <span class="console__token">time</span> <span class="console__token">&#39;2026-11-02T10:45:00.0000000&#39;</span> <span class="console__token">zone</span> <span class="console__token">designator</span> <span class="console__token">for</span> <span class="console__token">time</span> <span class="console__token">zone</span> <span class="console__token">&#39;UTC&#39;.</span> <span class="console__token">Expected</span> <span class="console__token">start</span> <span class="console__token">time</span> <span class="console__token">format</span> <span class="console__token">with</span> <span class="console__token">zone</span> <span class="console__token">designator</span> <span class="console__token">is</span> <span class="console__token">&#39;yyyy-MM-ddTHH:mm:ssZ&#39;.</span></span></code></pre>
    </div>
  </div></div><p>With <code>timeZone</code> set to <code>UTC</code> the service requires the trailing <code>Z</code>. Format the time like this:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="p">[</span><span class="no">datetime</span><span class="p">]::</span><span class="n">UtcNow</span><span class="p">.</span><span class="py">AddMinutes</span><span class="p">(</span><span class="mf">-1</span><span class="p">).</span><span class="py">ToString</span><span class="p">(</span><span class="s2">&#34;yyyy-MM-dd&#39;T&#39;HH:mm:ss&#39;Z&#39;&#34;</span><span class="p">)</span></span></span></code></pre></div></div>
  </div>
</div><h3 id="logic-app-skipped-the-first-day">Logic App skipped the first day<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#logic-app-skipped-the-first-day"
     aria-label="Link to section: Logic App skipped the first day" data-pagefind-ignore></a>
</h3>
<p>There is no error. You set <code>startTime</code> to the scheduled minute, and <code>nextExecutionTime</code> comes back a day late. The service reads that occurrence as already taken. Set <code>startTime</code> to one minute in the past, as in step 5.</p>
<h3 id="missingsubscriptionregistration-for-microsoftlogic">MissingSubscriptionRegistration for Microsoft.Logic<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#missingsubscriptionregistration-for-microsoftlogic"
     aria-label="Link to section: MissingSubscriptionRegistration for Microsoft.Logic" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">MissingSubscriptionRegistration</span> <span class="console__token">...</span> <span class="console__token">The</span> <span class="console__token">subscription</span> <span class="console__token">is</span> <span class="console__token">not</span> <span class="console__token">registered</span> <span class="console__token">to</span> <span class="console__token">use</span> <span class="console__token">namespace</span> <span class="console__token">&#39;Microsoft.Logic&#39;</span></span></code></pre>
    </div>
  </div></div><p>The subscription has never had a Logic App. Register the provider and run the create again:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">az</span> <span class="n">provider</span> <span class="n">register</span> <span class="p">-</span><span class="n">-namespace</span> <span class="n">Microsoft</span><span class="p">.</span><span class="py">Logic</span> <span class="p">-</span><span class="n">-wait</span></span></span></code></pre></div></div>
  </div>
</div><h3 id="cannot-find-user-or-service-principal-in-graph-database">Cannot find user or service principal in graph database<a class="heading-anchor" href="https://looselydecoupled.com/azure-vm-daily-maintenance-window/#cannot-find-user-or-service-principal-in-graph-database"
     aria-label="Link to section: Cannot find user or service principal in graph database" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Cannot</span> <span class="console__token">find</span> <span class="console__token">user</span> <span class="console__token">or</span> <span class="console__token">service</span> <span class="console__token">principal</span> <span class="console__token">in</span> <span class="console__token">graph</span> <span class="console__token">database</span></span></code></pre>
    </div>
  </div></div><p><code>az role assignment list --assignee &lt;principal-id&gt;</code> looks the identity up in Microsoft Graph, and a new identity isn&rsquo;t there yet. List by scope and role and filter on <code>principalId</code>, and create the assignment with <code>--assignee-object-id</code> and <code>--assignee-principal-type ServicePrincipal</code>, as in steps 4 and 6.</p>
]]></content:encoded>
    </item>
    
    <item>
      <title>PowerShell -File vs. -Command: Which Exit Code Does the Caller Get?</title>
      <link>https://looselydecoupled.com/powershell-file-vs-command-exit-code/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/powershell-file-vs-command-exit-code/</guid>
      <pubDate>Fri, 30 Oct 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>PowerShell</category>
      <category>Unattended</category>
      
      <description>Under -File the caller receives the exit code your script chose; under -Command, any script code other than 0 or 1 reaches the caller as 1.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>Run your script with <code>-File</code>, not <code>-Command</code>. With <code>-File</code>, the launcher receives the number that the script passes to <code>exit</code>. The launcher can be Task Scheduler, a <code>.cmd</code> file or another PowerShell session. With <code>-Command</code>, the launcher receives 1 for any number other than 0 or 1. Under <code>-Command</code>, a script that ends with <code>exit 3</code> reports 1. Task Scheduler shows 1 as a Last Run Result of <code>0x1</code>.</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">powershell.exe -NoProfile -File &#34;C:\Scripts\job.ps1&#34;</span></span></code></pre></div></div>
  </div>
</div><p>With either parameter, a script reports failure only when it exits with a number other than 0. A script still exits 0 after a <code>Write-Error</code> that lets it carry on. A script also exits 0 when its last line is a native command that fails. To pass a native command&rsquo;s code on under <code>-File</code>, end the script with <code>exit $LASTEXITCODE</code>. Under <code>-Command</code>, end the command string with <code>; exit $LASTEXITCODE</code>.</p>

</div>

<p>I call whatever starts your script the launcher: Task Scheduler, a <code>.cmd</code> file, or another PowerShell session. I ran every case in this article on Windows Server 2025, in Windows PowerShell 5.1 and PowerShell 7. The cases in the first two tables, the command strings and the missing script ran from three launchers: a <code>.cmd</code> file read <code>%ERRORLEVEL%</code>, a PowerShell session read <code>$LASTEXITCODE</code>, and a scheduled task showed its Last Run Result. All three got the same number every time, and Task Scheduler shows it in hex. The rest ran as scheduled tasks only. Microsoft documents the switches in <a href="https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Core/About/about_PowerShell_exe" rel="external noopener" target="_blank">about_PowerShell_exe<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> and <a href="https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_pwsh" rel="external noopener" target="_blank">about_Pwsh<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>. The tables here show what my runs returned.</p>
<h2 id="exit-codes-under--file">Exit codes under <code>-File</code><a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#exit-codes-under--file"
     aria-label="Link to section: Exit codes under -File" data-pagefind-ignore></a>
</h2>
<p>Under <code>-File</code>, the launcher gets the code your script exits with. Windows PowerShell 5.1 and PowerShell 7 give the same results:</p>
<div class="table-wrap" data-scrollable data-label="Table: Script">
  <table>
    <thead>
      <tr><th scope="col">Script</th><th scope="col">Exit code under <code>-File</code></th></tr>
    </thead>
    <tbody>
      <tr><td><code>'ok'</code></td><td>0</td></tr>
      <tr><td><code>exit 3</code></td><td>3</td></tr>
      <tr><td><code>exit 256</code></td><td>256 (<code>0x100</code> in Task Scheduler)</td></tr>
      <tr><td><code>exit -1</code></td><td>-1 (<code>0xFFFFFFFF</code> in Task Scheduler)</td></tr>
      <tr><td><code>throw 'boom'</code></td><td>1</td></tr>
      <tr><td>A syntax error (<code>'a' +</code>)</td><td>1</td></tr>
      <tr><td><code>Write-Error 'boom'</code>, then <code>'after'</code></td><td>0</td></tr>
      <tr><td><code>'before'</code>, then <code>Write-Error 'boom'</code> as the last statement</td><td>0</td></tr>
      <tr><td><code>cmd.exe /c exit 5</code> as the last line</td><td>0</td></tr>
    </tbody>
  </table>
</div>
<p>A script-terminating error is one that stops your script on the spot, like <code>throw</code> or a cmdlet run with <code>-ErrorAction Stop</code>. If your script stops on one, the launcher gets 1. A non-terminating error is one your script reports and then carries on past, like <code>Write-Error</code>. If your script hits only errors like that, the launcher gets 0. A native command is a program that isn&rsquo;t PowerShell, like cmd.exe or robocopy. If your script ends on one, the launcher also gets 0. So does a script that runs <code>Import-Module</code> on a missing module and then calls a command that doesn&rsquo;t exist. I saw that one in an earlier run as SYSTEM.</p>
<h2 id="exit-codes-under--command">Exit codes under <code>-Command</code><a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#exit-codes-under--command"
     aria-label="Link to section: Exit codes under -Command" data-pagefind-ignore></a>
</h2>
<p>Under <code>-Command &quot;&amp; 'script.ps1'&quot;</code>, the launcher doesn&rsquo;t get your script&rsquo;s code. It gets 0 or 1:</p>
<div class="table-wrap" data-scrollable data-label="Table: Script">
  <table>
    <thead>
      <tr><th scope="col">Script</th><th scope="col">Under <code>-File</code></th><th scope="col">Under <code>-Command &quot;&amp; 'script.ps1'&quot;</code></th></tr>
    </thead>
    <tbody>
      <tr><td><code>exit 3</code></td><td>3</td><td>1</td></tr>
      <tr><td><code>exit 256</code></td><td>256</td><td>1</td></tr>
      <tr><td><code>exit -1</code></td><td>-1</td><td>1</td></tr>
      <tr><td><code>ok</code>, <code>throw</code>, <code>Write-Error</code>, a syntax error, a native command</td><td>as in the earlier table</td><td>the same as under <code>-File</code></td></tr>
    </tbody>
  </table>
</div>
<p>When your script runs, the two switches differ only where it exits with a code other than 0 or 1. That&rsquo;s why your task shows <code>0x1</code> for a script that ends with <code>exit 3</code>.</p>
<p>An <code>exit</code> inside the command string keeps its code. With no script file, <code>-Command &quot;exit 5&quot;</code> gives 5 in both editions. Microsoft documents the same change to 1 when a native command is the last command in the string. I didn&rsquo;t test that case.</p>
<p>So where does the 0 or 1 come from? PowerShell keeps a success flag, <code>$?</code>, which reads <code>True</code> or <code>False</code> for the statement it ran last. Under <code>-Command</code>, PowerShell runs your string and then reports that flag: 0 for <code>True</code>, 1 for <code>False</code>. When the last statement is <code>&amp; 'script.ps1'</code>, the flag depends on how your script ended:</p>
<ul>
<li>If your script exits with any code other than 0, <code>$?</code> is <code>False</code>, and the launcher gets 1.</li>
<li>If your script only wrote a non-terminating error, or ended on a native command, <code>$?</code> stays <code>True</code>, and the launcher gets 0.</li>
</ul>
<p>That&rsquo;s why the same non-terminating error gives different codes, depending on what runs last in the string:</p>
<div class="table-wrap" data-scrollable data-label="Table: Command string">
  <table>
    <thead>
      <tr><th scope="col">Command string</th><th scope="col">Exit code</th></tr>
    </thead>
    <tbody>
      <tr><td><code>&quot;Write-Error 'boom'&quot;</code></td><td>1</td></tr>
      <tr><td><code>&quot;Write-Error 'boom'; 'after'&quot;</code></td><td>0</td></tr>
      <tr><td><code>&quot;&amp; 'script.ps1'&quot;</code>, where the script&rsquo;s last statement is <code>Write-Error 'boom'</code></td><td>0</td></tr>
      <tr><td><code>&quot;throw 'boom'&quot;</code></td><td>1</td></tr>
    </tbody>
  </table>
</div>
<h3 id="keep-the-real-code-under--command">Keep the real code under <code>-Command</code><a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#keep-the-real-code-under--command"
     aria-label="Link to section: Keep the real code under -Command" data-pagefind-ignore></a>
</h3>
<p>Pass the code on yourself: end the command string with <code>exit $LASTEXITCODE</code>.</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">-NoProfile -Command &#34;&amp; &#39;C:\Scripts\job.ps1&#39;; exit $LASTEXITCODE&#34;</span></span></code></pre></div></div>
  </div>
</div><p>This text goes in the task&rsquo;s Arguments field or on a line in a <code>.cmd</code> file. If you build it inside a double-quoted PowerShell string, for example for <code>New-ScheduledTaskAction -Argument</code>, escape the dollar sign as <code>`$LASTEXITCODE</code>. Otherwise your session fills in <code>$LASTEXITCODE</code> itself before the new PowerShell starts. If your script ends with <code>exit 5</code>, your task now gets 5 in both editions. Without this ending, it gets 1. When I redirected the call&rsquo;s output, this form returned 0 for a missing script and for a script that doesn&rsquo;t parse. I didn&rsquo;t test it without the redirect. If your script might not run, use the <code>try</code>/<code>catch</code> form in &ldquo;Script that never ran returns 0 with exit $LASTEXITCODE&rdquo;. Keep the <code>-Command</code> form when you need the redirect wrapper that <a href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/">Task Scheduler Falsely Reports Success for a PowerShell Script That Works Manually</a> describes.</p>
<h2 id="pass-a-native-commands-code-through">Pass a native command&rsquo;s code through<a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#pass-a-native-commands-code-through"
     aria-label="Link to section: Pass a native command’s code through" data-pagefind-ignore></a>
</h2>
<p>A native command&rsquo;s exit code doesn&rsquo;t become your script&rsquo;s exit code. If your script ends with <code>cmd.exe /c exit 5</code>, it returns 0 under both switches. To pass the code on, end your script with <code>exit $LASTEXITCODE</code>:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">cmd</span><span class="p">.</span><span class="py">exe</span> <span class="p">/</span><span class="n">c</span> <span class="n">exit</span> <span class="mf">5</span>
</span></span><span class="line"><span class="cl"><span class="n">exit</span> <span class="nv">$LASTEXITCODE</span></span></span></code></pre></div></div>
  </div>
</div><p>Under <code>-File</code>, the launcher now gets 5 in both editions. Under <code>-Command</code>, the same script still gives 1. It gives 5 once the command string ends with <code>; exit $LASTEXITCODE</code>, whether or not your script has its own <code>exit</code> line. A native command or a script&rsquo;s <code>exit</code> sets <code>$LASTEXITCODE</code>. For why a failed cmdlet leaves it alone, see <a href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/">Why $LASTEXITCODE Doesn&rsquo;t Work the Way You Expect in PowerShell</a>.</p>
<h2 id="read-the-exit-code-from-each-launcher">Read the exit code from each launcher<a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#read-the-exit-code-from-each-launcher"
     aria-label="Link to section: Read the exit code from each launcher" data-pagefind-ignore></a>
</h2>
<p>Each launcher prints the same number in a different form. Run your script from each one to confirm what you get.</p>
<p>In cmd.exe, <code>%ERRORLEVEL%</code> holds the code in decimal:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="BAT">
  <div class="code-block__head"><span class="code-block__lang">BAT</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bat" data-lang="bat"><span class="line"><span class="cl">powershell.exe -NoProfile -File C:\Scripts\job.ps1
</span></span><span class="line"><span class="cl"><span class="k">echo</span> <span class="nv">%ERRORLEVEL%</span></span></span></code></pre></div></div>
  </div>
</div><p>In the PowerShell session that starts your script, <code>$LASTEXITCODE</code> holds it in decimal:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="p">&amp;</span> <span class="n">powershell</span><span class="p">.</span><span class="py">exe</span> <span class="n">-NoProfile</span> <span class="o">-File</span> <span class="n">C:</span><span class="p">\</span><span class="n">Scripts</span><span class="p">\</span><span class="n">job</span><span class="p">.</span><span class="py">ps1</span>
</span></span><span class="line"><span class="cl"><span class="nv">$LASTEXITCODE</span></span></span></code></pre></div></div>
  </div>
</div><p>In Task Scheduler, <code>Get-ScheduledTaskInfo</code> prints <code>LastTaskResult</code> as an unsigned decimal, so exit -1 reads 4294967295 there. Last Run Result shows the same number in hex, <code>0xFFFFFFFF</code>. This command prints the hex form:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-ScheduledTaskInfo</span> <span class="n">-TaskName</span> <span class="s1">&#39;&lt;task-name&gt;&#39;</span> <span class="n">-TaskPath</span> <span class="s1">&#39;\&#39;</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Select-Object</span> <span class="n">LastRunTime</span><span class="p">,</span> <span class="vm">@</span><span class="p">{</span> <span class="n">Name</span> <span class="p">=</span> <span class="s1">&#39;LastTaskResult&#39;</span><span class="p">;</span> <span class="n">Expression</span> <span class="p">=</span> <span class="p">{</span> <span class="s1">&#39;0x{0:X}&#39;</span> <span class="o">-f</span> <span class="nv">$_</span><span class="p">.</span><span class="py">LastTaskResult</span> <span class="p">}</span> <span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>The task history records the code as an HRESULT, a Windows error number. For exit 1 it shows return code 2147942401 (<code>0x80070001</code>), in an entry that still reads &ldquo;successfully completed&rdquo;. Do not read that entry as success. Task history was off on the fresh Windows Server 2025 Azure Marketplace image I tested. Turn it on with <code>wevtutil set-log Microsoft-Windows-TaskScheduler/Operational /enabled:true</code> before the run you want to see.</p>
<h3 id="script-called-inside-a-session">Script called inside a session<a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#script-called-inside-a-session"
     aria-label="Link to section: Script called inside a session" data-pagefind-ignore></a>
</h3>
<p>When you call a script with <code>&amp;</code> inside a PowerShell session, the script&rsquo;s <code>exit</code> doesn&rsquo;t end your session. In both editions, <code>exit 3</code> in the called script ends only that script, and your session carries on. After the call, <code>$LASTEXITCODE</code> and <code>$?</code> read like this:</p>
<div class="table-wrap" data-scrollable data-label="Table: Called script">
  <table>
    <thead>
      <tr><th scope="col">Called script</th><th scope="col"><code>$LASTEXITCODE</code></th><th scope="col"><code>$?</code></th></tr>
    </thead>
    <tbody>
      <tr><td><code>'ok'</code></td><td>unset</td><td><code>True</code></td></tr>
      <tr><td><code>exit 3</code></td><td>3</td><td><code>False</code></td></tr>
      <tr><td><code>throw 'boom'</code></td><td>unset</td><td>not read; the caller&rsquo;s <code>catch</code> ran with <code>boom</code></td></tr>
      <tr><td><code>Write-Error 'boom'</code></td><td>unset</td><td><code>True</code></td></tr>
      <tr><td><code>cmd.exe /c exit 5</code></td><td>5</td><td><code>True</code></td></tr>
    </tbody>
  </table>
</div>
<p>I reset <code>$LASTEXITCODE</code> to <code>$null</code> before each call. After a script that ends in <code>cmd.exe /c exit 5</code>, <code>$?</code> is <code>True</code> for the script call. Read <code>$LASTEXITCODE</code>, not <code>$?</code>, to get the native command&rsquo;s result.</p>
<h2 id="check-your-scripts-with-a-coding-agent">Check your scripts with a coding agent<a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#check-your-scripts-with-a-coding-agent"
     aria-label="Link to section: Check your scripts with a coding agent" data-pagefind-ignore></a>
</h2>
<p>Paste this into your own local coding agent. It reads your scheduled tasks and reports which ones can lose an exit code. Add the names of any CI steps or <code>.cmd</code> wrappers you want checked on the line that starts &ldquo;Additional places to check&rdquo;. It changes nothing.</p>
<div class="code-block" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">You are auditing how PowerShell scripts are launched. Read only. Do not change
</span></span><span class="line"><span class="cl">anything: no Set-ScheduledTask, no Register-ScheduledTask, no edits to any
</span></span><span class="line"><span class="cl">script, task, wrapper or CI file. Do not start any task and do not run any
</span></span><span class="line"><span class="cl">script.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Additional places to check (leave empty if none): &lt;CI steps or .cmd wrappers&gt;
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">1. List every scheduled task whose action runs powershell.exe or pwsh.exe, with
</span></span><span class="line"><span class="cl">   Get-ScheduledTask. Add every item named above whose command line runs
</span></span><span class="line"><span class="cl">   powershell.exe or pwsh.exe. For each, report the task name or file, the
</span></span><span class="line"><span class="cl">   executable, and the arguments verbatim.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">2. Classify each by how the script is launched:
</span></span><span class="line"><span class="cl">   - File: the arguments use -File.
</span></span><span class="line"><span class="cl">   - CommandAmpersand: the arguments use -Command with &amp; &#39;script&#39; .
</span></span><span class="line"><span class="cl">   - CommandInline: the arguments use -Command with a command string that does
</span></span><span class="line"><span class="cl">     not call a script file.
</span></span><span class="line"><span class="cl">   - Other: a wrapper that launches powershell, or anything not covered by the
</span></span><span class="line"><span class="cl">     rules below. Report the arguments verbatim and say the result was not
</span></span><span class="line"><span class="cl">     measured.
</span></span><span class="line"><span class="cl">   For pwsh.exe, treat -f and -c as -File and -Command (documented aliases in
</span></span><span class="line"><span class="cl">   about_Pwsh). Report any other abbreviation, and any abbreviation on
</span></span><span class="line"><span class="cl">   powershell.exe, verbatim as Other. With neither switch, pwsh.exe arguments are File (about_Pwsh);
</span></span><span class="line"><span class="cl">   for powershell.exe, report the arguments verbatim and say the result was not
</span></span><span class="line"><span class="cl">   measured. Decode -EncodedCommand, then classify the decoded string as
</span></span><span class="line"><span class="cl">   CommandAmpersand or CommandInline.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">3. For each, say whether an exit code other than 0 or 1 from the script would
</span></span><span class="line"><span class="cl">   reach the caller, using these measured rules:
</span></span><span class="line"><span class="cl">   - File: the script&#39;s exit code reaches the caller unchanged, if the path
</span></span><span class="line"><span class="cl">     is right (see the path rule below).
</span></span><span class="line"><span class="cl">   - CommandAmpersand: any code other than 0 or 1 becomes 1, unless the command
</span></span><span class="line"><span class="cl">     string ends with &#34;; exit $LASTEXITCODE&#34;. If it does end that way, the code
</span></span><span class="line"><span class="cl">     survives. Measured with the script&#39;s output redirected (*&gt; log): a script
</span></span><span class="line"><span class="cl">     path that does not exist or a script that does not parse then returns 0,
</span></span><span class="line"><span class="cl">     unless the call sits inside try { } catch { exit 1 }. Without a redirect
</span></span><span class="line"><span class="cl">     this case was not measured; say so.
</span></span><span class="line"><span class="cl">   - CommandInline: &#34;exit N&#34; inside the string keeps N. A string that is only
</span></span><span class="line"><span class="cl">     Write-Error gives 1; Write-Error followed by a statement that succeeds
</span></span><span class="line"><span class="cl">     (measured: Write-Error &#39;boom&#39;; &#39;after&#39;) gives 0. The code follows the
</span></span><span class="line"><span class="cl">     last statement&#39;s status. For any other string, say the result was not
</span></span><span class="line"><span class="cl">     measured.
</span></span><span class="line"><span class="cl">   - File and CommandAmpersand: a script that ends on a native command returns
</span></span><span class="line"><span class="cl">     0. Under File, ending the script with &#34;exit $LASTEXITCODE&#34; passes the code
</span></span><span class="line"><span class="cl">     on. Under CommandAmpersand, the command string must also end with
</span></span><span class="line"><span class="cl">     &#34;; exit $LASTEXITCODE&#34;. A Write-Error that does not stop the script leaves
</span></span><span class="line"><span class="cl">     the code at 0.
</span></span><span class="line"><span class="cl">   - File: if the script path in the arguments is unquoted and contains a space,
</span></span><span class="line"><span class="cl">     or the file does not exist, the code is 0xFFFD0000 (Windows PowerShell 5.1)
</span></span><span class="line"><span class="cl">     or 0x40 (PowerShell 7) and no script code survives. Check the path exists
</span></span><span class="line"><span class="cl">     and is quoted.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">   For items from the Additional places line, say the caller was not measured
</span></span><span class="line"><span class="cl">   (the base File and CommandAmpersand results were measured for cmd.exe, a
</span></span><span class="line"><span class="cl">   parent PowerShell and Task Scheduler; the &#34;; exit $LASTEXITCODE&#34;, redirect
</span></span><span class="line"><span class="cl">   and try/catch results for Task Scheduler only) and report the
</span></span><span class="line"><span class="cl">   classification only.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">4. For each File and CommandAmpersand task, open the script it names (read only) and report whether
</span></span><span class="line"><span class="cl">   it ends with an explicit exit, and whether its last statement is a native
</span></span><span class="line"><span class="cl">   command.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Report one row per task: name, launch type, whether a code other than 0 or 1
</span></span><span class="line"><span class="cl">survives, and why. Then propose each fix as text for me to review and apply.</span></span></code></pre></div></div>
  </div>
</div><h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="exit-code--196608-0xfffd0000-or-64-missing-script-or-unquoted-path-with-a-space">Exit code -196608 (0xFFFD0000) or 64: missing script or unquoted path with a space<a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#exit-code--196608-0xfffd0000-or-64-missing-script-or-unquoted-path-with-a-space"
     aria-label="Link to section: Exit code -196608 (0xFFFD0000) or 64: missing script or unquoted path with a space" data-pagefind-ignore></a>
</h3>
<p>When your script doesn&rsquo;t exist, the code depends on the edition and the switch. An unquoted path that contains a space, such as <code>-File C:\ts\My Scripts\ok.ps1</code>, gives the same two codes:</p>
<div class="table-wrap" data-scrollable data-label="Table: Action">
  <table>
    <thead>
      <tr><th scope="col">Action</th><th scope="col">Windows PowerShell 5.1</th><th scope="col">PowerShell 7</th></tr>
    </thead>
    <tbody>
      <tr><td><code>-File</code> with a missing script</td><td>-196608 (<code>0xFFFD0000</code>)</td><td>64 (<code>0x40</code>)</td></tr>
      <tr><td><code>-File</code> with an unquoted path that contains a space</td><td><code>0xFFFD0000</code></td><td><code>0x40</code></td></tr>
      <tr><td><code>-Command &quot;&amp; 'script.ps1'&quot;</code> with a missing script</td><td>1</td><td>1</td></tr>
    </tbody>
  </table>
</div>
<p>cmd.exe and a PowerShell session print -196608 for the first value. <code>Get-ScheduledTaskInfo</code> prints 4294770688, and Task Scheduler prints <code>0xFFFD0000</code>. To fix the space case, quote the path: <code>-File &quot;C:\ts\My Scripts\ok.ps1&quot;</code> gives 0 in both editions.</p>
<h3 id="script-that-never-ran-returns-0-with-exit-lastexitcode">Script that never ran returns 0 with exit $LASTEXITCODE<a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#script-that-never-ran-returns-0-with-exit-lastexitcode"
     aria-label="Link to section: Script that never ran returns 0 with exit $LASTEXITCODE" data-pagefind-ignore></a>
</h3>
<p>I ran the wrapper <code>-Command &quot;&amp; 'script.ps1' *&gt; log; exit $LASTEXITCODE&quot;</code>, which redirects the output to a log. It returned 0 for a missing script and for a script with a syntax error, in both editions, because no native command set the code. The form in &ldquo;Keep the real code under <code>-Command</code>&rdquo; has no redirect, and I didn&rsquo;t test this case for it. Wrap the call in <code>try</code> and write the error to the log, and the launcher gets 1 for both:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">-NoProfile -Command &#34;try { &amp; &#39;C:\Scripts\job.ps1&#39; *&gt; C:\Scripts\logs\job.log } catch { $_ *&gt;&gt; C:\Scripts\logs\job.log; exit 1 }; exit $LASTEXITCODE&#34;</span></span></code></pre></div></div>
  </div>
</div><p>The same escaping applies as earlier: inside a double-quoted PowerShell string, escape each <code>$</code> with a backtick. For how to write that log, see <a href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/">Task Scheduler Falsely Reports Success for a PowerShell Script That Works Manually</a>.</p>
<h2 id="what-these-tests-did-not-cover">What these tests did not cover<a class="heading-anchor" href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/#what-these-tests-did-not-cover"
     aria-label="Link to section: What these tests did not cover" data-pagefind-ignore></a>
</h2>
<ul>
<li>A CI runner as the launcher. I tested cmd.exe, a PowerShell session, and Task Scheduler.</li>
<li><code>return</code> instead of <code>exit</code>, and <code>-File</code> with arguments passed to the script.</li>
<li>Windows Server 2022, Windows 11, and Task Scheduler logons other than a SYSTEM task.</li>
</ul>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2025 Datacenter 24H2, build 26100.33674</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>Windows PowerShell 5.1.26100.33648 and PowerShell 7.6.9</dd></div>
    <div class="tested__row"><dt>Launchers</dt> <dd>cmd.exe, a parent Windows PowerShell 5.1 session, and a Task Scheduler task running as SYSTEM</dd></div>
    <div class="tested__row"><dt>Earlier run</dt> <dd>Build 26100.33650 with PowerShell 7.6.8, Task Scheduler only</dd></div>
    <div class="tested__row"><dt>Not tested</dt> <dd>CI runners, return, Windows Server 2022, Windows 11</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>October 2026</dd></div>
  </dl>
</div>
]]></content:encoded>
    </item>
    
    <item>
      <title>Task Scheduler Falsely Reports Success for a PowerShell Script That Works Manually</title>
      <link>https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/</guid>
      <pubDate>Sat, 24 Oct 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>Unattended</category>
      <category>PowerShell</category>
      
      <description>Task Scheduler records the exit code of powershell.exe, not whether the script worked, so a script that hit an error and carried on is recorded as a success.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>When a PowerShell script works at your prompt but fails under Task Scheduler, the task can still report success. A Last Run Result of <code>0x0</code> and a history entry that says &ldquo;successfully&rdquo; don&rsquo;t prove that the script worked. Three failures leave the result at <code>0x0</code>: a non-terminating error, a failed <code>Import-Module</code>, and a native command&rsquo;s exit code. A non-terminating error is one that PowerShell reports and then carries on past.</p>
<p>Either of two changes shows the failure. One change adds <code>Start-Transcript</code> to the script. The other change runs the script from a <code>-Command</code> action that redirects all output to a file. End the script with <code>exit $LASTEXITCODE</code>, so that a native command&rsquo;s exit code reaches the task:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Start-Transcript</span> <span class="n">-Path</span> <span class="s1">&#39;C:\Scripts\logs\job-transcript.log&#39;</span>
</span></span><span class="line"><span class="cl"><span class="c"># ... the script ...</span>
</span></span><span class="line"><span class="cl"><span class="n">exit</span> <span class="nv">$LASTEXITCODE</span></span></span></code></pre></div></div>
  </div>
</div><p>With a <code>-File</code> action, the <code>exit</code> line passes the native command&rsquo;s code to the task. A script that ends with <code>cmd.exe /c exit 5</code> and then <code>exit $LASTEXITCODE</code> shows <code>0x5</code>. A <code>-Command</code> action that calls the script with <code>&amp;</code> reports 1 for any exit code from the script other than 0 or 1. A <code>-Command</code> action needs <code>; exit $LASTEXITCODE</code> at the end of its own command string as well. Wrap the call to the script in <code>try</code> too. With the <code>try</code>, a script that throws, hits an <code>-ErrorAction Stop</code> error, doesn&rsquo;t exist or doesn&rsquo;t parse reports <code>0x1</code>. The <code>catch</code> writes the error to the log:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">-NoProfile -Command &#34;try { &amp; &#39;C:\Scripts\job.ps1&#39; *&gt; C:\Scripts\logs\job.log } catch { $_ *&gt;&gt; C:\Scripts\logs\job.log; exit 1 }; exit $LASTEXITCODE&#34;</span></span></code></pre></div></div>
  </div>
</div><p>Create <code>C:\Scripts\logs</code> first, and make sure that the task&rsquo;s account can write to the folder. If the folder is missing or not writable, the script never runs, and the task still shows <code>0x0</code>.</p>
<p>Then check the usual causes:</p>
<ul>
<li>The task runs as a different account, with its own profile, module path and registry hive, and no mapped drives. Install modules in <code>C:\Program Files\WindowsPowerShell\Modules</code>, and use UNC paths.</li>
<li>A standard user&rsquo;s task with a stored password failed to start when the user lacked the <strong>Log on as a batch job</strong> right. The failed task showed <code>0x41303</code>, with an empty last run time. To confirm the cause, run <code>Get-WinEvent -FilterHashtable @{ LogName = 'Security'; Id = 4625 } -MaxEvents 5</code> in an elevated session. The fix, untested here, is to add the account to <strong>Log on as a batch job</strong> (Local Policies, User Rights Assignment).</li>
<li>Without a <strong>Start in</strong> value, the working directory is <code>C:\Windows\system32</code>. Set <strong>Start in</strong>, or build paths from <code>$PSScriptRoot</code>.</li>
<li>A script path that contains spaces fails when it isn&rsquo;t quoted. Quote the path: <code>-File &quot;C:\Scripts\My Scripts\job.ps1&quot;</code>.</li>
<li>Under <code>RemoteSigned</code>, the zone mark that Windows puts on a downloaded file blocks the script. Check <code>Get-ExecutionPolicy -List</code> and the script&rsquo;s <code>Zone.Identifier</code> stream. Run <code>Unblock-File</code> after you have read the script.</li>
<li>Without <code>-NonInteractive</code>, a <code>Read-Host</code> prompt leaves the task running. With <code>-NonInteractive</code>, the task quietly succeeds with an empty value. Take the prompt out of the script.</li>
</ul>

</div>

<p>I ran each of these failures on short-lived Windows Server 2025 test VMs, all built from the same image. I registered the tasks with <code>Register-ScheduledTask</code>, started them with <code>Start-ScheduledTask</code>, and read the Last Run Result back with <code>Get-ScheduledTaskInfo</code>. The failure runs used SYSTEM; the account and working-directory checks also ran as a local administrator, and the batch logon case as a standard user.</p>
<h2 id="success-is-reported-when-the-script-failed">Success is reported when the script failed<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#success-is-reported-when-the-script-failed"
     aria-label="Link to section: Success is reported when the script failed" data-pagefind-ignore></a>
</h2>
<p>Task Scheduler reports whether the process exited, not whether your script did its work. Each of these script endings gives the same Last Run Result in Windows PowerShell 5.1 and in PowerShell 7, with <code>-File</code> or <code>-Command</code>, run as SYSTEM. The first three fail and still show <code>0x0</code>:</p>
<div class="table-wrap" data-scrollable data-label="Table: Script ends with">
  <table>
    <thead>
      <tr><th scope="col">Script ends with</th><th scope="col">Last Run Result</th></tr>
    </thead>
    <tbody>
      <tr><td><code>Write-Error 'boom'</code>, then more output</td><td><code>0x0</code></td></tr>
      <tr><td><code>cmd.exe /c exit 5</code> as the last line</td><td><code>0x0</code></td></tr>
      <tr><td><code>Import-Module</code> of a module that doesn&rsquo;t exist, then a missing command</td><td><code>0x0</code></td></tr>
      <tr><td><code>throw &quot;boom&quot;</code></td><td><code>0x1</code></td></tr>
      <tr><td><code>exit 1</code></td><td><code>0x1</code></td></tr>
    </tbody>
  </table>
</div>
<p>The task history is no better. With history turned on, a task whose script ends with <code>exit 1</code> logs event 201 and event 102:</p>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Task</span> <span class="console__token">Scheduler</span> <span class="console__token">successfully</span> <span class="console__token">completed</span> <span class="console__token">task</span> <span class="console__token">&#34;\&lt;task-name&gt;&#34;</span> <span class="console__token">,</span> <span class="console__token">instance</span> <span class="console__token">&#34;{&lt;guid&gt;}&#34;</span> <span class="console__token">,</span> <span class="console__token">action</span> <span class="console__token">&#34;C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe&#34;</span> <span class="console__token">with</span> <span class="console__token">return</span> <span class="console__token">code</span> <span class="console__token">2147942401.</span>
</span><span class="line"><span class="console__token">Task</span> <span class="console__token">Scheduler</span> <span class="console__token">successfully</span> <span class="console__token">finished</span> <span class="console__token">&#34;{&lt;guid&gt;}&#34;</span> <span class="console__token">instance</span> <span class="console__token">of</span> <span class="console__token">the</span> <span class="console__token">&#34;\&lt;task-name&gt;&#34;</span> <span class="console__token">task</span> <span class="console__token">for</span> <span class="console__token">user</span> <span class="console__token">&#34;NT</span> <span class="console__token">AUTHORITY\SYSTEM&#34;.</span></span></code></pre>
    </div>
  </div></div><p>The return code <code>2147942401</code> is <code>0x80070001</code>, the exit code 1 in HRESULT form.</p>
<h2 id="make-the-failure-visible">Make the failure visible<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#make-the-failure-visible"
     aria-label="Link to section: Make the failure visible" data-pagefind-ignore></a>
</h2>
<p>Do this before you chase a cause. The first three ways in this section record or pass on what the script did; the fourth records only the exit code and run times, not the failure.</p>
<h3 id="pass-a-native-commands-exit-code-to-the-task">Pass a native command&rsquo;s exit code to the task<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#pass-a-native-commands-exit-code-to-the-task"
     aria-label="Link to section: Pass a native command’s exit code to the task" data-pagefind-ignore></a>
</h3>
<p>A task reads the process exit code, and a script that ends on a native command doesn&rsquo;t pass that command&rsquo;s code on. A script that ends with <code>cmd.exe /c exit 5</code> shows <code>0x0</code>. Add one line and the task shows <code>0x5</code> with <code>-File</code>, in both editions:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">cmd</span><span class="p">.</span><span class="py">exe</span> <span class="p">/</span><span class="n">c</span> <span class="n">exit</span> <span class="mf">5</span>
</span></span><span class="line"><span class="cl"><span class="n">exit</span> <span class="nv">$LASTEXITCODE</span></span></span></code></pre></div></div>
  </div>
</div><p>That holds for a <code>-File</code> action. Under <code>-Command</code>, when the last command is a script or an external program that exits with a code other than 0 or 1, PowerShell converts that code to 1. <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe" rel="external noopener" target="_blank">about_powershell_exe<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> says so, and <a href="https://looselydecoupled.com/powershell-file-vs-command-exit-code/">PowerShell -File vs. -Command: Which Exit Code Does the Caller Get?</a> measures it case by case. The same script shows <code>0x1</code> from <code>-Command &quot;&amp; 'job.ps1'&quot;</code>, and so does a script that ends with <code>exit 5</code>. End the action&rsquo;s own quotes with <code>; exit $LASTEXITCODE</code> and the task shows <code>0x5</code> in both editions, even when the script itself has no <code>exit</code> line.</p>
<p><code>$LASTEXITCODE</code> holds the code of the last native program, or of a script that ended with <code>exit</code>. A cmdlet never sets it; for why, see <a href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/">Why $LASTEXITCODE Doesn&rsquo;t Work the Way You Expect in PowerShell</a>.</p>
<h3 id="record-a-transcript-inside-the-script">Record a transcript inside the script<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#record-a-transcript-inside-the-script"
     aria-label="Link to section: Record a transcript inside the script" data-pagefind-ignore></a>
</h3>
<p>Put <code>Start-Transcript</code> first in the script. In my test, a script that ran <code>whoami</code>, a <code>Write-Error</code>, a failing <code>Import-Module</code> and a <code>throw</code> left a transcript that held the account (<code>nt authority\system</code>), both errors, and the <code>throw</code>. The task result was <code>0x1</code>. In Windows PowerShell 5.1, each error appears twice in the transcript.</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Start-Transcript</span> <span class="n">-Path</span> <span class="s1">&#39;C:\Scripts\logs\job-transcript.log&#39;</span>
</span></span><span class="line"><span class="cl"><span class="n">whoami</span></span></span></code></pre></div></div>
  </div>
</div><h3 id="redirect-all-output-from-the-action">Redirect all output from the action<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#redirect-all-output-from-the-action"
     aria-label="Link to section: Redirect all output from the action" data-pagefind-ignore></a>
</h3>
<p>If you can&rsquo;t edit the script, run it from a <code>-Command</code> action and redirect every stream to a file. A redirect creates the file but not a missing folder. If the folder is missing, or SYSTEM can&rsquo;t write to it, the script doesn&rsquo;t run at all, and the task still shows <code>0x0</code> in both editions, with or without the <code>try</code>. So create the folder first, make sure the task&rsquo;s account can write to it, and check that the log exists after the first run:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">New-Item</span> <span class="n">-ItemType</span> <span class="n">Directory</span> <span class="n">-Force</span> <span class="n">-Path</span> <span class="s1">&#39;C:\Scripts\logs&#39;</span></span></span></code></pre></div></div>
  </div>
</div><p>Then set the action&rsquo;s arguments:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">-NoProfile -Command &#34;try { &amp; &#39;C:\Scripts\job.ps1&#39; *&gt; C:\Scripts\logs\job.log } catch { $_ *&gt;&gt; C:\Scripts\logs\job.log; exit 1 }; exit $LASTEXITCODE&#34;</span></span></code></pre></div></div>
  </div>
</div><p>To register it from PowerShell, keep the arguments in a single-quoted here-string so nothing expands:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$arguments</span> <span class="p">=</span> <span class="sh">@&#39;
</span></span></span><span class="line"><span class="cl"><span class="sh">-NoProfile -Command &#34;try { &amp; &#39;C:\Scripts\job.ps1&#39; *&gt; C:\Scripts\logs\job.log } catch { $_ *&gt;&gt; C:\Scripts\logs\job.log; exit 1 }; exit $LASTEXITCODE&#34;
</span></span></span><span class="line"><span class="cl"><span class="sh">&#39;@</span>
</span></span><span class="line"><span class="cl"><span class="nv">$action</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskAction</span> <span class="n">-Execute</span> <span class="s1">&#39;powershell.exe&#39;</span> <span class="n">-Argument</span> <span class="nv">$arguments</span></span></span></code></pre></div></div>
  </div>
</div><p>Read the registered action back to confirm it:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="p">(</span><span class="nb">Get-ScheduledTask</span> <span class="n">-TaskName</span> <span class="s1">&#39;&lt;task-name&gt;&#39;</span><span class="p">).</span><span class="py">Actions</span><span class="p">.</span><span class="n">Arguments</span></span></span></code></pre></div></div>
  </div>
</div><p>Leave <code>; exit $LASTEXITCODE</code> off the end of the action&rsquo;s arguments, and a plain <code>&amp; 'script' *&gt; log</code> action shows <code>0x1</code>, even when the script itself ends with <code>exit $LASTEXITCODE</code> after a native code of 5. With it in the arguments, the task shows <code>0x5</code>. If the script writes a non-terminating error and carries on, the Last Run Result stays <code>0x0</code>, and the log holds the error and the line that comes after it. The redirect shows the failure; it doesn&rsquo;t change the result.</p>
<p>The <code>try</code> is there for a script that stops on an error or never starts. Without the <code>try</code>/<code>catch</code>, four failures go wrong. A script path that doesn&rsquo;t exist and a script with a syntax error each show <code>0x0</code>, because no native command has set a code, and neither creates a log file. A script that prints a line and then hits a <code>throw</code> or an <code>-ErrorAction Stop</code> error shows <code>0x1</code>, but its log holds only the printed line, not the error. With the <code>catch</code> writing <code>$_</code> (the error it caught) to the log, all four show <code>0x1</code> in both editions. Each log holds the error: the <code>throw</code> message, <code>Cannot find path</code>, the parse error, or <code>The term ... is not recognized</code>. The earlier results don&rsquo;t change.</p>
<h3 id="turn-on-task-history">Turn on task history<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#turn-on-task-history"
     aria-label="Link to section: Turn on task history" data-pagefind-ignore></a>
</h3>
<p>On the fresh image I tested, the <code>Microsoft-Windows-TaskScheduler/Operational</code> log was disabled, so a failed task left no history at all. This changes the event log configuration of the machine. In an elevated session, run:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">wevtutil</span> <span class="nb">set-log</span> <span class="nb">Microsoft-Windows</span><span class="n">-TaskScheduler</span><span class="p">/</span><span class="n">Operational</span> <span class="p">/</span><span class="n">enabled</span><span class="err">:</span><span class="n">true</span></span></span></code></pre></div></div>
  </div>
</div><p>After that, registering and running one task logged event 106 (registered), then 325 (queued), 110 (launched), 129 (launched process), 100 (started), 200 (launched action), and then 201 and 102 as shown earlier.</p>
<h2 id="read-the-last-run-result">Read the last run result<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#read-the-last-run-result"
     aria-label="Link to section: Read the last run result" data-pagefind-ignore></a>
</h2>
<p>Find your code in the table. The meanings are what each value meant in these tests, not a full list.</p>
<div class="table-wrap" data-scrollable data-label="Table: Last Run Result">
  <table>
    <thead>
      <tr><th scope="col">Last Run Result</th><th scope="col">What it meant in these tests</th></tr>
    </thead>
    <tbody>
      <tr><td><code>0x0</code></td><td>The process exited with code 0. The script might still have failed (see the table earlier).</td></tr>
      <tr><td><code>0x1</code></td><td><code>throw</code>, <code>exit 1</code>, a script blocked by its zone mark, or any other non-zero exit code from a script that a <code>-Command</code> action calls with <code>&amp;</code> (a script that ended with <code>exit 5</code> gives this; see &ldquo;Pass a native command&rsquo;s exit code to the task&rdquo;). A <code>-Command</code> action wrapped in <code>try</code>/<code>catch</code> also gives <code>0x1</code> for a missing script or one that doesn&rsquo;t parse.</td></tr>
      <tr><td><code>0x5</code></td><td><code>exit $LASTEXITCODE</code> after a native command that exited with 5.</td></tr>
      <tr><td><code>0x41303</code></td><td>The task has not yet run. A standard user&rsquo;s task showed this and never started.</td></tr>
      <tr><td><code>0x41301</code></td><td>The task is running. A script waiting on <code>Read-Host</code> stayed here.</td></tr>
      <tr><td><code>0x41306</code></td><td>The task was stopped while running, by hand or by its execution time limit. A script waiting for input showed this both ways.</td></tr>
      <tr><td><code>0xFFFD0000</code></td><td>Windows PowerShell 5.1 could not find the <code>-File</code> script: the path doesn&rsquo;t exist, or it contains a space and isn&rsquo;t quoted.</td></tr>
      <tr><td><code>0x40</code></td><td>PowerShell 7 could not find the <code>-File</code> script: the path doesn&rsquo;t exist, or it contains a space and isn&rsquo;t quoted.</td></tr>
    </tbody>
  </table>
</div>
<p>To read the value, and the time of the last run:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-ScheduledTaskInfo</span> <span class="n">-TaskName</span> <span class="s1">&#39;&lt;task-name&gt;&#39;</span> <span class="n">-TaskPath</span> <span class="s1">&#39;\&#39;</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Select-Object</span> <span class="n">LastRunTime</span><span class="p">,</span> <span class="vm">@</span><span class="p">{</span> <span class="n">Name</span> <span class="p">=</span> <span class="s1">&#39;LastTaskResult&#39;</span><span class="p">;</span> <span class="n">Expression</span> <span class="p">=</span> <span class="p">{</span> <span class="s1">&#39;0x{0:X}&#39;</span> <span class="o">-f</span> <span class="nv">$_</span><span class="p">.</span><span class="py">LastTaskResult</span> <span class="p">}</span> <span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>Change <code>-TaskPath</code> if the task is in a subfolder.</p>
<h2 id="check-a-task-with-a-coding-agent">Check a task with a coding agent<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#check-a-task-with-a-coding-agent"
     aria-label="Link to section: Check a task with a coding agent" data-pagefind-ignore></a>
</h2>
<p>Paste this into your own local coding agent, with the task name filled in. It reads the task and reports against the checklist in this article. It changes nothing and doesn&rsquo;t start the task.</p>
<div class="code-block" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">You are checking one Windows scheduled task. Read only. Do not change anything:
</span></span><span class="line"><span class="cl">no Set-ScheduledTask, no Register-ScheduledTask, no wevtutil set-log, no edits
</span></span><span class="line"><span class="cl">to the script, no policy changes. Do not start, stop or enable the task, and do
</span></span><span class="line"><span class="cl">not run the script.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Task name: &lt;task-name&gt;
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">1. Run Get-ScheduledTask and Get-ScheduledTaskInfo for the task. Report:
</span></span><span class="line"><span class="cl">   - the principal: user, logon type and run level
</span></span><span class="line"><span class="cl">   - the action: executable, arguments and the Start in (working directory)
</span></span><span class="line"><span class="cl">   - Last Run Result (as hex) and last run time
</span></span><span class="line"><span class="cl">2. Report whether the log Microsoft-Windows-TaskScheduler/Operational is
</span></span><span class="line"><span class="cl">   enabled. If it is disabled, say so and propose the command to enable it as
</span></span><span class="line"><span class="cl">   text. Do not run it.
</span></span><span class="line"><span class="cl">3. If the principal is a user and not SYSTEM, report whether that account
</span></span><span class="line"><span class="cl">   holds the &#34;Log on as a batch job&#34; right (SeBatchLogonRight), directly or
</span></span><span class="line"><span class="cl">   through a group. Use a read-only method.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Then compare each finding with this checklist and say which items apply:
</span></span><span class="line"><span class="cl">- 0x1: the script threw, called exit 1, or is blocked. Read the script path
</span></span><span class="line"><span class="cl">  from the action and check it with
</span></span><span class="line"><span class="cl">  Get-Item -LiteralPath &lt;path&gt; -Stream Zone.Identifier -ErrorAction SilentlyContinue.
</span></span><span class="line"><span class="cl">  A ZoneId=3 stream under a RemoteSigned policy is the blocked-script cause.
</span></span><span class="line"><span class="cl">  Do not run Unblock-File; propose it as text.
</span></span><span class="line"><span class="cl">- Last Run Result 0x0 does not prove success. Errors that do not terminate,
</span></span><span class="line"><span class="cl">  a failed Import-Module and a native command&#39;s exit code all leave 0x0.
</span></span><span class="line"><span class="cl">  The script should write a transcript or the action should redirect output
</span></span><span class="line"><span class="cl">  to a file, and the script should end with exit $LASTEXITCODE.
</span></span><span class="line"><span class="cl">- The action uses -Command and calls a script with &amp;: any exit code other
</span></span><span class="line"><span class="cl">  than 0 or 1 from that script reaches the task as 0x1 unless the action&#39;s own quotes end with ; exit $LASTEXITCODE.
</span></span><span class="line"><span class="cl">  If they do, the call should sit inside try { } catch { $_ *&gt;&gt; &lt;log&gt;;
</span></span><span class="line"><span class="cl">  exit 1 }, or a script that is missing or doesn&#39;t parse reaches the task
</span></span><span class="line"><span class="cl">  as 0x0, and an error that stops the script never reaches the log.
</span></span><span class="line"><span class="cl">- The action redirects to a log file that doesn&#39;t exist after the task ran:
</span></span><span class="line"><span class="cl">  the script never ran, whatever the Last Run Result says. Check that the
</span></span><span class="line"><span class="cl">  folder exists and the task&#39;s account can write to it, then that the script
</span></span><span class="line"><span class="cl">  path exists and the script parses. Without a catch that writes $_ to the
</span></span><span class="line"><span class="cl">  log, a missing script or a syntax error also leaves no log.
</span></span><span class="line"><span class="cl">- 0x41303 with no last run time: the task never started. For a non-SYSTEM
</span></span><span class="line"><span class="cl">  user whose task stores a password, a missing batch logon right is the
</span></span><span class="line"><span class="cl">  cause found in these tests.
</span></span><span class="line"><span class="cl">- 0x41301 for a long time: the script may be waiting on Read-Host.
</span></span><span class="line"><span class="cl">- 0xFFFD0000 (Windows PowerShell 5.1) or 0x40 (PowerShell 7): the -File
</span></span><span class="line"><span class="cl">  script was not found: the path doesn&#39;t exist, or it contains a space and
</span></span><span class="line"><span class="cl">  isn&#39;t quoted in the arguments.
</span></span><span class="line"><span class="cl">- Start in empty: the working directory is C:\Windows\system32.
</span></span><span class="line"><span class="cl">- The principal differs from the account the script was tested as: profile,
</span></span><span class="line"><span class="cl">  module path, registry hive and mapped drives differ. Mapped drives do not
</span></span><span class="line"><span class="cl">  carry from one task to the next.
</span></span><span class="line"><span class="cl">- The action&#39;s executable is powershell.exe or pwsh.exe: the two editions
</span></span><span class="line"><span class="cl">  read different module folders.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Report each finding, then propose each fix as text for me to review.</span></span></code></pre></div></div>
  </div>
</div><h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="module-drive-or-setting-missing-under-the-task">Module, drive or setting missing under the task<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#module-drive-or-setting-missing-under-the-task"
     aria-label="Link to section: Module, drive or setting missing under the task" data-pagefind-ignore></a>
</h3>
<p>The task runs as a different account, and each account has its own profile, registry hive and module folders. I read these from a probe script that ran as a task in each context:</p>
<div class="table-wrap" data-scrollable data-label="Table: Task runs as">
  <table>
    <thead>
      <tr><th scope="col">Task runs as</th><th scope="col">Profile folder</th><th scope="col">Current directory</th><th scope="col"><code>HKCU</code> value set by the admin</th><th scope="col">Module installed for the current user in 5.1</th></tr>
    </thead>
    <tbody>
      <tr><td>SYSTEM, Windows PowerShell 5.1</td><td><code>C:\Windows\system32\config\systemprofile</code></td><td><code>C:\Windows\system32</code></td><td>not found</td><td>not found</td></tr>
      <tr><td>SYSTEM, PowerShell 7</td><td><code>C:\Windows\system32\config\systemprofile</code></td><td><code>C:\Windows\System32</code></td><td>not found</td><td>not found</td></tr>
      <tr><td>Local administrator, 5.1</td><td><code>C:\Users\&lt;user&gt;</code></td><td><code>C:\Windows\system32</code></td><td>found</td><td>found</td></tr>
      <tr><td>Local administrator, PowerShell 7</td><td><code>C:\Users\&lt;user&gt;</code></td><td><code>C:\Windows\System32</code></td><td>found</td><td>not found</td></tr>
    </tbody>
  </table>
</div>
<p>Three things follow:</p>
<ul>
<li><strong>SYSTEM has no Documents folder.</strong> The first entry on SYSTEM&rsquo;s <code>PSModulePath</code> in 5.1 is the relative path <code>WindowsPowerShell\Modules</code>.</li>
<li><strong>A module is tied to an edition and a user.</strong> That user&rsquo;s 5.1 task finds a module installed for the current user in 5.1 (<code>Documents\WindowsPowerShell\Modules</code>). The same user&rsquo;s PowerShell 7 task doesn&rsquo;t, and neither does SYSTEM in either edition. <code>C:\Program Files\WindowsPowerShell\Modules</code> is on every list, so install there for a task. For the steps, see <a href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/">Install AWS Tools for PowerShell for All Users on Windows</a>.</li>
<li><strong>A mapped drive doesn&rsquo;t carry over.</strong> I mapped <code>Z:</code> with <code>net use Z: \\localhost\tsshare /persistent:yes</code> inside one task. It was gone in every later task, including a later task of the same user, although that user&rsquo;s <code>HKCU:\Network\Z</code> entry was still present. Use UNC paths (<code>\\server\share</code>) in the script. I didn&rsquo;t test share access from a task account, so confirm that the account can read the share.</li>
</ul>
<p>In my tests, <strong>Run with highest privileges</strong> didn&rsquo;t change the group list or integrity level of the task&rsquo;s process, for a task registered with a stored password. The integrity level is the trust level Windows gives a process. <code>whoami /groups</code> showed the same groups and the same <code>High Mandatory Level</code> with the setting off and on. I didn&rsquo;t test &ldquo;Run only when user is logged on&rdquo; or S4U logons (the &ldquo;Do not store password&rdquo; option), so do not assume it holds there.</p>
<h3 id="standard-users-task-never-starts-and-shows-0x41303">Standard user&rsquo;s task never starts and shows 0x41303<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#standard-users-task-never-starts-and-shows-0x41303"
     aria-label="Link to section: Standard user’s task never starts and shows 0x41303" data-pagefind-ignore></a>
</h3>
<p>The task registers without an error, <code>Start-ScheduledTask</code> returns, and nothing happens. The Last Run Result is <code>0x41303</code>, the last run time is empty and the script leaves no output. On my test machine the Operational log held nothing, because it was disabled.</p>
<p>The cause shows up in the Security log: the standard user (a member of Users only) isn&rsquo;t allowed to log on as a batch job. On my test machine, Administrators, Backup Operators and Performance Log Users held the right. Two events of ID 4625 recorded it:</p>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Logon</span> <span class="console__token">Type:</span> <span class="console__token">4</span>
</span><span class="line"><span class="console__token">Account</span> <span class="console__token">Name:</span> <span class="console__token">&lt;user&gt;</span>
</span><span class="line"><span class="console__token">The</span> <span class="console__token">user</span> <span class="console__token">has</span> <span class="console__token">not</span> <span class="console__token">been</span> <span class="console__token">granted</span> <span class="console__token">the</span> <span class="console__token">requested</span> <span class="console__token">logon</span> <span class="console__token">type</span> <span class="console__token">at</span> <span class="console__token">this</span> <span class="console__token">machine.</span>
</span><span class="line"><span class="console__token">Status:</span> <span class="console__token">0xC000015B</span></span></code></pre>
    </div>
  </div></div><p>To look for them, in an elevated session:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-WinEvent</span> <span class="n">-FilterHashtable</span> <span class="vm">@</span><span class="p">{</span> <span class="n">LogName</span> <span class="p">=</span> <span class="s1">&#39;Security&#39;</span><span class="p">;</span> <span class="n">Id</span> <span class="p">=</span> <span class="mf">4625</span> <span class="p">}</span> <span class="n">-MaxEvents</span> <span class="mf">5</span></span></span></code></pre></div></div>
  </div>
</div><p>The right is named <strong>Log on as a batch job</strong> (<code>SeBatchLogonRight</code>). Per <a href="https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-10/security/threat-protection/security-policy-settings/log-on-as-a-batch-job" rel="external noopener" target="_blank">Microsoft&rsquo;s documentation of the setting<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>, it lives under Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment. A change takes effect the next time the account logs on. The same page says that when the Add Scheduled Task Wizard sets up a task with a user name and password, the user gets the right automatically, and that domain-based Group Policy for the right prevents that. I registered my task with <code>Register-ScheduledTask</code> and a stored password, not with the wizard, and the account didn&rsquo;t get the right. I didn&rsquo;t test the wizard. The accounts were local, and I didn&rsquo;t examine Group Policy on the machine. The fix is to add the account to <strong>Log on as a batch job</strong> (Local Policies, User Rights Assignment). I didn&rsquo;t test granting the right, so confirm the result by starting the task afterwards and reading the Last Run Result.</p>
<h3 id="relative-paths-resolve-to-the-wrong-folder">Relative paths resolve to the wrong folder<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#relative-paths-resolve-to-the-wrong-folder"
     aria-label="Link to section: Relative paths resolve to the wrong folder" data-pagefind-ignore></a>
</h3>
<p>Without a <strong>Start in</strong> value, the working directory is <code>C:\Windows\system32</code> in both editions, for SYSTEM and for the local administrator, so a relative path resolves there. Set <strong>Start in</strong> to <code>C:\ts</code> and the working directory is <code>C:\ts</code> in both. <code>$PSScriptRoot</code> holds the running script&rsquo;s own folder in every context, with or without <strong>Start in</strong>, so build paths from it:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$logPath</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$PSScriptRoot</span> <span class="s1">&#39;job.log&#39;</span></span></span></code></pre></div></div>
  </div>
</div><p>For a task registered in PowerShell, the <code>-WorkingDirectory</code> parameter of <code>New-ScheduledTaskAction</code> sets <strong>Start in</strong>. The <a href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/">Start a 7 Days to Die Dedicated Server at Boot on Windows and Stop It Cleanly</a> registers a task that way.</p>
<h3 id="script-path-not-found-or-unquoted-gives-0xfffd0000-or-0x40">Script path not found or unquoted gives 0xFFFD0000 or 0x40<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#script-path-not-found-or-unquoted-gives-0xfffd0000-or-0x40"
     aria-label="Link to section: Script path not found or unquoted gives 0xFFFD0000 or 0x40" data-pagefind-ignore></a>
</h3>
<p>A <code>-File</code> path that doesn&rsquo;t exist at all gives the same two exit codes. The case I tested here is a path that contains a space with the <code>-File</code> argument unquoted. With <code>-File C:\ts\My Scripts\ok.ps1</code>, Windows PowerShell 5.1 shows <code>0xFFFD0000</code> and PowerShell 7 shows <code>0x40</code>. The console messages differ. Windows PowerShell 5.1 prints:</p>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Processing</span> <span class="console__token">-File</span> <span class="console__token">&#39;C:\ts\My&#39;</span> <span class="console__token">failed</span> <span class="console__token">because</span> <span class="console__token">the</span> <span class="console__token">file</span> <span class="console__token">does</span> <span class="console__token">not</span> <span class="console__token">have</span> <span class="console__token">a</span> <span class="console__token">&#39;.ps1&#39;</span> <span class="console__token">extension.</span> <span class="console__token">Specify</span> <span class="console__token">a</span> <span class="console__token">valid</span> <span class="console__token">Windows</span> <span class="console__token">PowerShell</span> <span class="console__token">script</span> <span class="console__token">file</span> <span class="console__token">name,</span> <span class="console__token">and</span> <span class="console__token">then</span> <span class="console__token">try</span> <span class="console__token">again.</span></span></code></pre>
    </div>
  </div></div><p>PowerShell 7 prints:</p>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">The</span> <span class="console__token">argument</span> <span class="console__token">&#39;C:\ts\My&#39;</span> <span class="console__token">is</span> <span class="console__token">not</span> <span class="console__token">recognized</span> <span class="console__token">as</span> <span class="console__token">the</span> <span class="console__token">name</span> <span class="console__token">of</span> <span class="console__token">a</span> <span class="console__token">script</span> <span class="console__token">file.</span> <span class="console__token">Check</span> <span class="console__token">the</span> <span class="console__token">spelling</span> <span class="console__token">of</span> <span class="console__token">the</span> <span class="console__token">name,</span> <span class="console__token">or</span> <span class="console__token">if</span> <span class="console__token">a</span> <span class="console__token">path</span> <span class="console__token">was</span> <span class="console__token">included,</span> <span class="console__token">verify</span> <span class="console__token">that</span> <span class="console__token">the</span> <span class="console__token">path</span> <span class="console__token">is</span> <span class="console__token">correct</span> <span class="console__token">and</span> <span class="console__token">try</span> <span class="console__token">again.</span></span></code></pre>
    </div>
  </div></div><p>Quote the path in the action&rsquo;s arguments. <code>-File &quot;C:\ts\My Scripts\ok.ps1&quot;</code> gives <code>0x0</code> on both:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">-NoProfile -File &#34;C:\Scripts\My Scripts\job.ps1&#34;</span></span></code></pre></div></div>
  </div>
</div><h3 id="downloaded-script-is-blocked-and-gives-0x1">Downloaded script is blocked and gives 0x1<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#downloaded-script-is-blocked-and-gives-0x1"
     aria-label="Link to section: Downloaded script is blocked and gives 0x1" data-pagefind-ignore></a>
</h3>
<p>A script that carries a <code>Zone.Identifier</code> stream with <code>ZoneId=3</code> fails with <code>0x1</code> under the <code>RemoteSigned</code> policy, in both editions and with both <code>-File</code> and <code>-Command</code>. The same content without the stream gives <code>0x0</code>, which is the control. Windows PowerShell 5.1 prints the message below; PowerShell 7 prints the same text after <code>SecurityError:</code>.</p>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">File</span> <span class="console__token">C:\ts\f\zoned.ps1</span> <span class="console__token">cannot</span> <span class="console__token">be</span> <span class="console__token">loaded.</span> <span class="console__token">The</span> <span class="console__token">file</span> <span class="console__token">C:\ts\f\zoned.ps1</span> <span class="console__token">is</span> <span class="console__token">not</span> <span class="console__token">digitally</span> <span class="console__token">signed.</span> <span class="console__token">You</span> <span class="console__token">cannot</span> <span class="console__token">run</span> <span class="console__token">this</span> <span class="console__token">script</span> <span class="console__token">on</span> <span class="console__token">the</span> <span class="console__token">current</span> <span class="console__token">system.</span></span></code></pre>
    </div>
  </div></div><p>The test image shipped Windows PowerShell 5.1 with the <code>LocalMachine</code> policy set to <code>Unrestricted</code>, which warns before it runs a downloaded file rather than refusing it. I didn&rsquo;t test a zoned script under it. I set it to <code>RemoteSigned</code> first, which per <code>about_Execution_Policies</code> is the Windows Server default.</p>
<p>To check whether a script carries the mark:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-Item</span> <span class="n">-LiteralPath</span> <span class="s1">&#39;C:\Scripts\job.ps1&#39;</span> <span class="n">-Stream</span> <span class="n">Zone</span><span class="p">.</span><span class="py">Identifier</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span></span></span></code></pre></div></div>
  </div>
</div><p>Only if the stream is present and you have read the script:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Unblock-File</span> <span class="n">-LiteralPath</span> <span class="s1">&#39;C:\Scripts\job.ps1&#39;</span></span></span></code></pre></div></div>
  </div>
</div><p><code>Unblock-File</code> removes the <code>Zone.Identifier</code> stream, per <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/unblock-file" rel="external noopener" target="_blank">its documentation<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>. I didn&rsquo;t run it in these tests.</p>
<h3 id="task-stays-running-or-finishes-with-nothing">Task stays running, or finishes with nothing<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#task-stays-running-or-finishes-with-nothing"
     aria-label="Link to section: Task stays running, or finishes with nothing" data-pagefind-ignore></a>
</h3>
<p>Both outcomes come from the same cause: the script was written for a person at a prompt. With a <code>Read-Host</code> line, the task is still in State Running (<code>0x41301</code>) after 30 seconds, in both editions. The default execution time limit of a settings set from <code>New-ScheduledTaskSettingsSet</code> is 72 hours (<code>PT72H</code>), so the task can stay that way for days. When I stopped the stuck task after 30 seconds, its Last Run Result became <code>0x41306</code>.</p>
<p>Adding <code>-NonInteractive</code> to the action changes the failure and hides it. The task finishes in under 30 seconds with <code>0x0</code>, and the output file reads <code>answered: </code> with nothing after it. The error ends only that statement, not the script, so the script carried on with an empty value:</p>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Read-Host</span> <span class="console__token">:</span> <span class="console__token">Windows</span> <span class="console__token">PowerShell</span> <span class="console__token">is</span> <span class="console__token">in</span> <span class="console__token">NonInteractive</span> <span class="console__token">mode.</span> <span class="console__token">Read</span> <span class="console__token">and</span> <span class="console__token">Prompt</span> <span class="console__token">functionality</span> <span class="console__token">is</span> <span class="console__token">not</span> <span class="console__token">available.</span></span></code></pre>
    </div>
  </div></div><p>Take the prompt out of the script, and pass what it asked for as a parameter or a value in the script. Do not use <code>-NonInteractive</code> to make a prompt go away.</p>
<h2 id="what-these-tests-did-not-cover">What these tests did not cover<a class="heading-anchor" href="https://looselydecoupled.com/powershell-script-works-manually-fails-task-scheduler/#what-these-tests-did-not-cover"
     aria-label="Link to section: What these tests did not cover" data-pagefind-ignore></a>
</h2>
<p>The numbers in this article come from short-lived test VMs of one Windows Server 2025 image, and they are not a general result.</p>
<ul>
<li><strong>Not tested:</strong> &ldquo;Run only when user is logged on&rdquo;, &ldquo;Do not store password&rdquo; (S4U), domain accounts and group managed service accounts, network share access as SYSTEM or as a user, and arguments passed to the script from the action.</li>
<li><strong>Not tested:</strong> Windows Server 2022 and Windows 11.</li>
<li><strong>Not tested:</strong> the fix for the batch logon right, and the fix for the blocked script.</li>
</ul>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2025 Datacenter 24H2, build 26100.33650</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>Windows PowerShell 5.1.26100.33648 and PowerShell 7.6.8</dd></div>
    <div class="tested__row"><dt>Accounts</dt> <dd>Local administrator and local standard user, stored-password logon, plus SYSTEM</dd></div>
    <div class="tested__row"><dt>Execution policy</dt> <dd>LocalMachine set to RemoteSigned for the failure runs</dd></div>
    <div class="tested__row"><dt>Redirect wrapper</dt> <dd>Rerun on build 26100.33674 with PowerShell 7.6.9, as SYSTEM</dd></div>
    <div class="tested__row"><dt>Missing -File script</dt> <dd>Build 26100.33674 with PowerShell 7.6.9, as SYSTEM</dd></div>
    <div class="tested__row"><dt>Not tested</dt> <dd>Logged-on-only and S4U logons, domain accounts, network shares, Windows Server 2022, Windows 11</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>October 2026</dd></div>
  </dl>
</div>
]]></content:encoded>
    </item>
    
    <item>
      <title>Start a 7 Days to Die Dedicated Server at Boot on Windows and Stop It Cleanly</title>
      <link>https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/</guid>
      <pubDate>Fri, 02 Oct 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>Game servers</category>
      <category>PowerShell</category>
      <category>Unattended</category>
      
      <description>Run a 7 Days to Die server from a Windows scheduled task with no time limit, and stop it over telnet so the shutdown finishes and the world is saved.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>Register a scheduled task with four settings. Its action is the server executable itself. Its trigger is at startup. It runs as the SYSTEM account. Its execution time limit is zero. Stop the server with its telnet <code>shutdown</code> command. The server accepts that command on <code>127.0.0.1:8081</code> by default.</p>
<p>The telnet stop lets the server finish its shutdown. The server process then exited with code <code>0</code> and wrote every save file. <code>Stop-ScheduledTask</code> ends the process from outside in about a second, with exit code <code>1067</code>. On V 3.2, that stop cut the save short and wrote about half the files. On V 3.4, the same stop wrote all the files, in a new world nobody was playing. The task&rsquo;s default time limit is 72 hours. After that, Task Scheduler ends the server the same way.</p>
<p>Run the next code in an elevated PowerShell on the server. Your config file (<code>myserver.xml</code> here) must be in the install folder, with <code>UserDataFolder</code> set in it:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$dir</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$log</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$dir</span> <span class="s1">&#39;output_log.txt&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$flags</span> <span class="p">=</span> <span class="s1">&#39;-quit -batchmode -nographics -configfile=myserver.xml -dedicated&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$arguments</span> <span class="p">=</span> <span class="s2">&#34;-logfile </span><span class="se">`&#34;</span><span class="nv">$log</span><span class="se">`&#34;</span><span class="s2"> </span><span class="nv">$flags</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$action</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskAction</span> <span class="n">-Execute</span> <span class="p">(</span><span class="nb">Join-Path</span> <span class="nv">$dir</span> <span class="s1">&#39;7DaysToDieServer.exe&#39;</span><span class="p">)</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Argument</span> <span class="nv">$arguments</span> <span class="n">-WorkingDirectory</span> <span class="nv">$dir</span>
</span></span><span class="line"><span class="cl"><span class="nv">$trigger</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskTrigger</span> <span class="n">-AtStartup</span>
</span></span><span class="line"><span class="cl"><span class="nv">$settings</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskSettingsSet</span> <span class="n">-ExecutionTimeLimit</span> <span class="p">([</span><span class="no">TimeSpan</span><span class="p">]::</span><span class="n">Zero</span><span class="p">)</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-AllowStartIfOnBatteries</span> <span class="n">-DontStopIfGoingOnBatteries</span>
</span></span><span class="line"><span class="cl"><span class="nb">Register-ScheduledTask</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServer&#39;</span> <span class="n">-Action</span> <span class="nv">$action</span> <span class="n">-Trigger</span> <span class="nv">$trigger</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Settings</span> <span class="nv">$settings</span> <span class="n">-User</span> <span class="s1">&#39;SYSTEM&#39;</span> <span class="n">-RunLevel</span> <span class="n">Highest</span></span></span></code></pre></div></div>
  </div>
</div><p><code>Start-ScheduledTask -TaskName 7DaysToDieServer</code> starts the server. The <code>Stop-GameServer</code> function in step 4 stops it. The game-specific parts are the server&rsquo;s flags, its ready line, and telnet as the way to stop it.</p>
<p>The test server wasn&rsquo;t restarted. The at-startup trigger is confirmed to be registered, not confirmed to fire. Step 5 has the check to run after your first reboot.</p>

</div>

<p><a href="https://looselydecoupled.com/configure-7-days-to-die-server-and-open-ports/">Configure a 7 Days to Die Dedicated Server and Open Its Ports</a> left a server you start by hand. This part makes Windows start it when the machine boots, keep it running, and stop it without losing the world.</p>
<!-- style-check: procedure -->
<h2 id="1-register-the-task">1. Register the task<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#1-register-the-task"
     aria-label="Link to section: 1. Register the task" data-pagefind-ignore></a>
</h2>
<p>The task runs the server executable directly. Nothing wraps it, so the task&rsquo;s state says whether the server is running, and stopping the task stops the server.</p>
<p>The configuration article&rsquo;s <code>UserDataFolder</code> setting matters here. SYSTEM has its own profile, separate from yours. Without that setting, a server that runs as SYSTEM writes its world under that profile, at <code>C:\Windows\System32\config\systemprofile\AppData\Roaming\7DaysToDie</code>. Check that your <code>myserver.xml</code> has it set before you register the task.</p>
<p>This registers the task:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$dir</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$log</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$dir</span> <span class="s1">&#39;output_log.txt&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$flags</span> <span class="p">=</span> <span class="s1">&#39;-quit -batchmode -nographics -configfile=myserver.xml -dedicated&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$arguments</span> <span class="p">=</span> <span class="s2">&#34;-logfile </span><span class="se">`&#34;</span><span class="nv">$log</span><span class="se">`&#34;</span><span class="s2"> </span><span class="nv">$flags</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$action</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskAction</span> <span class="n">-Execute</span> <span class="p">(</span><span class="nb">Join-Path</span> <span class="nv">$dir</span> <span class="s1">&#39;7DaysToDieServer.exe&#39;</span><span class="p">)</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Argument</span> <span class="nv">$arguments</span> <span class="n">-WorkingDirectory</span> <span class="nv">$dir</span>
</span></span><span class="line"><span class="cl"><span class="nv">$trigger</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskTrigger</span> <span class="n">-AtStartup</span>
</span></span><span class="line"><span class="cl"><span class="nv">$settings</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskSettingsSet</span> <span class="n">-ExecutionTimeLimit</span> <span class="p">([</span><span class="no">TimeSpan</span><span class="p">]::</span><span class="n">Zero</span><span class="p">)</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-AllowStartIfOnBatteries</span> <span class="n">-DontStopIfGoingOnBatteries</span>
</span></span><span class="line"><span class="cl"><span class="nb">Register-ScheduledTask</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServer&#39;</span> <span class="n">-Action</span> <span class="nv">$action</span> <span class="n">-Trigger</span> <span class="nv">$trigger</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Settings</span> <span class="nv">$settings</span> <span class="n">-User</span> <span class="s1">&#39;SYSTEM&#39;</span> <span class="n">-RunLevel</span> <span class="n">Highest</span></span></span></code></pre></div></div>
  </div>
</div><p>What each part does:</p>
<ul>
<li><code>-WorkingDirectory</code> sets the folder the server starts in. The server found <code>myserver.xml</code> next to its executable without it, so this is a precaution and not a requirement.</li>
<li><code>-AtStartup</code> runs the task when Windows starts, before anyone logs on.</li>
<li><code>-User 'SYSTEM'</code> with <code>-RunLevel Highest</code> runs it as the SYSTEM account, with no password to store. SYSTEM has machine-wide rights, so a flaw in the server or a mod it loads would have them too. If players you don&rsquo;t trust can reach the server, register the task under a dedicated local account that can write only to the install folder. I didn&rsquo;t test that.</li>
<li><code>-ExecutionTimeLimit ([TimeSpan]::Zero)</code> turns the time limit off. The next step shows why that is the setting to get right.</li>
<li><code>-AllowStartIfOnBatteries</code> and <code>-DontStopIfGoingOnBatteries</code> turn off two defaults that exist for laptops. Both are on by default, and a virtual machine has no battery, so these are harmless there.</li>
</ul>
<p><code>Register-ScheduledTask</code> prints an error if the name already exists, and leaves the first task as it was. Running the block twice is harmless. To change a task, remove it with <code>Unregister-ScheduledTask -TaskName '7DaysToDieServer' -Confirm:$false</code> and register it again.</p>
<p>Read the settings back:</p>
<div class="console"><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">$task</span> <span class="console__token">=</span> <span class="console__token">Get-ScheduledTask</span> <span class="console__token">-TaskName</span> <span class="console__token">&#39;7DaysToDieServer&#39;</span>
</span><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">$task.Settings.ExecutionTimeLimit</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">PT0S</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">$task.Triggers[0].CimClass.CimClassName</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">MSFT_TaskBootTrigger</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">$task.Principal.UserId</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">SYSTEM</span></span></code></pre>
    </div>
  </div></div><p><code>PT0S</code> is how Task Scheduler stores no limit.</p>
<h2 id="2-turn-off-the-72-hour-execution-time-limit">2. Turn off the 72-hour execution time limit<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#2-turn-off-the-72-hour-execution-time-limit"
     aria-label="Link to section: 2. Turn off the 72-hour execution time limit" data-pagefind-ignore></a>
</h2>
<p>A task registered with no settings read back <code>PT72H</code>. Task Scheduler ends a task that runs longer than its limit, and a game server is meant to run for weeks.</p>
<p>To see what it does to the server, I registered the same task with a limit of two minutes and started it. The server ran until the limit, and Task Scheduler then ended it, about 123 seconds after the start. The task went back to <code>Ready</code> with a last result of <code>267014</code>, which is Task Scheduler&rsquo;s code for a task that was terminated. The limit ends the process the same way <code>Stop-ScheduledTask</code> does in step 4, from outside and with exit code <code>1067</code>, which is not a clean stop.</p>
<p>A longer limit only moves that moment. With <code>PT72H</code> the server would have been stopped three days after each start, and nothing would have restarted it. The <code>-ExecutionTimeLimit ([TimeSpan]::Zero)</code> in step 1 turns the limit off.</p>
<p>There is a second way to build this task, and I tested it too. The action starts a small script that launches the server detached, with <code>Start-Process</code>, and exits. The task then finishes in seconds, and the limit never applies. With a two-minute limit the server was still running after more than three minutes, the task itself had finished within seconds, and <code>Stop-ScheduledTask</code> left the server running. That design needs the telnet stop in step 4 anyway. I used the direct task because its state says whether the server is running.</p>
<h2 id="3-start-the-task-and-wait-for-the-server">3. Start the task and wait for the server<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#3-start-the-task-and-wait-for-the-server"
     aria-label="Link to section: 3. Start the task and wait for the server" data-pagefind-ignore></a>
</h2>
<p><code>Start-ScheduledTask</code> returns as soon as the task starts. The server takes about 40 seconds to be ready. This starts the task and waits for the server&rsquo;s own ready line:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$log</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer\output_log.txt&#39;</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nb">Get-Process</span> <span class="n">7DaysToDieServer</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">throw</span> <span class="s1">&#39;A 7DaysToDieServer process is already running. Stop it first.&#39;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">Remove-Item</span> <span class="n">-LiteralPath</span> <span class="nv">$log</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span>
</span></span><span class="line"><span class="cl"><span class="nb">Start-ScheduledTask</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServer&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$deadline</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Get-Date</span><span class="p">).</span><span class="py">AddMinutes</span><span class="p">(</span><span class="mf">5</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="nv">$ready</span> <span class="p">=</span> <span class="vm">$false</span>
</span></span><span class="line"><span class="cl"><span class="k">while</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$ready</span> <span class="o">-and</span> <span class="p">(</span><span class="nb">Get-Date</span><span class="p">)</span> <span class="o">-lt</span> <span class="nv">$deadline</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$ready</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Test-Path</span> <span class="nv">$log</span><span class="p">)</span> <span class="o">-and</span>
</span></span><span class="line"><span class="cl">        <span class="p">(</span><span class="nb">Select-String</span> <span class="n">-Path</span> <span class="nv">$log</span> <span class="n">-Pattern</span> <span class="s1">&#39;StartGame done&#39;</span> <span class="n">-Quiet</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$ready</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Start-Sleep</span> <span class="n">-Seconds</span> <span class="mf">2</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$ready</span><span class="p">)</span> <span class="p">{</span> <span class="k">throw</span> <span class="s1">&#39;The server was not ready after five minutes.&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nv">$task</span> <span class="p">=</span> <span class="nb">Get-ScheduledTask</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServer&#39;</span>
</span></span><span class="line"><span class="cl"><span class="s1">&#39;Task state: {0}; last result: {1}&#39;</span> <span class="o">-f</span> <span class="nv">$task</span><span class="p">.</span><span class="n">State</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">(</span><span class="nb">Get-ScheduledTaskInfo</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServer&#39;</span><span class="p">).</span><span class="n">LastTaskResult</span></span></span></code></pre></div></div>
  </div>
</div><p>It stops if a <code>7DaysToDieServer</code> process is already running, however it was started. A task in the <code>Ready</code> state would start a second server on the same ports and folder if you had started the first one by hand. And <code>Start-ScheduledTask</code> on a running task does nothing and returns no error. It does set the last result to <code>2147946720</code>, the refusal from the default one-instance rule, and a later read of the result would mislead. It deletes the old log first. The check looks for <code>StartGame done</code>, and a leftover log would satisfy it at once.</p>
<p>While the server runs, the output is:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">Task state: Running; last result: 267009</span></span></code></pre></div></div>
  </div>
</div><p>A state of <code>Running</code> and a last result of <code>267009</code> mean the task is running. That is a status code and not an error.</p>
<h2 id="4-stop-the-server-with-the-telnet-shutdown-command">4. Stop the server with the telnet shutdown command<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#4-stop-the-server-with-the-telnet-shutdown-command"
     aria-label="Link to section: 4. Stop the server with the telnet shutdown command" data-pagefind-ignore></a>
</h2>
<p>The server has a telnet console, on <code>127.0.0.1:8081</code> by default, and its <code>shutdown</code> command is the stop that works. Setting <code>TelnetPassword</code> makes the console listen on every interface instead, so keep Windows Firewall and any cloud network security group closed to that port. This function sends the command, with the password first if there is one, and waits for the process to exit:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Stop-GameServer</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">([</span><span class="no">securestring</span><span class="p">]</span><span class="nv">$Password</span><span class="p">,</span> <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$Port</span> <span class="p">=</span> <span class="mf">8081</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$TimeoutSeconds</span> <span class="p">=</span> <span class="mf">90</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$server</span> <span class="p">=</span> <span class="vm">@</span><span class="p">(</span><span class="nb">Get-Process</span> <span class="n">7DaysToDieServer</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$server</span><span class="p">.</span><span class="py">Count</span> <span class="o">-ne</span> <span class="mf">1</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">throw</span> <span class="s2">&#34;Expected one 7DaysToDieServer process, found </span><span class="p">$(</span><span class="nv">$server</span><span class="p">.</span><span class="n">Count</span><span class="p">)</span><span class="s2">.&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="vm">$null</span> <span class="p">=</span> <span class="nv">$server</span><span class="p">[</span><span class="mf">0</span><span class="p">].</span><span class="py">Handle</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$client</span> <span class="p">=</span> <span class="nb">New-Object</span> <span class="n">Net</span><span class="p">.</span><span class="py">Sockets</span><span class="p">.</span><span class="py">TcpClient</span><span class="p">(</span><span class="s1">&#39;127.0.0.1&#39;</span><span class="p">,</span> <span class="nv">$Port</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$stream</span> <span class="p">=</span> <span class="nv">$client</span><span class="p">.</span><span class="py">GetStream</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$stream</span><span class="p">.</span><span class="py">ReadTimeout</span> <span class="p">=</span> <span class="mf">2000</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$buffer</span> <span class="p">=</span> <span class="nb">New-Object</span> <span class="n">byte</span><span class="p">[]</span> <span class="mf">4096</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$reply</span> <span class="p">=</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$text</span> <span class="p">=</span> <span class="s1">&#39;&#39;</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$until</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Get-Date</span><span class="p">).</span><span class="py">AddSeconds</span><span class="p">(</span><span class="mf">3</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">                <span class="k">while</span> <span class="p">((</span><span class="nb">Get-Date</span><span class="p">)</span> <span class="o">-lt</span> <span class="nv">$until</span> <span class="o">-and</span>
</span></span><span class="line"><span class="cl">                    <span class="p">(</span><span class="nv">$count</span> <span class="p">=</span> <span class="nv">$stream</span><span class="p">.</span><span class="py">Read</span><span class="p">(</span><span class="nv">$buffer</span><span class="p">,</span> <span class="mf">0</span><span class="p">,</span> <span class="nv">$buffer</span><span class="p">.</span><span class="n">Length</span><span class="p">))</span> <span class="o">-gt</span> <span class="mf">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">                    <span class="nv">$text</span> <span class="p">+=</span> <span class="p">[</span><span class="no">Text.Encoding</span><span class="p">]::</span><span class="n">ASCII</span><span class="p">.</span><span class="py">GetString</span><span class="p">(</span><span class="nv">$buffer</span><span class="p">,</span> <span class="mf">0</span><span class="p">,</span> <span class="nv">$count</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">                <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="k">catch</span> <span class="p">[</span><span class="no">IO.IOException</span><span class="p">]</span> <span class="p">{</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$text</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$send</span> <span class="p">=</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">param</span><span class="p">(</span><span class="nv">$line</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$bytes</span> <span class="p">=</span> <span class="p">[</span><span class="no">Text.Encoding</span><span class="p">]::</span><span class="n">ASCII</span><span class="p">.</span><span class="py">GetBytes</span><span class="p">(</span><span class="s2">&#34;</span><span class="nv">$line</span><span class="se">`r`n</span><span class="s2">&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$stream</span><span class="p">.</span><span class="py">Write</span><span class="p">(</span><span class="nv">$bytes</span><span class="p">,</span> <span class="mf">0</span><span class="p">,</span> <span class="nv">$bytes</span><span class="p">.</span><span class="n">Length</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="nv">$Password</span> <span class="o">-and</span> <span class="nv">$Password</span><span class="p">.</span><span class="py">Length</span> <span class="o">-gt</span> <span class="mf">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="p">&amp;</span> <span class="nv">$send</span> <span class="p">([</span><span class="no">Net.NetworkCredential</span><span class="p">]::</span><span class="n">new</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="nv">$Password</span><span class="p">).</span><span class="n">Password</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$login</span> <span class="p">=</span> <span class="p">&amp;</span> <span class="nv">$reply</span>
</span></span><span class="line"><span class="cl">            <span class="k">if</span> <span class="p">(</span><span class="nv">$login</span> <span class="o">-match</span> <span class="s1">&#39;Password incorrect&#39;</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">                <span class="k">throw</span> <span class="s1">&#39;The telnet password is missing or wrong.&#39;</span>
</span></span><span class="line"><span class="cl">            <span class="p">}</span>
</span></span><span class="line"><span class="cl">            <span class="k">if</span> <span class="p">(</span><span class="nv">$login</span> <span class="o">-notmatch</span> <span class="s1">&#39;Logon successful&#39;</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">                <span class="k">throw</span> <span class="s1">&#39;The server did not confirm the telnet login.&#39;</span>
</span></span><span class="line"><span class="cl">            <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="p">&amp;</span> <span class="nv">$send</span> <span class="s1">&#39;shutdown&#39;</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">((&amp;</span> <span class="nv">$reply</span><span class="p">)</span> <span class="o">-match</span> <span class="s1">&#39;Password incorrect&#39;</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">throw</span> <span class="s1">&#39;The telnet password is missing or wrong.&#39;</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">finally</span> <span class="p">{</span> <span class="nv">$client</span><span class="p">.</span><span class="py">Close</span><span class="p">()</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$server</span><span class="p">[</span><span class="mf">0</span><span class="p">].</span><span class="py">WaitForExit</span><span class="p">(</span><span class="nv">$TimeoutSeconds</span> <span class="p">*</span> <span class="mf">1000</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">throw</span> <span class="s2">&#34;The server was still running after </span><span class="nv">$TimeoutSeconds</span><span class="s2"> seconds.&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="s1">&#39;Stopped, exit code {0}.&#39;</span> <span class="o">-f</span> <span class="nv">$server</span><span class="p">[</span><span class="mf">0</span><span class="p">].</span><span class="py">ExitCode</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>It stops with an error and doesn&rsquo;t touch the process in two cases. The telnet port refuses the connection, which is what <code>TelnetEnabled</code> set to <code>false</code> does. Or the server answers <code>Password incorrect</code>. It never forces the process to end. Run it as <code>Stop-GameServer</code>. With a telnet password, read it as a secure string so it stays out of your console history and any transcript:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$telnet</span> <span class="p">=</span> <span class="nb">Read-Host</span> <span class="s1">&#39;Telnet password&#39;</span> <span class="n">-AsSecureString</span>
</span></span><span class="line"><span class="cl"><span class="nb">Stop-GameServer</span> <span class="n">-Password</span> <span class="nv">$telnet</span></span></span></code></pre></div></div>
  </div>
</div><p>The function turns it back into text only to send it. The game&rsquo;s telnet console takes it unencrypted, one more reason to keep that port closed.</p>
<p>On the task&rsquo;s server it stopped the process with exit code <code>0</code>. The task went back to <code>Ready</code> with a last result of <code>0</code>, because the process ended by itself. The server wrote 8 to 14 files under <code>Saves</code> and its log ran on to the end of its shutdown, after <code>SaveAndCleanupWorld</code> and <code>Saving 0 of chunks</code>, with 47 more lines. It took two to eight seconds.</p>
<p>With a telnet password set, I connected three ways and sent <code>shutdown</code> each time. With no password, or a wrong one, the server answered <code>Password incorrect, please enter password:</code> and kept running, and the function reports that at once. With the right password it stopped in two seconds, exit code <code>0</code>, and the log held <code>SaveAndCleanupWorld</code>.</p>
<p>Each wrong attempt counts toward the server&rsquo;s <code>TelnetFailedLoginLimit</code>, which was 10 on this server. The function sends the password first and reads the reply, for at most three seconds, and sends <code>shutdown</code> only after the server has said <code>Logon successful</code>, so a wrong password uses one attempt. Sent together, the <code>shutdown</code> after a wrong password would count as a second one. With the limit set to 3, a wrong password and then a missing one still left the right password working.</p>
<p>If the reply is late or says neither, the function stops with <code>The server did not confirm the telnet login.</code> The server also prints its log to a telnet connection, so a read that waited only for silence could go on as long as the server logged something every two seconds.</p>
<h3 id="why-stop-scheduledtask-isnt-a-clean-stop">Why <code>Stop-ScheduledTask</code> isn&rsquo;t a clean stop<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#why-stop-scheduledtask-isnt-a-clean-stop"
     aria-label="Link to section: Why Stop-ScheduledTask isn’t a clean stop" data-pagefind-ignore></a>
</h3>
<p><code>Stop-ScheduledTask -TaskName '7DaysToDieServer'</code> is the obvious stop for a task, and it ends the process from outside. I ran it twice on the task&rsquo;s server on V 3.2, and twice on V 3.4:</p>
<ul>
<li>The process exited with code <code>1067</code> after about a second every time. <code>1067</code> is <code>ERROR_PROCESS_ABORTED</code>, &ldquo;The process terminated unexpectedly&rdquo;. The process had that exit code every time Task Scheduler ended it here.</li>
<li>On V 3.2 the log began the shutdown, with <code>SaveAndCleanupWorld</code> and <code>Stopping server</code>. It then ended at <code>Cleared queues.</code> instead of running on for another 40 or so lines. It wrote three to five files under <code>Saves</code>, among them <code>main.ttw</code>, <code>players.xml</code> and <code>decoration.7dt</code>. The telnet stop also wrote <code>vehicles.dat</code>, <code>power.dat</code>, <code>turrets.dat</code>, <code>drones.dat</code> and <code>blockLimits.dat</code>, and none of those five were written in either <code>Stop-ScheduledTask</code> run.</li>
<li>On V 3.4 the log ran the whole save, through <code>TurretTracker saved</code> to <code>[EOS] Server unregistered</code>, and each run wrote the same eight files as the telnet stop, those five included. Only the last lines of the shutdown, <code>Terminating threads</code> and <code>OnApplicationQuit</code>, were missing.</li>
<li>The task read <code>Ready</code> with a last result of <code>267014</code>, Task Scheduler&rsquo;s code for a terminated task.</li>
</ul>
<p>I ran these on a new world with nobody connected. On V 3.4 the forced stop finished the save on an idle server. That doesn&rsquo;t show it finishes one on a world people are playing, and V 3.2 shows that a build can change it. Stop with telnet, and use <code>Stop-ScheduledTask</code> as the fallback when telnet isn&rsquo;t available.</p>
<h3 id="other-ways-to-stop-it-taskkill-and-the-close-request">Other ways to stop it: taskkill and the close request<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#other-ways-to-stop-it-taskkill-and-the-close-request"
     aria-label="Link to section: Other ways to stop it: taskkill and the close request" data-pagefind-ignore></a>
</h3>
<p>With telnet off, I tried the other ways a script might stop the process. The first two behave differently when a console session started the server and when the task did, so the table has both:</p>
<div class="table-wrap" data-scrollable data-label="Table: Method">
  <table>
    <thead>
      <tr><th scope="col">Method</th><th scope="col">Server started by the task</th><th scope="col">Server started from a console session</th></tr>
    </thead>
    <tbody>
      <tr><td><code>CloseMainWindow()</code> on the process</td><td>Returned <code>False</code>, and the server kept running</td><td>Returned <code>True</code>, and the server was still running 10 seconds later</td></tr>
      <tr><td><code>taskkill /PID &lt;id&gt;</code> without <code>/F</code></td><td><code>ERROR: ... This process can only be terminated forcefully (with /F option).</code> The server kept running</td><td><code>SUCCESS: Sent termination signal</code>, and the server was still running five seconds later</td></tr>
      <tr><td><code>Stop-Process -Force</code></td><td>Not run</td><td>Ended it at once. The log has no <code>SaveAndCleanupWorld</code></td></tr>
    </tbody>
  </table>
</div>
<p>The server runs with <code>-batchmode -nographics</code>, and the two polite requests had no effect on it. <code>Stop-Process -Force</code> is the last resort. After it, the server had logged no save, so whatever happened since the last save is gone.</p>
<!-- style-check: end procedure -->
<h2 id="5-check-the-task-after-the-first-reboot">5. Check the task after the first reboot<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#5-check-the-task-after-the-first-reboot"
     aria-label="Link to section: 5. Check the task after the first reboot" data-pagefind-ignore></a>
</h2>
<p>The at-startup trigger was registered and read back as a boot trigger, and the task starts on command. I didn&rsquo;t restart the test server, so I haven&rsquo;t seen the trigger fire. After your first reboot, check that it did:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-ScheduledTaskInfo</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServer&#39;</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Select-Object</span> <span class="n">LastRunTime</span><span class="p">,</span> <span class="n">LastTaskResult</span>
</span></span><span class="line"><span class="cl"><span class="nb">Get-Process</span> <span class="n">7DaysToDieServer</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span></span></span></code></pre></div></div>
  </div>
</div><p>A <code>LastRunTime</code> near the boot time and a running process mean it worked. Stop the server with step 4 before you restart the machine on purpose. I haven&rsquo;t tested what Windows does to the server when it shuts down with the task running, and if it ends the process the way <code>Stop-ScheduledTask</code> does, the save can be partial.</p>
<p>Nothing here restarts the server if it crashes. The task has no restart settings.</p>
<h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="server-stops-by-itself-after-three-days">Server stops by itself after three days<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#server-stops-by-itself-after-three-days"
     aria-label="Link to section: Server stops by itself after three days" data-pagefind-ignore></a>
</h3>
<p>The task has the default 72-hour limit, or whatever limit you set. Read it with <code>(Get-ScheduledTask -TaskName '7DaysToDieServer').Settings.ExecutionTimeLimit</code>. If it isn&rsquo;t <code>PT0S</code>, remove the task and register it again with step 1.</p>
<h3 id="task-starts-and-the-server-isnt-running">Task starts and the server isn&rsquo;t running<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#task-starts-and-the-server-isnt-running"
     aria-label="Link to section: Task starts and the server isn’t running" data-pagefind-ignore></a>
</h3>
<p>The log in <code>-logfile</code> has the reason. Two causes seen on this server: a missing Visual C++ runtime, and a <code>ServerPort</code> outside 1024 to 65530.</p>
<h3 id="stop-gameserver-says-the-connection-was-refused"><code>Stop-GameServer</code> says the connection was refused<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#stop-gameserver-says-the-connection-was-refused"
     aria-label="Link to section: Stop-GameServer says the connection was refused" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Exception</span> <span class="console__token">calling</span> <span class="console__token">&#34;.ctor&#34;</span> <span class="console__token">with</span> <span class="console__token">&#34;2&#34;</span> <span class="console__token">argument(s):</span> <span class="console__token">&#34;No</span> <span class="console__token">connection</span> <span class="console__token">could</span> <span class="console__token">be</span> <span class="console__token">made</span> <span class="console__token">because</span> <span class="console__token">the</span> <span class="console__token">target</span> <span class="console__token">machine</span> <span class="console__token">actively</span> <span class="console__token">refused</span> <span class="console__token">it</span> <span class="console__token">127.0.0.1:8081&#34;</span></span></code></pre>
    </div>
  </div></div><p>Telnet is off, or on another port. Check <code>TelnetEnabled</code> and <code>TelnetPort</code> in <code>myserver.xml</code>. Until telnet works, <code>Stop-ScheduledTask</code> is the fallback, with the cost step 4 describes.</p>
<h3 id="last-result-267014-or-exit-code-1067-after-a-stop">Last result 267014, or exit code 1067, after a stop<a class="heading-anchor" href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/#last-result-267014-or-exit-code-1067-after-a-stop"
     aria-label="Link to section: Last result 267014, or exit code 1067, after a stop" data-pagefind-ignore></a>
</h3>
<p>Task Scheduler uses it for a task that was ended from outside, which is what <code>Stop-ScheduledTask</code> and the time limit do. The process itself exits with <code>1067</code> when Task Scheduler ends it. A telnet stop leaves <code>0</code> for both. Step 4 shows what that stop cost on V 3.2.</p>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2025 Datacenter (10.0.26100), virtual machine</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>Windows PowerShell 5.1, elevated</dd></div>
    <div class="tested__row"><dt>Game</dt> <dd>7 Days to Die dedicated server (294420), V 3.4.0 (b9); V 3.2 results on V 3.2.0 (b10)</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>October 2026</dd></div>
  </dl>
</div>
]]></content:encoded>
    </item>
    
    <item>
      <title>Update a 7 Days to Die Dedicated Server Only When There Is a New Build</title>
      <link>https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/</guid>
      <pubDate>Thu, 24 Sep 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>Game servers</category>
      <category>PowerShell</category>
      <category>Unattended</category>
      
      <description>Compare the buildid in the appmanifest with SteamCMD&#39;s app_info_print and run app_update only when they differ. Success! and exit code 0 prove nothing.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>Read the installed build number from <code>steamapps\appmanifest_294420.acf</code>. Read the published build number from SteamCMD&rsquo;s <code>app_info_print</code>. Run <code>app_update</code> only when the two numbers differ.</p>
<p>After the update, read the installed build number again. SteamCMD can print <code>Success!</code> and exit with code <code>0</code> without changing the build. On a server installed from a branch, SteamCMD did this until <code>-beta public</code> was added to the command.</p>
<p>The code below runs in PowerShell on the server and reads both numbers. It prints the installed build and the build that Steam publishes on the <code>public</code> branch:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$manifest</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer\steamapps\appmanifest_294420.acf&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$installed</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Select-String</span> <span class="n">-LiteralPath</span> <span class="nv">$manifest</span> <span class="n">-Pattern</span> <span class="s1">&#39;^\t&#34;buildid&#34;\s+&#34;(\d+)&#34;&#39;</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Select-Object</span> <span class="n">-First</span> <span class="mf">1</span><span class="p">).</span><span class="n">Matches</span><span class="p">[</span><span class="mf">0</span><span class="p">].</span><span class="n">Groups</span><span class="p">[</span><span class="mf">1</span><span class="p">].</span><span class="py">Value</span>
</span></span><span class="line"><span class="cl"><span class="nv">$arguments</span> <span class="p">=</span> <span class="s1">&#39;+login&#39;</span><span class="p">,</span> <span class="s1">&#39;anonymous&#39;</span><span class="p">,</span> <span class="s1">&#39;+app_info_update&#39;</span><span class="p">,</span> <span class="s1">&#39;1&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="s1">&#39;+app_info_print&#39;</span><span class="p">,</span> <span class="s1">&#39;294420&#39;</span><span class="p">,</span> <span class="s1">&#39;+quit&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$info</span> <span class="p">=</span> <span class="p">(&amp;</span> <span class="s1">&#39;C:\steamcmd\steamcmd.exe&#39;</span> <span class="nv">$arguments</span> <span class="mf">2</span><span class="p">&gt;&amp;</span><span class="mf">1</span><span class="p">)</span> <span class="n">-join</span> <span class="s2">&#34;</span><span class="se">`n</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$pattern</span> <span class="p">=</span> <span class="s1">&#39;(?s)&#34;branches&#34;\s*\{.*?&#34;public&#34;\s*\{[^}]*?&#34;buildid&#34;\s+&#34;(\d+)&#34;&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$published</span> <span class="p">=</span> <span class="p">[</span><span class="no">regex</span><span class="p">]::</span><span class="n">Match</span><span class="p">(</span><span class="nv">$info</span><span class="p">,</span> <span class="nv">$pattern</span><span class="p">).</span><span class="n">Groups</span><span class="p">[</span><span class="mf">1</span><span class="p">].</span><span class="py">Value</span>
</span></span><span class="line"><span class="cl"><span class="s2">&#34;installed </span><span class="nv">$installed</span><span class="s2">, published </span><span class="nv">$published</span><span class="s2">&#34;</span></span></span></code></pre></div></div>
  </div>
</div><p>Two parts are specific to each game. They are the app ID, <code>294420</code>, and the file that holds the build number. Step 4 has the whole update as one function.</p>

</div>

<p>The previous parts installed the server, configured it, and made it start at boot and stop cleanly. This part keeps it current without restarting it for nothing. A server that runs <code>app_update</code> every morning restarts on the days when Steam has published nothing, and its players lose the session for no reason.</p>
<!-- style-check: procedure -->
<h2 id="1-read-the-installed-build-from-appmanifest_294420acf">1. Read the installed build from appmanifest_294420.acf<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#1-read-the-installed-build-from-appmanifest_294420acf"
     aria-label="Link to section: 1. Read the installed build from appmanifest_294420.acf" data-pagefind-ignore></a>
</h2>
<p>SteamCMD records what it installed in <code>steamapps\appmanifest_294420.acf</code>, inside the server&rsquo;s folder. The file is Valve&rsquo;s KeyValues text, and the installed build is the top-level <code>buildid</code> line:</p>
<div class="console"><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">$manifest</span> <span class="console__token">=</span> <span class="console__token">&#39;C:\7DaysToDieServer\steamapps\appmanifest_294420.acf&#39;</span>
</span><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">Select-String</span> <span class="console__token">-Path</span> <span class="console__token">$manifest</span> <span class="console__token">-Pattern</span> <span class="console__token">&#39;buildid&#39;</span> <span class="console__token">|</span> <span class="console__token">ForEach-Object</span> <span class="console__token">Line</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line">    <span class="console__token">&#34;buildid&#34;</span>        <span class="console__token">&#34;26237934&#34;</span>
</span><span class="line">    <span class="console__token">&#34;TargetBuildID&#34;</span>        <span class="console__token">&#34;26237934&#34;</span></span></code></pre>
    </div>
  </div></div><p><code>TargetBuildID</code> is a different key. The pattern in the next function has quotes around <code>buildid</code>, so it doesn&rsquo;t match that line. It also requires one leading tab, which makes it the top-level key and not one nested deeper. The first function reads the number and returns nothing when the file or the line is missing. The second reads the branch the install came from, which the manifest records as <code>BetaKey</code>, and gives <code>public</code> when there is none:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Get-InstalledBuild</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">([</span><span class="no">string</span><span class="p">]</span><span class="nv">$ServerDir</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer&#39;</span><span class="p">,</span> <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$AppId</span> <span class="p">=</span> <span class="s1">&#39;294420&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$manifest</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$ServerDir</span> <span class="s2">&#34;steamapps\appmanifest_</span><span class="nv">$AppId</span><span class="s2">.acf&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="p">(</span><span class="nb">Test-Path</span> <span class="n">-LiteralPath</span> <span class="nv">$manifest</span><span class="p">))</span> <span class="p">{</span> <span class="k">return</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$match</span> <span class="p">=</span> <span class="nb">Select-String</span> <span class="n">-LiteralPath</span> <span class="nv">$manifest</span> <span class="n">-Pattern</span> <span class="s1">&#39;^\t&#34;buildid&#34;\s+&#34;(\d+)&#34;&#39;</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Select-Object</span> <span class="n">-First</span> <span class="mf">1</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$match</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$match</span><span class="p">.</span><span class="n">Matches</span><span class="p">[</span><span class="mf">0</span><span class="p">].</span><span class="n">Groups</span><span class="p">[</span><span class="mf">1</span><span class="p">].</span><span class="py">Value</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Get-InstalledBranch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">([</span><span class="no">string</span><span class="p">]</span><span class="nv">$ServerDir</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer&#39;</span><span class="p">,</span> <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$AppId</span> <span class="p">=</span> <span class="s1">&#39;294420&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$manifest</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$ServerDir</span> <span class="s2">&#34;steamapps\appmanifest_</span><span class="nv">$AppId</span><span class="s2">.acf&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="p">(</span><span class="nb">Test-Path</span> <span class="n">-LiteralPath</span> <span class="nv">$manifest</span><span class="p">))</span> <span class="p">{</span> <span class="k">return</span> <span class="s1">&#39;public&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$match</span> <span class="p">=</span> <span class="nb">Select-String</span> <span class="n">-LiteralPath</span> <span class="nv">$manifest</span> <span class="n">-Pattern</span> <span class="s1">&#39;&#34;BetaKey&#34;\s+&#34;([^&#34;]+)&#34;&#39;</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Select-Object</span> <span class="n">-First</span> <span class="mf">1</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$match</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$match</span><span class="p">.</span><span class="n">Matches</span><span class="p">[</span><span class="mf">0</span><span class="p">].</span><span class="n">Groups</span><span class="p">[</span><span class="mf">1</span><span class="p">].</span><span class="py">Value</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="s1">&#39;public&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><h2 id="2-read-the-published-build-from-app_info_print">2. Read the published build from app_info_print<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#2-read-the-published-build-from-app_info_print"
     aria-label="Link to section: 2. Read the published build from app_info_print" data-pagefind-ignore></a>
</h2>
<p><code>app_info_print</code> prints everything Steam has on the app, about 560 lines for this server. The part that matters is <code>branches</code>, which has one entry per branch, each with its own <code>buildid</code>:</p>
<div class="code-block" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">        &#34;branches&#34;
</span></span><span class="line"><span class="cl">        {
</span></span><span class="line"><span class="cl">            &#34;public&#34;
</span></span><span class="line"><span class="cl">            {
</span></span><span class="line"><span class="cl">                &#34;buildid&#34;        &#34;26237934&#34;
</span></span><span class="line"><span class="cl">                &#34;timeupdated&#34;        &#34;1793199733&#34;
</span></span><span class="line"><span class="cl">                &#34;timebuildupdated&#34;        &#34;1793087985&#34;
</span></span><span class="line"><span class="cl">            }
</span></span><span class="line"><span class="cl">            &#34;v3.4.0&#34;
</span></span><span class="line"><span class="cl">            {
</span></span><span class="line"><span class="cl">                &#34;buildid&#34;        &#34;26237934&#34;
</span></span><span class="line"><span class="cl">                &#34;description&#34;        &#34;Version 3.4.0 Stable&#34;
</span></span><span class="line"><span class="cl">                &#34;timeupdated&#34;        &#34;1793199733&#34;
</span></span><span class="line"><span class="cl">                &#34;timebuildupdated&#34;        &#34;1793087985&#34;
</span></span><span class="line"><span class="cl">            }
</span></span><span class="line"><span class="cl">            &#34;v3.3.0&#34;
</span></span><span class="line"><span class="cl">            {
</span></span><span class="line"><span class="cl">                &#34;buildid&#34;        &#34;25661908&#34;
</span></span><span class="line"><span class="cl">                &#34;description&#34;        &#34;Version 3.3.0 Stable&#34;
</span></span><span class="line"><span class="cl">                &#34;timeupdated&#34;        &#34;1791219591&#34;</span></span></code></pre></div></div>
  </div>
</div><p><code>+app_info_update 1</code> makes SteamCMD fetch fresh data before it prints, and the whole lookup took about three seconds here. Take the <code>buildid</code> of the branch you run, which is <code>public</code> unless you chose a beta. The same text holds a <code>public</code> entry under each depot, with a <code>gid</code> and no <code>buildid</code>. A search from the first <code>public</code> therefore depends on where the sections happen to sit. The pattern here starts at <code>branches</code>:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Get-PublishedBuild</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$SteamCmd</span> <span class="p">=</span> <span class="s1">&#39;C:\steamcmd\steamcmd.exe&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$AppId</span> <span class="p">=</span> <span class="s1">&#39;294420&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$Branch</span> <span class="p">=</span> <span class="s1">&#39;public&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="p">(</span><span class="nb">Test-Path</span> <span class="n">-LiteralPath</span> <span class="nv">$SteamCmd</span><span class="p">))</span> <span class="p">{</span> <span class="k">return</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$arguments</span> <span class="p">=</span> <span class="s1">&#39;+login&#39;</span><span class="p">,</span> <span class="s1">&#39;anonymous&#39;</span><span class="p">,</span> <span class="s1">&#39;+app_info_update&#39;</span><span class="p">,</span> <span class="s1">&#39;1&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="s1">&#39;+app_info_print&#39;</span><span class="p">,</span> <span class="nv">$AppId</span><span class="p">,</span> <span class="s1">&#39;+quit&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$text</span> <span class="p">=</span> <span class="p">(&amp;</span> <span class="nv">$SteamCmd</span> <span class="nv">$arguments</span> <span class="mf">2</span><span class="p">&gt;&amp;</span><span class="mf">1</span><span class="p">)</span> <span class="n">-join</span> <span class="s2">&#34;</span><span class="se">`n</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$pattern</span> <span class="p">=</span> <span class="s1">&#39;(?s)&#34;branches&#34;\s*\{.*?&#34;&#39;</span> <span class="p">+</span> <span class="p">[</span><span class="no">regex</span><span class="p">]::</span><span class="n">Escape</span><span class="p">(</span><span class="nv">$Branch</span><span class="p">)</span> <span class="p">+</span>
</span></span><span class="line"><span class="cl">        <span class="s1">&#39;&#34;\s*\{[^}]*?&#34;buildid&#34;\s+&#34;(\d+)&#34;&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$match</span> <span class="p">=</span> <span class="p">[</span><span class="no">regex</span><span class="p">]::</span><span class="n">Match</span><span class="p">(</span><span class="nv">$text</span><span class="p">,</span> <span class="nv">$pattern</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$match</span><span class="p">.</span><span class="n">Success</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$match</span><span class="p">.</span><span class="n">Groups</span><span class="p">[</span><span class="mf">1</span><span class="p">].</span><span class="py">Value</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>It returns nothing when SteamCMD isn&rsquo;t where you said, or when the text has no such branch, which is what a failed connection to Steam gives too. A branch that doesn&rsquo;t exist, <code>nonexistent</code> here, gave an empty result. Branch names are case-sensitive, and a branch that needs a password isn&rsquo;t covered.</p>
<h2 id="3-compare-the-two-builds-and-treat-a-missing-number-as-unknown">3. Compare the two builds, and treat a missing number as unknown<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#3-compare-the-two-builds-and-treat-a-missing-number-as-unknown"
     aria-label="Link to section: 3. Compare the two builds, and treat a missing number as unknown" data-pagefind-ignore></a>
</h2>
<p>Run both functions:</p>
<div class="console"><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">Get-InstalledBuild</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">26237934</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">Get-PublishedBuild</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">26237934</span></span></code></pre>
    </div>
  </div></div><p>Equal numbers mean there is nothing to do. When either is empty, you don&rsquo;t know, and the safe answer is to stop and say so, not to guess. The next function does that.</p>
<h2 id="4-update-only-when-they-differ">4. Update only when they differ<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#4-update-only-when-they-differ"
     aria-label="Link to section: 4. Update only when they differ" data-pagefind-ignore></a>
</h2>
<p>This function does the whole job. When the builds match and the install is already on the branch you want, it returns at once and touches nothing, so a running server keeps running. When they differ it stops the server if one is running, runs <code>app_update</code>, reads the installed build again to check, and starts the server if it was running:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Update-GameServer</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$ServerDir</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$SteamCmd</span> <span class="p">=</span> <span class="s1">&#39;C:\steamcmd\steamcmd.exe&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$AppId</span> <span class="p">=</span> <span class="s1">&#39;294420&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$Branch</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">scriptblock</span><span class="p">]</span><span class="nv">$StopServer</span> <span class="p">=</span> <span class="p">{</span> <span class="nb">Stop-GameServer</span> <span class="p">},</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="no">scriptblock</span><span class="p">]</span><span class="nv">$StartServer</span> <span class="p">=</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nb">Start-ScheduledTask</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServer&#39;</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nb">Test-Path</span> <span class="n">-LiteralPath</span> <span class="nv">$ServerDir</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$ServerDir</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Resolve-Path</span> <span class="n">-LiteralPath</span> <span class="nv">$ServerDir</span><span class="p">).</span><span class="py">ProviderPath</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$Branch</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$Branch</span> <span class="p">=</span> <span class="nb">Get-InstalledBranch</span> <span class="n">-ServerDir</span> <span class="nv">$ServerDir</span> <span class="n">-AppId</span> <span class="nv">$AppId</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$installed</span> <span class="p">=</span> <span class="nb">Get-InstalledBuild</span> <span class="n">-ServerDir</span> <span class="nv">$ServerDir</span> <span class="n">-AppId</span> <span class="nv">$AppId</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$published</span> <span class="p">=</span> <span class="nb">Get-PublishedBuild</span> <span class="n">-SteamCmd</span> <span class="nv">$SteamCmd</span> <span class="n">-AppId</span> <span class="nv">$AppId</span> <span class="n">-Branch</span> <span class="nv">$Branch</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;Installed build: </span><span class="p">$(</span><span class="k">if</span> <span class="p">(</span><span class="nv">$installed</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$installed</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="s1">&#39;unknown&#39;</span> <span class="p">})</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;Published build: </span><span class="p">$(</span><span class="k">if</span> <span class="p">(</span><span class="nv">$published</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$published</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="s1">&#39;unknown&#39;</span> <span class="p">})</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$installed</span> <span class="o">-or</span> <span class="o">-not</span> <span class="nv">$published</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">throw</span> <span class="s1">&#39;Could not read both builds. Nothing was changed.&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$installedBranch</span> <span class="p">=</span> <span class="nb">Get-InstalledBranch</span> <span class="n">-ServerDir</span> <span class="nv">$ServerDir</span> <span class="n">-AppId</span> <span class="nv">$AppId</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$sameBuild</span> <span class="p">=</span> <span class="nv">$installed</span> <span class="o">-eq</span> <span class="nv">$published</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$sameBuild</span> <span class="o">-and</span> <span class="nv">$installedBranch</span> <span class="o">-eq</span> <span class="nv">$Branch</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="s1">&#39;Already on the published build. Nothing to do.&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$exe</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$ServerDir</span> <span class="s1">&#39;7DaysToDieServer.exe&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$wasRunning</span> <span class="p">=</span> <span class="p">[</span><span class="no">bool</span><span class="p">](</span><span class="nb">Get-Process</span> <span class="n">7DaysToDieServer</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Where-Object</span> <span class="p">{</span> <span class="nv">$_</span><span class="p">.</span><span class="py">Path</span> <span class="o">-eq</span> <span class="nv">$exe</span> <span class="p">})</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$restart</span> <span class="p">=</span> <span class="nv">$wasRunning</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$restart</span><span class="p">)</span> <span class="p">{</span> <span class="p">&amp;</span> <span class="nv">$StopServer</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$arguments</span> <span class="p">=</span> <span class="s1">&#39;+force_install_dir&#39;</span><span class="p">,</span> <span class="nv">$ServerDir</span><span class="p">,</span> <span class="s1">&#39;+login&#39;</span><span class="p">,</span> <span class="s1">&#39;anonymous&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="s1">&#39;+app_update&#39;</span><span class="p">,</span> <span class="nv">$AppId</span><span class="p">,</span> <span class="s1">&#39;-beta&#39;</span><span class="p">,</span> <span class="nv">$Branch</span><span class="p">,</span> <span class="s1">&#39;validate&#39;</span><span class="p">,</span> <span class="s1">&#39;+quit&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="k">foreach</span> <span class="p">(</span><span class="nv">$attempt</span> <span class="k">in</span> <span class="mf">1</span><span class="p">,</span> <span class="mf">2</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="vm">$null</span> <span class="p">=</span> <span class="p">&amp;</span> <span class="nv">$SteamCmd</span> <span class="nv">$arguments</span> <span class="mf">2</span><span class="p">&gt;&amp;</span><span class="mf">1</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$after</span> <span class="p">=</span> <span class="nb">Get-InstalledBuild</span> <span class="n">-ServerDir</span> <span class="nv">$ServerDir</span> <span class="n">-AppId</span> <span class="nv">$AppId</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$now</span> <span class="p">=</span> <span class="nb">Get-InstalledBranch</span> <span class="n">-ServerDir</span> <span class="nv">$ServerDir</span> <span class="n">-AppId</span> <span class="nv">$AppId</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$onBranch</span> <span class="p">=</span> <span class="nv">$now</span> <span class="o">-eq</span> <span class="nv">$Branch</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="nv">$after</span> <span class="o">-eq</span> <span class="nv">$published</span> <span class="o">-and</span> <span class="nv">$onBranch</span><span class="p">)</span> <span class="p">{</span> <span class="k">break</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="c"># Steam may have published another build since the first lookup.</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$published</span> <span class="p">=</span> <span class="nb">Get-PublishedBuild</span> <span class="n">-SteamCmd</span> <span class="nv">$SteamCmd</span> <span class="n">-AppId</span> <span class="nv">$AppId</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">            <span class="n">-Branch</span> <span class="nv">$Branch</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="nv">$after</span> <span class="o">-eq</span> <span class="nv">$published</span> <span class="o">-and</span> <span class="nv">$onBranch</span><span class="p">)</span> <span class="p">{</span> <span class="k">break</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$note</span> <span class="p">=</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$restart</span><span class="p">)</span> <span class="p">{</span> <span class="s1">&#39; The server was left stopped.&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$after</span> <span class="o">-or</span> <span class="o">-not</span> <span class="nv">$published</span> <span class="o">-or</span> <span class="nv">$after</span> <span class="o">-ne</span> <span class="nv">$published</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$shown</span> <span class="p">=</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$after</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$after</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="s1">&#39;unknown&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$wanted</span> <span class="p">=</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$published</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$published</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="s1">&#39;unknown&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="k">throw</span> <span class="s2">&#34;Update failed: installed build is </span><span class="nv">$shown</span><span class="s2">, expected </span><span class="nv">$wanted</span><span class="s2">.</span><span class="nv">$note</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$afterBranch</span> <span class="p">=</span> <span class="nb">Get-InstalledBranch</span> <span class="n">-ServerDir</span> <span class="nv">$ServerDir</span> <span class="n">-AppId</span> <span class="nv">$AppId</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$afterBranch</span> <span class="o">-ne</span> <span class="nv">$Branch</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">throw</span> <span class="s2">&#34;Update failed: the install is on branch </span><span class="nv">$afterBranch</span><span class="s2">, not </span><span class="nv">$Branch</span><span class="s2">.</span><span class="nv">$note</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$restart</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="p">&amp;</span> <span class="nv">$StartServer</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$deadline</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Get-Date</span><span class="p">).</span><span class="py">AddSeconds</span><span class="p">(</span><span class="mf">60</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">do</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$running</span> <span class="p">=</span> <span class="nb">Get-Process</span> <span class="n">7DaysToDieServer</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$started</span> <span class="p">=</span> <span class="p">[</span><span class="no">bool</span><span class="p">](</span><span class="nv">$running</span> <span class="p">|</span> <span class="nb">Where-Object</span> <span class="p">{</span> <span class="nv">$_</span><span class="p">.</span><span class="py">Path</span> <span class="o">-eq</span> <span class="nv">$exe</span> <span class="p">})</span>
</span></span><span class="line"><span class="cl">            <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$started</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Start-Sleep</span> <span class="n">-Seconds</span> <span class="mf">2</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span> <span class="k">until</span> <span class="p">(</span><span class="nv">$started</span> <span class="o">-or</span> <span class="p">(</span><span class="nb">Get-Date</span><span class="p">)</span> <span class="o">-gt</span> <span class="nv">$deadline</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$started</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">throw</span> <span class="s2">&#34;Updated to build </span><span class="nv">$after</span><span class="s2">, but the server did not start.&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nv">$sameBuild</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="s2">&#34;Switched to branch </span><span class="nv">$Branch</span><span class="s2">. The build is </span><span class="nv">$after</span><span class="s2">.&#34;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;Updated to build </span><span class="nv">$after</span><span class="s2">.&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>Run it as <code>Update-GameServer</code>. <code>Stop-GameServer</code> is the function from <a href="https://looselydecoupled.com/start-7-days-to-die-server-at-boot-and-stop-it-cleanly/">Start a 7 Days to Die Dedicated Server at Boot on Windows and Stop It Cleanly</a>, so define it first, and the default start command is that article&rsquo;s scheduled task. Change either with <code>-StopServer</code> and <code>-StartServer</code>. With a telnet password, read it once and pass it through <code>-StopServer</code>: <code>$telnet = Read-Host 'Telnet password' -AsSecureString</code>, then <code>Update-GameServer -StopServer { Stop-GameServer -Password $telnet }</code>.</p>
<p>What it does around the update:</p>
<ul>
<li>It resolves <code>-ServerDir</code> to a full path first, so a relative path such as <code>.\old-server</code> finds the running server too.</li>
<li>Without <code>-Branch</code> it uses the branch the manifest records, so a server on a beta stays on it. Passing <code>-Branch</code> moves a server to another one.</li>
<li>Two branches can have the same build. Then the function runs <code>app_update</code> and says <code>Switched to branch ...</code>. It still stops and starts a running server, because a build published in the meantime would change the files under it.</li>
<li>It runs <code>app_update</code> a second time if the first leaves the wrong build or the wrong branch. Moving from <code>public</code> to an older branch printed <code>Success!</code> and changed nothing until the second run.</li>
<li>A failed update stops the function with an error and leaves the server stopped on purpose, because a half-updated install that starts and reports success is worse.</li>
<li>If the build doesn&rsquo;t match, it asks Steam for the published build once more before it gives up, because Steam can publish a newer build between the first lookup and the update.</li>
<li>After the update it waits up to a minute for the server process, since <code>Start-ScheduledTask</code> only submits the request, and stops with an error if none appears.</li>
<li>A build number it can&rsquo;t read, before or after the update, counts as a failed update too, and the message says <code>unknown</code> for it.</li>
</ul>
<p>On a server that is current, with the server running:</p>
<div class="console"><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">Update-GameServer</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Installed</span> <span class="console__token">build:</span> <span class="console__token">26237934</span>
</span><span class="line"><span class="console__token">Published</span> <span class="console__token">build:</span> <span class="console__token">26237934</span>
</span><span class="line"><span class="console__token">Already</span> <span class="console__token">on</span> <span class="console__token">the</span> <span class="console__token">published</span> <span class="console__token">build.</span> <span class="console__token">Nothing</span> <span class="console__token">to</span> <span class="console__token">do.</span></span></code></pre>
    </div>
  </div></div><p>The server&rsquo;s process ID didn&rsquo;t change, and the manifest wasn&rsquo;t touched.</p>
<h3 id="real-update-from-branch-v330-to-public">Real update from branch v3.3.0 to public<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#real-update-from-branch-v330-to-public"
     aria-label="Link to section: Real update from branch v3.3.0 to public" data-pagefind-ignore></a>
</h3>
<p>To test an update that has something to download, I installed the previous stable version into a separate folder with <code>-beta v3.3.0</code>. That is build <code>25661908</code>. I started its server and ran the function against it:</p>
<div class="console"><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">Update-GameServer</span> <span class="console__token">-ServerDir</span> <span class="console__token">C:\scratch\old-server</span> <span class="console__token">-Branch</span> <span class="console__token">public</span> <span class="console__token">`</span>
</span><span class="line"><span class="prompt">&gt;     </span><span class="console__token">-StartServer</span> <span class="console__token">{</span> <span class="console__token">&lt;start</span> <span class="console__token">command</span> <span class="console__token">for</span> <span class="console__token">that</span> <span class="console__token">folder&gt;</span> <span class="console__token">}</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Installed</span> <span class="console__token">build:</span> <span class="console__token">25661908</span>
</span><span class="line"><span class="console__token">Published</span> <span class="console__token">build:</span> <span class="console__token">26237934</span>
</span><span class="line"><span class="console__token">Stopped,</span> <span class="console__token">exit</span> <span class="console__token">code</span> <span class="console__token">0.</span>
</span><span class="line"><span class="console__token">Updated</span> <span class="console__token">to</span> <span class="console__token">build</span> <span class="console__token">26237934.</span></span></code></pre>
    </div>
  </div></div><p>The old server was stopped over telnet and exited with code <code>0</code>. The update downloaded only what changed between the two builds, and the server started again on the new build. The stop line comes from the start-at-boot article&rsquo;s function.</p>
<h3 id="plain-app_update-exits-0-and-the-build-doesnt-change">Plain app_update exits 0 and the build doesn&rsquo;t change<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#plain-app_update-exits-0-and-the-build-doesnt-change"
     aria-label="Link to section: Plain app_update exits 0 and the build doesn’t change" data-pagefind-ignore></a>
</h3>
<p>The command I started with was the plain <code>app_update 294420 validate</code>, which is what an install script usually has. On the <code>v3.3.0</code> install it printed <code>Success! App '294420' fully installed.</code>, exited with code <code>0</code>, and left the build at <code>25661908</code>. On this install SteamCMD had recorded the branch in the manifest as <code>BetaKey</code>, and a plain <code>app_update</code> stayed on it. The manifest read <code>v3.3.0</code> before, and <code>public</code> after <code>-beta public</code>.</p>
<p>Running <code>-beta public</code> on a server that was already on <code>public</code> changed nothing: the build stayed current.</p>
<p>Staying on its own branch is right for a server that should stay on one, which is why <code>-Branch</code> defaults to the manifest&rsquo;s <code>BetaKey</code>. It also means the exit code and the <code>Success!</code> line say nothing about whether the build you wanted landed. The function therefore reads the installed build again and compares it with the published one.</p>
<h3 id="validate-restores-the-shipped-config"><code>validate</code> restores the shipped config<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#validate-restores-the-shipped-config"
     aria-label="Link to section: validate restores the shipped config" data-pagefind-ignore></a>
</h3>
<p><code>validate</code> checks every file against Steam&rsquo;s copy and restores any shipped file you edited. It put <code>serverconfig.xml</code> back to the shipped version when the install article ran it, and again here. If you run the server from <code>myserver.xml</code>, as <a href="https://looselydecoupled.com/configure-7-days-to-die-server-and-open-ports/">Configure a 7 Days to Die Dedicated Server and Open Its Ports</a> does, an update leaves your settings alone.</p>
<!-- style-check: end procedure -->
<h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="update-failed-installed-build-is-not-the-published-one">Update failed: installed build is not the published one<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#update-failed-installed-build-is-not-the-published-one"
     aria-label="Link to section: Update failed: installed build is not the published one" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Update</span> <span class="console__token">failed:</span> <span class="console__token">installed</span> <span class="console__token">build</span> <span class="console__token">is</span> <span class="console__token">24436799,</span> <span class="console__token">expected</span> <span class="console__token">24994542.</span> <span class="console__token">The</span> <span class="console__token">server</span> <span class="console__token">was</span> <span class="console__token">left</span> <span class="console__token">stopped.</span></span></code></pre>
    </div>
  </div></div><p>The function ran <code>app_update</code> and the installed build didn&rsquo;t become the published one. I couldn&rsquo;t make a real update fail, so I got this message by wrapping SteamCMD in a script that answers <code>app_update</code> with an error. Read what SteamCMD prints by running its command yourself, with the arguments from the function. If the server was running, it stays stopped. Start it again once you have the installed build right, or after you decide to run on the old one.</p>
<h3 id="update-reports-success-and-the-build-is-the-old-one">Update reports success and the build is the old one<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#update-reports-success-and-the-build-is-the-old-one"
     aria-label="Link to section: Update reports success and the build is the old one" data-pagefind-ignore></a>
</h3>
<p>The manifest&rsquo;s <code>BetaKey</code> still names the branch the install came from, so a plain <code>app_update</code> stays on it. Pass <code>-beta</code> with the branch you want, which the function does through <code>-Branch</code>, and read the installed build again.</p>
<h3 id="could-not-read-both-builds">Could not read both builds<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#could-not-read-both-builds"
     aria-label="Link to section: Could not read both builds" data-pagefind-ignore></a>
</h3>
<p>The function stopped before changing anything, and a mistyped <code>-Branch</code> ends up here too. The installed build is unknown when the manifest file is missing, which happens when <code>-ServerDir</code> is wrong. The published build is unknown when SteamCMD isn&rsquo;t where you said, can&rsquo;t reach Steam, or has no such branch. Check with <code>Get-PublishedBuild -Branch &lt;name&gt;</code> and read the printed text.</p>
<h3 id="update-landed-and-the-server-didnt-start">Update landed and the server didn&rsquo;t start<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#update-landed-and-the-server-didnt-start"
     aria-label="Link to section: Update landed and the server didn’t start" data-pagefind-ignore></a>
</h3>
<p>The update itself finished, and the function says so: <code>Updated to build &lt;build&gt;, but the server did not start.</code> Look at the task&rsquo;s last result with <code>Get-ScheduledTaskInfo</code> and at the server&rsquo;s log.</p>
<p><code>Update-GameServer</code> starts the server only if one was running when it began. A server that was stopped stays stopped, and gives no such error.</p>
<h2 id="what-i-didnt-test">What I didn&rsquo;t test<a class="heading-anchor" href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/#what-i-didnt-test"
     aria-label="Link to section: What I didn’t test" data-pagefind-ignore></a>
</h2>
<p>I didn&rsquo;t see Steam publish a new build on <code>public</code> while this was running, so the update tested here was a move from an older branch to the current public build. I didn&rsquo;t test a branch that needs a password, or a path to SteamCMD that has spaces in it. It exercises the same download, stop and start steps, but a routine patch is smaller. The article doesn&rsquo;t schedule the check. And the stop and start commands are the previous parts&rsquo;, which I ran separately.</p>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2025 Datacenter (10.0.26100), virtual machine</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>Windows PowerShell 5.1, elevated</dd></div>
    <div class="tested__row"><dt>Game</dt> <dd>7 Days to Die dedicated server (294420), V 3.4.0 (b9)</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>October 2026</dd></div>
  </dl>
</div>
]]></content:encoded>
    </item>
    
    <item>
      <title>Install SteamCMD and a Steam Dedicated Server on Windows Server</title>
      <link>https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/</guid>
      <pubDate>Thu, 24 Sep 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>Game servers</category>
      <category>Unattended</category>
      
      <description>SteamCMD and a dedicated server installed on Windows Server, checked by the success line, the executable and the build ID rather than the exit code.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>Unpack SteamCMD to <code>C:\steamcmd</code>. Then install the server with one command that looks the app up first. The examples install 7 Days to Die, whose app ID is <code>294420</code>. Four parts are specific to each game. They are the app ID, the install folder, the server executable&rsquo;s name, and whether the game accepts <code>+login anonymous</code>. The size you expect changes with the game.</p>
<p>In PowerShell on the server:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">New-Item</span> <span class="n">-ItemType</span> <span class="n">Directory</span> <span class="n">-Path</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span> <span class="n">-Force</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl"><span class="nb">Invoke-WebRequest</span> <span class="n">-Uri</span> <span class="s1">&#39;https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-OutFile</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="py">zip</span> <span class="n">-UseBasicParsing</span>
</span></span><span class="line"><span class="cl"><span class="nb">Expand-Archive</span> <span class="n">-Path</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="py">zip</span> <span class="n">-DestinationPath</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span> <span class="n">-Force</span>
</span></span><span class="line"><span class="cl"><span class="nb">Remove-Item</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="py">zip</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="py">exe</span> <span class="p">+</span><span class="n">force_install_dir</span> <span class="s2">&#34;C:\7DaysToDieServer&#34;</span> <span class="p">+</span><span class="n">login</span> <span class="n">anonymous</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="p">+</span><span class="n">app_info_print</span> <span class="mf">294420</span> <span class="p">+</span><span class="n">app_update</span> <span class="mf">294420</span> <span class="n">validate</span> <span class="p">+</span><span class="n">quit</span></span></span></code></pre></div></div>
  </div>
</div><p>The install worked when two things are true. The output contains <code>Success! App '294420' fully installed.</code> And <code>C:\7DaysToDieServer\7DaysToDieServer.exe</code> exists. Don&rsquo;t go by the exit code. A fresh SteamCMD exits 7 on its first run, whether or not the install worked.</p>
<p>Do not run that command with <code>validate</code> later on a server whose <code>serverconfig.xml</code> you&rsquo;ve edited. The <code>validate</code> argument restores the shipped file. <a href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#4-run-it-again-on-an-installed-server">Step 4</a> has the details.</p>
<p>Two errors can end the output: <code>ERROR! Failed to install app '294420' (Missing configuration)</code> and <code>Error! App '294420' state is 0x602 after update job.</code> If either appears, run the same command again. Both cleared on the second run in testing. <a href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#missing-configuration-on-the-first-install"><code>Missing configuration</code></a> is the one most likely to stop you. On a fresh SteamCMD, <code>+app_info_print</code> prevents it.</p>

</div>

<p>The install is one command, which is why the ways it misleads you on a fresh machine are easy to miss. The first run of SteamCMD updates itself and exits 7, including a run that installs the server. The first install on a fresh SteamCMD fails unless SteamCMD has already fetched the app&rsquo;s record. A download of 16 GB can end with one corrupt file, and a rerun repairs it. An install path on a drive that doesn&rsquo;t exist gets a <code>Success!</code> line and an install in the wrong folder. This part installs SteamCMD and the 7 Days to Die server and says how to tell a good install from a bad one. Finding the app ID for another game is <a href="https://looselydecoupled.com/find-steam-dedicated-server-app-id/">Steam App IDs for 25 Dedicated Servers, and How to Confirm One with SteamCMD</a>.</p>
<!-- style-check: procedure -->
<h2 id="1-download-and-unpack-steamcmdzip">1. Download and unpack steamcmd.zip<a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#1-download-and-unpack-steamcmdzip"
     aria-label="Link to section: 1. Download and unpack steamcmd.zip" data-pagefind-ignore></a>
</h2>
<p>Run this in PowerShell on the server. It creates <code>C:\steamcmd</code>, downloads Valve&rsquo;s <code>steamcmd.zip</code> into it, unpacks it and deletes the zip. The zip holds one file, <code>steamcmd.exe</code>, so there is no installer to run. <code>-UseBasicParsing</code> stops <code>Invoke-WebRequest</code> from parsing the download as a web page. <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-5.1" rel="external noopener" target="_blank">Microsoft&rsquo;s documentation<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a> says Windows PowerShell requires it where Internet Explorer isn&rsquo;t installed, and that after a December 2025 security update <code>Invoke-WebRequest</code> asks for confirmation without it, which stalls an unattended script.</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">New-Item</span> <span class="n">-ItemType</span> <span class="n">Directory</span> <span class="n">-Path</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span> <span class="n">-Force</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl"><span class="nb">Invoke-WebRequest</span> <span class="n">-Uri</span> <span class="s1">&#39;https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-OutFile</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="py">zip</span> <span class="n">-UseBasicParsing</span>
</span></span><span class="line"><span class="cl"><span class="nb">Expand-Archive</span> <span class="n">-Path</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="py">zip</span> <span class="n">-DestinationPath</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span> <span class="n">-Force</span>
</span></span><span class="line"><span class="cl"><span class="nb">Remove-Item</span> <span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="n">zip</span></span></span></code></pre></div></div>
  </div>
</div><p>SteamCMD fetches the rest of itself the first time it runs, and that run exits 7. Step 3 and <a href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#exit-code-7-and-other-codes-that-mislead">the exit code section</a> say how to check an install without the exit code.</p>
<h2 id="2-install-the-server-with-app_update">2. Install the server with app_update<a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#2-install-the-server-with-app_update"
     aria-label="Link to section: 2. Install the server with app_update" data-pagefind-ignore></a>
</h2>
<p>This writes about 17 GB under <code>C:\7DaysToDieServer</code> and downloads about that much, and the size grows with the game&rsquo;s versions, so leave the drive a few gigabytes more than that. Check that the drive exists and has the room: <code>Get-PSDrive C | Select-Object Used, Free</code>. The command, with each argument explained:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="py">exe</span> <span class="p">+</span><span class="n">force_install_dir</span> <span class="s2">&#34;C:\7DaysToDieServer&#34;</span> <span class="p">+</span><span class="n">login</span> <span class="n">anonymous</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="p">+</span><span class="n">app_info_print</span> <span class="mf">294420</span> <span class="p">+</span><span class="n">app_update</span> <span class="mf">294420</span> <span class="n">validate</span> <span class="p">+</span><span class="n">quit</span></span></span></code></pre></div></div>
  </div>
</div><div class="table-wrap" data-scrollable data-label="Table: Argument">
  <table>
    <thead>
      <tr><th scope="col">Argument</th><th scope="col">What it does</th></tr>
    </thead>
    <tbody>
      <tr><td><code>+force_install_dir &quot;C:\7DaysToDieServer&quot;</code></td><td>The folder the server goes in. SteamCMD creates it. Keep the quotes</td></tr>
      <tr><td><code>+login anonymous</code></td><td>Signs in without an account. <a href="https://looselydecoupled.com/find-steam-dedicated-server-app-id/">Steam App IDs for 25 Dedicated Servers, and How to Confirm One with SteamCMD</a> says which servers allow it</td></tr>
      <tr><td><code>+app_info_print 294420</code></td><td>Fetches the app&rsquo;s record and prints it, about 550 lines. Without it, or an earlier run that signed in, the first install on a fresh SteamCMD fails</td></tr>
      <tr><td><code>+app_update 294420 validate</code></td><td>Installs the app, or repairs an existing install by checking every file</td></tr>
      <tr><td><code>+quit</code></td><td>Ends the session. Without it SteamCMD stays open instead of exiting</td></tr>
    </tbody>
  </table>
</div>
<p>Keep the quotes around the folder. Without them, a path with a space splits at the space. I ran a small app with <code>+force_install_dir C:\scratch\p2 space\lit</code>, and SteamCMD installed it into <code>C:\scratch\p2</code>, exited with code <code>0</code> and printed no warning. With the path in quotes it installed where I told it to.</p>
<p>On a fresh SteamCMD the first part of the output is SteamCMD updating itself. A complete download and install took several minutes on this server. Near the end of a successful run the output reads as follows, and a few lines of shutdown messages follow it. The progress numbers differ from run to run:</p>
<div class="code-block" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl"> Update state (0x101) committing, progress: 89.68 (16115623152 / 17970674557)
</span></span><span class="line"><span class="cl"> Update state (0x0) unknown, progress: 0.00 (0 / 0)
</span></span><span class="line"><span class="cl">Success! App &#39;294420&#39; fully installed.</span></span></code></pre></div></div>
  </div>
</div><h2 id="3-confirm-the-install">3. Confirm the install<a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#3-confirm-the-install"
     aria-label="Link to section: 3. Confirm the install" data-pagefind-ignore></a>
</h2>
<p>Check three things: the <code>Success!</code> line from step 2, the executable at the path you chose, and the manifest SteamCMD writes for the app. A path SteamCMD can&rsquo;t use isn&rsquo;t an error, as <a href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#success-but-the-files-are-in-the-wrong-folder">one of the failures</a> shows, so look at the path and don&rsquo;t rely on the <code>Success!</code> line alone. The last two checks are:</p>
<div class="console"><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">Test-Path</span> <span class="console__token">C:\7DaysToDieServer\7DaysToDieServer.exe</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">True</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__command" data-copyable data-copy-label="command">
    <div class="code-block__head"><span class="code-block__lang">Command</span></div>
    <div class="code-block__scroll"><pre data-copy-source><code><span class="line"><span class="prompt">PS&gt; </span><span class="console__token">Select-String</span> <span class="console__token">-Path</span> <span class="console__token">C:\7DaysToDieServer\steamapps\appmanifest_294420.acf</span> <span class="console__token">`</span>
</span><span class="line"><span class="prompt">&gt;     </span><span class="console__token">-Pattern</span> <span class="console__token">&#39;&#34;(StateFlags|buildid)&#34;&#39;</span> <span class="console__token">|</span>
</span><span class="line"><span class="prompt">&gt;     </span><span class="console__token">ForEach-Object</span> <span class="console__token">{</span> <span class="console__token">$_.Line.Trim()</span> <span class="console__token">-replace</span> <span class="console__token">&#39;\t+&#39;,</span> <span class="console__token">&#39;</span>  <span class="console__token">&#39;</span> <span class="console__token">}</span></span></code></pre>
    </div>
  </div><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Output</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">&#34;StateFlags&#34;</span>  <span class="console__token">&#34;4&#34;</span>
</span><span class="line"><span class="console__token">&#34;buildid&#34;</span>  <span class="console__token">&#34;26237934&#34;</span></span></code></pre>
    </div>
  </div></div><p><code>StateFlags</code> is <code>4</code> after a complete install. A failed install leaves a different value: the failed install in <a href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#state-is-0x602-after-update-job-at-the-end-of-the-download">the 0x602 section</a> left <code>1538</code>. <code>buildid</code> is the build you installed. A later part uses it to decide whether Steam has published a newer one.</p>
<h2 id="4-run-it-again-on-an-installed-server">4. Run it again on an installed server<a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#4-run-it-again-on-an-installed-server"
     aria-label="Link to section: 4. Run it again on an installed server" data-pagefind-ignore></a>
</h2>
<p>The same command works on a server that is already installed. <a href="https://looselydecoupled.com/update-7-days-to-die-server-only-on-new-build/">Update a 7 Days to Die Dedicated Server Only When There Is a New Build</a> uses it to update. With <code>validate</code> it checks every file, which took a minute or two here, and ends with the same <code>fully installed</code> line:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="py">exe</span> <span class="p">+</span><span class="n">force_install_dir</span> <span class="s2">&#34;C:\7DaysToDieServer&#34;</span> <span class="p">+</span><span class="n">login</span> <span class="n">anonymous</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="p">+</span><span class="n">app_update</span> <span class="mf">294420</span> <span class="n">validate</span> <span class="p">+</span><span class="n">quit</span></span></span></code></pre></div></div>
  </div>
</div><p>Without <code>validate</code> it doesn&rsquo;t check every file. On an up-to-date server it did nothing, took a few seconds and ended <code>Success! App '294420' already up to date.</code></p>
<p><code>validate</code> also restores every file to the version Valve ships, including <code>serverconfig.xml</code>. I changed <code>ServerName</code> and <code>ServerMaxPlayerCount</code> in that file and ran the command with <code>validate</code>. Both were back to the shipped values, and the file matched the shipped original. The same command without <code>validate</code> left my edit alone. A copy of the file under another name, and a note file that isn&rsquo;t part of the install, survived <code>validate</code>. So keep your settings in a copy and start the server with <code>-configfile=</code> naming it. <a href="https://looselydecoupled.com/configure-7-days-to-die-server-and-open-ports/">Configure a 7 Days to Die Dedicated Server and Open Its Ports</a> does that.</p>
<!-- style-check: end procedure -->
<h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="missing-configuration-on-the-first-install"><code>Missing configuration</code> on the first install<a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#missing-configuration-on-the-first-install"
     aria-label="Link to section: Missing configuration on the first install" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">ERROR!</span> <span class="console__token">Failed</span> <span class="console__token">to</span> <span class="console__token">install</span> <span class="console__token">app</span> <span class="console__token">&#39;294420&#39;</span> <span class="console__token">(Missing</span> <span class="console__token">configuration)</span></span></code></pre>
    </div>
  </div></div><p>A fresh SteamCMD fails the first install before it downloads anything, and the same command succeeds when you run it again. I ran two or three trials of each case on a fresh SteamCMD with Core Keeper&rsquo;s server (app <code>1963720</code>), which is a small download:</p>
<ul>
<li>The install as the first run exited 7 with the error.</li>
<li>The install after one <code>+quit</code> run, or two, exited 8 with the error.</li>
<li>The install with <code>+app_info_update 1</code> added exited 8 with the error.</li>
<li>The install in the same command as a lookup of a different app, <code>+app_info_print 440</code>, exited 8 with the error.</li>
<li>The install in the same command as a lookup of the app itself, <code>+app_info_print 1963720</code>, succeeded every time.</li>
<li>The install after an earlier run that signed in, <code>+login anonymous +quit</code>, succeeded every time.</li>
<li>The install after an earlier run that looked up an app, the same one or a different one, succeeded every time.</li>
</ul>
<p>So the first install fails unless SteamCMD has already signed in anonymously in an earlier run, or the same command looks up the app being installed. The 7 Days to Die server failed on a SteamCMD that had run <code>+quit</code> twice, and succeeded with <code>+app_info_print 294420</code> in the same command. Either put the lookup before <code>+app_update</code> as in step 2, or run <code>C:\steamcmd\steamcmd.exe +login anonymous +quit</code> once before the install. I don&rsquo;t know why either works.</p>
<h3 id="success-but-the-files-are-in-the-wrong-folder"><code>Success!</code> but the files are in the wrong folder<a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#success-but-the-files-are-in-the-wrong-folder"
     aria-label="Link to section: Success! but the files are in the wrong folder" data-pagefind-ignore></a>
</h3>
<p>An install path that SteamCMD can&rsquo;t use isn&rsquo;t an error. With no drive <code>Z:</code> on the machine, this command printed <code>Success! App '1963720' fully installed.</code> and exited <code>0</code>:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">C:</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">\</span><span class="n">steamcmd</span><span class="p">.</span><span class="py">exe</span> <span class="p">+</span><span class="n">force_install_dir</span> <span class="s2">&#34;Z:\nope&#34;</span> <span class="p">+</span><span class="n">login</span> <span class="n">anonymous</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="p">+</span><span class="n">app_update</span> <span class="mf">1963720</span> <span class="p">+</span><span class="n">quit</span></span></span></code></pre></div></div>
  </div>
</div><p>Nothing was created on <code>Z:</code>. The server went under the SteamCMD folder, in <code>steamapps\common\Core Keeper Dedicated Server</code>, with its manifest and executable. That happened in three of three trials. A folder that doesn&rsquo;t exist yet on a drive that does, such as <code>C:\7DaysToDieServer</code>, is created. Check that the drive exists with <code>Test-Path Z:\</code>, and check that the executable exists at the path you chose.</p>
<h3 id="state-is-0x602-after-update-job-at-the-end-of-the-download"><code>state is 0x602 after update job</code> at the end of the download<a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#state-is-0x602-after-update-job-at-the-end-of-the-download"
     aria-label="Link to section: state is 0x602 after update job at the end of the download" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">Error!</span> <span class="console__token">App</span> <span class="console__token">&#39;294420&#39;</span> <span class="console__token">state</span> <span class="console__token">is</span> <span class="console__token">0x602</span> <span class="console__token">after</span> <span class="console__token">update</span> <span class="console__token">job.</span></span></code></pre>
    </div>
  </div></div><p>The last progress line was 98.59%, and SteamCMD then rejected the files it had staged. <code>logs\content_log.txt</code> under the SteamCMD folder says why: <code>Staged file validation failed (0 missing, 1 corrupt, 0 unreadable) (Corrupt update files)</code>. The server&rsquo;s folder had no <code>7DaysToDieServer.exe</code> and the manifest read <code>StateFlags</code> <code>1538</code>. Run the same install command again. In my run the second one finished in 21 seconds with <code>fully installed</code>. It happened once in my first three complete installs from a fresh SteamCMD.</p>
<h3 id="exit-code-7-and-other-codes-that-mislead">Exit code 7 and other codes that mislead<a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#exit-code-7-and-other-codes-that-mislead"
     aria-label="Link to section: Exit code 7 and other codes that mislead" data-pagefind-ignore></a>
</h3>
<p>The exit code of <code>steamcmd.exe</code> doesn&rsquo;t say whether the install worked:</p>
<ul>
<li>The first run of a fresh SteamCMD exits <code>7</code>. When that run also installs the server the output contains <code>Success!</code>, and when the install fails it exits <code>7</code> as well.</li>
<li>A refused install, for example <code>No subscription</code>, exits <code>8</code>.</li>
<li>A command SteamCMD doesn&rsquo;t know, for example <code>+no_such_command</code>, prints <code>Command not found: no_such_command</code> and exits <code>0</code>.</li>
<li>An install path on a drive that doesn&rsquo;t exist exits <code>0</code> and prints <code>Success!</code>, as the previous section shows.</li>
</ul>
<p>Look for a <code>Success!</code> line in the output, and check that the executable exists at the path you chose. A <code>Success!</code> line is followed by a few lines of shutdown messages, so test for it with <code>Select-String</code> and not as the last line. A script that tests only <code>$LASTEXITCODE</code> calls a good first install a failure and a mistyped command a success.</p>
<h3 id="no-subscription"><code>No subscription</code><a class="heading-anchor" href="https://looselydecoupled.com/install-steamcmd-steam-dedicated-server-windows/#no-subscription"
     aria-label="Link to section: No subscription" data-pagefind-ignore></a>
</h3>
<div class="console console--error"><div class="code-block code-block--wrap console__output">
    <p class="console__output-label">Error</p>
    <div class="code-block__scroll"><pre><code><span class="line"><span class="console__token">ERROR!</span> <span class="console__token">Failed</span> <span class="console__token">to</span> <span class="console__token">install</span> <span class="console__token">app</span> <span class="console__token">&#39;223350&#39;</span> <span class="console__token">(No</span> <span class="console__token">subscription)</span></span></code></pre>
    </div>
  </div></div><p>That&rsquo;s DayZ&rsquo;s server, app <code>223350</code>. The install was refused for an anonymous login. The ID is the game&rsquo;s, or the server isn&rsquo;t available anonymously. An ID that no app has fails with <code>Missing configuration</code> instead. <a href="https://looselydecoupled.com/find-steam-dedicated-server-app-id/">Steam App IDs for 25 Dedicated Servers, and How to Confirm One with SteamCMD</a> tells them apart.</p>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2025 Datacenter (10.0.26100), virtual machine</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>Windows PowerShell 5.1, elevated</dd></div>
    <div class="tested__row"><dt>SteamCMD</dt> <dd>client version 1792617903, anonymous login</dd></div>
    <div class="tested__row"><dt>Game</dt> <dd>7 Days to Die dedicated server (294420), V 3.4.0, build 26237934</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>October 2026</dd></div>
  </dl>
</div>
]]></content:encoded>
    </item>
    
    <item>
      <title>Why $LASTEXITCODE Doesn&#39;t Work the Way You Expect in PowerShell</title>
      <link>https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/</guid>
      <pubDate>Wed, 23 Sep 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>PowerShell</category>
      <category>Unattended</category>
      
      <description>Cmdlets never set LASTEXITCODE, so after a failed cmdlet it still holds whatever the last native program returned, often zero.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p><code>$LASTEXITCODE</code> is not the success status of the last PowerShell cmdlet. Use it
for a native executable such as <code>aws.exe</code>, and capture it immediately:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">aws</span> <span class="p">-</span><span class="n">-version</span>
</span></span><span class="line"><span class="cl"><span class="nv">$Code</span> <span class="p">=</span> <span class="nv">$LASTEXITCODE</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nv">$Code</span> <span class="o">-ne</span> <span class="mf">0</span><span class="p">)</span> <span class="p">{</span> <span class="k">throw</span> <span class="s2">&#34;AWS CLI exited with code </span><span class="nv">$Code</span><span class="s2">&#34;</span> <span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>For a cmdlet, use PowerShell error handling:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-Item</span> <span class="n">-LiteralPath</span> <span class="s1">&#39;C:\Data\settings.json&#39;</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span></span></span></code></pre></div></div>
  </div>
</div><p><code>-ErrorAction Stop</code> turns a cmdlet&rsquo;s non-terminating error into a terminating
one, which stops the script or reaches an enclosing <code>catch</code>.</p>

</div>

<p>While working on a backup script for my
<a href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/">7 Days to Die game server</a>,
I thought it would be good to share this.</p>
<p>You replace an AWS CLI command with a PowerShell cmdlet and keep the success
check. The cmdlet prints an error. The script announces success anyway.</p>
<p>The check still runs. It&rsquo;s reading the result of a different operation.</p>
<!-- style-check: procedure -->
<h2 id="reproduce-a-failed-command-with-exit-code-zero">Reproduce a failed command with exit code zero<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#reproduce-a-failed-command-with-exit-code-zero"
     aria-label="Link to section: Reproduce a failed command with exit code zero" data-pagefind-ignore></a>
</h2>
<p>Run this in PowerShell on Windows:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">cmd</span><span class="p">.</span><span class="py">exe</span> <span class="p">/</span><span class="n">d</span> <span class="p">/</span><span class="n">c</span> <span class="n">exit</span> <span class="mf">0</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Error</span> <span class="s1">&#39;Demonstration: the upload failed&#39;</span> <span class="n">-ErrorAction</span> <span class="k">Continue</span>
</span></span><span class="line"><span class="cl"><span class="s2">&#34;Native exit code: </span><span class="nv">$LASTEXITCODE</span><span class="s2">&#34;</span></span></span></code></pre></div></div>
  </div>
</div><p>The error appears, followed by:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">Native exit code: 0</span></span></code></pre></div></div>
  </div>
</div><p>The zero came from <code>cmd.exe</code>. <code>Write-Error</code> did not update it. The explicit
<code>Continue</code> makes this demonstration non-terminating even if your session normally
uses a stricter error preference.</p>
<p>The reverse is just as misleading:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">cmd</span><span class="p">.</span><span class="py">exe</span> <span class="p">/</span><span class="n">d</span> <span class="p">/</span><span class="n">c</span> <span class="n">exit</span> <span class="mf">7</span>
</span></span><span class="line"><span class="cl"><span class="nb">Get-Date</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl"><span class="s2">&#34;Native exit code: </span><span class="nv">$LASTEXITCODE</span><span class="s2">&#34;</span></span></span></code></pre></div></div>
  </div>
</div><p>This prints <code>7</code> even though <code>Get-Date</code> succeeded. These examples illustrate why
a value left in the variable is not evidence about a later cmdlet.</p>
<p>Microsoft defines the variable for native programs and PowerShell scripts;
script behavior also depends on invocation and the <code>exit</code> keyword. Ordinary
cmdlet success or failure does not make it a universal status register. See
<a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables#lastexitcode" rel="external noopener" target="_blank">about_Automatic_Variables<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>.</p>
<h2 id="for-native-commands-check-each-result-at-the-boundary">For native commands, check each result at the boundary<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#for-native-commands-check-each-result-at-the-boundary"
     aria-label="Link to section: For native commands, check each result at the boundary" data-pagefind-ignore></a>
</h2>
<p>This example assumes AWS CLI is installed, the source exists, and the active
AWS identity can access your chosen bucket:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$Source</span> <span class="p">=</span> <span class="s1">&#39;C:\Data\exports&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$Destination</span> <span class="p">=</span> <span class="s1">&#39;s3://YOUR-BUCKET/exports/&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="vm">$null</span> <span class="p">=</span> <span class="nb">Get-Command</span> <span class="n">aws</span> <span class="n">-CommandType</span> <span class="n">Application</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl"><span class="n">aws</span> <span class="n">s3</span> <span class="n">sync</span> <span class="nv">$Source</span> <span class="nv">$Destination</span>
</span></span><span class="line"><span class="cl"><span class="nv">$Code</span> <span class="p">=</span> <span class="nv">$LASTEXITCODE</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nv">$Code</span> <span class="o">-ne</span> <span class="mf">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">throw</span> <span class="s2">&#34;S3 sync did not complete cleanly; AWS CLI exit code </span><span class="nv">$Code</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="s1">&#39;Export transfer completed&#39;</span></span></span></code></pre></div></div>
  </div>
</div><p>Replace <code>YOUR-BUCKET</code> before running it. AWS documents nonzero outcomes including
failed S3 transfers and skipped files. A skipped file is enough to reject a
backup run as incomplete; inspect the command output for the cause. See the
<a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-returncodes.html" rel="external noopener" target="_blank">AWS CLI return-code reference<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>.</p>
<div class="admonition admonition--warning" role="note">
  <p class="admonition__label">
    <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#i-triangle-alert"/></svg>
    <span>Warning</span>
  </p>
  <p>Do not run three transfers and check only after the third. A later successful
native command replaces an earlier failure code with zero, so the script
reports success for a backup that partly failed. That is worse than no
success message at all: you now have positive evidence for something untrue,
and you will not look again until you need the data.</p>
</div><p>Capture and handle each result before moving on.</p>
<p>Also distinguish a process failure from a launch failure. If <code>aws</code> is not
found, no AWS CLI process returned an exit code, and the check reads whatever
an earlier native command left. The <code>Get-Command</code> line stops the script before
that can happen.</p>
<!-- style-check: end procedure -->
<h2 id="why-trycatch-sometimes-misses-a-cmdlet-error">Why try/catch sometimes misses a cmdlet error<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#why-trycatch-sometimes-misses-a-cmdlet-error"
     aria-label="Link to section: Why try/catch sometimes misses a cmdlet error" data-pagefind-ignore></a>
</h2>
<p>PowerShell can report an error while continuing execution. For example:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Error</span> <span class="s1">&#39;Demonstration failure&#39;</span> <span class="n">-ErrorAction</span> <span class="k">Continue</span>
</span></span><span class="line"><span class="cl">    <span class="s1">&#39;Still inside try&#39;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="s1">&#39;Caught the error&#39;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>The error is displayed and <code>Still inside try</code> prints. The catch block isn&rsquo;t
entered. Change that one invocation to <code>-ErrorAction Stop</code> and the catch block
runs instead.</p>
<p>Some errors already terminate execution; they don&rsquo;t need this promotion.
<code>-ErrorAction Stop</code> makes the intended behavior explicit for cmdlet errors that
would otherwise continue. Microsoft&rsquo;s <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally" rel="external noopener" target="_blank">try/catch documentation<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>
explains which errors those blocks handle.</p>
<h2 id="catch-a-write-s3object-failure-with--erroraction-stop">Catch a <code>Write-S3Object</code> failure with <code>-ErrorAction Stop</code><a class="heading-anchor" href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#catch-a-write-s3object-failure-with--erroraction-stop"
     aria-label="Link to section: Catch a Write-S3Object failure with -ErrorAction Stop" data-pagefind-ignore></a>
</h2>
<p>With <code>AWS.Tools.S3</code> installed and AWS access configured, use this for an
intentional upload of one existing file:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Import-Module</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">S3</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-S3Object</span> <span class="n">-BucketName</span> <span class="s1">&#39;YOUR-BUCKET&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">        <span class="o">-File</span> <span class="s1">&#39;C:\Data\exports\report.json&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">        <span class="n">-Key</span> <span class="s1">&#39;exports/report.json&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">        <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="s1">&#39;Upload completed&#39;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Warning</span> <span class="p">(</span><span class="s2">&#34;Upload failed: {0}&#34;</span> <span class="o">-f</span> <span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">throw</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
  </div>
</div><p>The success message is reachable only after the upload returns normally. The
bare <code>throw</code> propagates the caught error to the caller. Logging and then
continuing would hide the failure from whatever invoked the script.</p>
<p>If you have no context to add and no recovery to attempt, remove the <code>try/catch</code>
and keep <code>-ErrorAction Stop</code>. A catch block that only rethrows isn&rsquo;t required.</p>
<h2 id="psnativecommanduseerroractionpreference-in-powershell-7"><code>$PSNativeCommandUseErrorActionPreference</code> in PowerShell 7<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#psnativecommanduseerroractionpreference-in-powershell-7"
     aria-label="Link to section: $PSNativeCommandUseErrorActionPreference in PowerShell 7" data-pagefind-ignore></a>
</h2>
<p>PowerShell 7.4 added <code>$PSNativeCommandUseErrorActionPreference</code>. When it&rsquo;s
<code>$true</code>, nonzero native exit codes produce PowerShell errors governed by
<code>$ErrorActionPreference</code>; with <code>Stop</code>, those can reach <code>catch</code>. The default is
<code>$false</code>. Microsoft documents it in
<a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables#psnativecommanduseerroractionpreference" rel="external noopener" target="_blank">about_Preference_Variables<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>.</p>
<p>That doesn&rsquo;t make <code>-ErrorAction Stop</code> a parameter for <code>aws.exe</code>. Passed to a
native program, it&rsquo;s an argument for that program to interpret. Explicit
exit-code checks remain useful for scripts spanning Windows PowerShell 5.1 and
PowerShell 7, and for tools whose nonzero codes have special meanings.</p>
<p>If native error promotion is enabled with <code>Stop</code>, execution can leave the native
invocation before the following explicit check. Either path must preserve the
failure; don&rsquo;t catch it and then print success.</p>
<h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/powershell-lastexitcode-cmdlet-errors/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<p><strong>LASTEXITCODE is empty or stale.</strong> There may be no relevant native result in the
session. Choose the error mechanism for the operation you actually ran.</p>
<p><strong>Can I replace it with <code>$?</code> everywhere?</strong> <code>$?</code> describes the last command&rsquo;s
execution status and is overwritten by the next command. It isn&rsquo;t a durable
record of a multi-step job. Structured error handling is clearer for cmdlets.</p>
<p><strong>The task still reports success.</strong> Check whether a wrapper catches and suppresses
the error, then exits normally. At the outer script boundary, preserve a failure
through an unhandled terminating error or an intentional nonzero <code>exit</code> code.</p>
<p>A script needs to remember whether the work succeeded. That starts by listening
to the failure signal the command actually provides.</p>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2019 (10.0.17763)</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>Windows PowerShell 5.1</dd></div>
    <div class="tested__row"><dt>PowerShell 7 section</dt> <dd>7.6.6 on macOS 27.0</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>October 2026</dd></div>
  </dl>
</div>
]]></content:encoded>
    </item>
    
    <item>
      <title>How to Install AWS Tools for PowerShell for All Users on Windows</title>
      <link>https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/</guid>
      <pubDate>Mon, 07 Sep 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>Unattended</category>
      <category>AWS</category>
      <category>PowerShell</category>
      
      <description>You end up with AWS.Tools in Program Files, where a task running as SYSTEM finds it; SYSTEM&#39;s module path never includes your Documents folder.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>Open the PowerShell edition that your automation uses, <strong>as Administrator</strong>.
In Windows PowerShell 5.1, run this block first:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$protocol</span> <span class="p">=</span> <span class="p">[</span><span class="no">Net.ServicePointManager</span><span class="p">]::</span><span class="n">SecurityProtocol</span>
</span></span><span class="line"><span class="cl"><span class="nv">$tls12</span> <span class="p">=</span> <span class="p">[</span><span class="no">Net.SecurityProtocolType</span><span class="p">]::</span><span class="n">Tls12</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nv">$protocol</span> <span class="o">-ne</span> <span class="s1">&#39;SystemDefault&#39;</span> <span class="o">-and</span> <span class="o">-not</span> <span class="p">(</span><span class="nv">$protocol</span> <span class="o">-band</span> <span class="nv">$tls12</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">Net.ServicePointManager</span><span class="p">]::</span><span class="n">SecurityProtocol</span> <span class="p">=</span> <span class="nv">$protocol</span> <span class="o">-bor</span> <span class="nv">$tls12</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">Install-PackageProvider</span> <span class="n">-Name</span> <span class="n">NuGet</span> <span class="n">-MinimumVersion</span> <span class="mf">2.8</span><span class="p">.</span><span class="py">5</span><span class="p">.</span><span class="py">201</span> <span class="n">-Force</span> <span class="p">|</span> <span class="nb">Out-Null</span></span></span></code></pre></div></div>
  </div>
</div><p>The gallery needs TLS 1.2, as Microsoft&rsquo;s
<a href="https://devblogs.microsoft.com/powershell/powershell-gallery-tls-support/" rel="external noopener" target="_blank">PowerShell Gallery TLS post<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>
explains. The NuGet provider download needs TLS 1.2 too, so the TLS check
comes before the provider install. The <code>if</code> adds TLS 1.2 only when the
session has neither TLS 1.2 nor the operating system&rsquo;s default. It never removes a protocol. It leaves the operating system&rsquo;s default alone, as Microsoft&rsquo;s
<a href="https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls#recommendations" rel="external noopener" target="_blank">TLS guidance<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>
recommends. The operating system&rsquo;s default can negotiate newer versions of
TLS. On the test server, the check changed nothing. The last line installs
the NuGet provider, and does nothing where the provider is already in place.</p>
<p>Then install the modular S3 package for all users:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Install-Module</span> <span class="n">-Name</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">Installer</span> <span class="n">-MinimumVersion</span> <span class="mf">2.0</span><span class="p">.</span><span class="py">0</span> <span class="n">-MaximumVersion</span> <span class="mf">2.9</span><span class="p">.</span><span class="py">999</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Repository</span> <span class="n">PSGallery</span> <span class="n">-Scope</span> <span class="n">AllUsers</span> <span class="n">-Force</span>
</span></span><span class="line"><span class="cl"><span class="nb">Import-Module</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">Installer</span> <span class="n">-MinimumVersion</span> <span class="mf">2.0</span><span class="p">.</span><span class="py">0</span> <span class="n">-MaximumVersion</span> <span class="mf">2.9</span><span class="p">.</span><span class="py">999</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl"><span class="nb">Install-AWSToolsModule</span> <span class="n">-Name</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">S3</span> <span class="n">-Version</span> <span class="s1">&#39;5.*&#39;</span> <span class="n">-Scope</span> <span class="n">AllUsers</span></span></span></code></pre></div></div>
  </div>
</div><p>Swap <code>AWS.Tools.S3</code> for the service module that your script calls.</p>
<p>An older 1.x installer may already be on the machine. Version 1.x of the
installer has no <code>-Version</code> parameter. If 1.x loads, the last line fails.
Without <code>-Force</code>, <code>Install-Module</code> only warns that 1.x is already installed,
and leaves 1.x in place. With <code>-Force</code>, <code>Install-Module</code> installs 2.x beside
1.x, and the import line loads 2.x. <code>-MaximumVersion 2.9.999</code> on both lines
keeps a future 3.x out of a workflow written for 2.x. AWS&rsquo;s own install
command uses the same limit.</p>
<p>Keep <code>-Version '5.*'</code>. Without <code>-Version</code>, the installer takes the latest
major version, which can carry breaking changes, as AWS&rsquo;s
<a href="https://aws.amazon.com/blogs/developer/aws-tools-installer-v2-is-now-generally-available/" rel="external noopener" target="_blank">Installer v2 announcement<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>
warns. With <code>-Name</code>, the installer installs only the modules you name, plus
<code>AWS.Tools.Common</code>. Other AWS.Tools modules stay at their current versions.
If your tasks use several modules that should move in step, name every one
of those modules.</p>
<p>In Windows PowerShell 5.1, the gallery may stay unreachable after the TLS check and the provider install. Then TLS isn&rsquo;t the cause. Look at a proxy, DNS or a firewall. An install
that reaches the gallery and then fails has a different cause. One such
cause is the .NET or PowerShellGet version that the package requires.</p>
<p>Verify from a fresh session under the account that runs the task:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Import-Module</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">S3</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl"><span class="p">(</span><span class="nb">Get-Module</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="n">S3</span><span class="p">).</span><span class="n">ModuleBase</span></span></span></code></pre></div></div>
  </div>
</div><p>For Windows PowerShell, the path should start
<code>$env:ProgramFiles\WindowsPowerShell\Modules\</code>. For PowerShell 7, the path
should start <code>$env:ProgramFiles\PowerShell\Modules\</code>. <code>$env:ProgramFiles</code> is
<code>C:\Program Files</code> for a 64-bit host, and <code>C:\Program Files (x86)</code> for a
32-bit one.</p>
<div class="admonition admonition--note" role="note">
  <p class="admonition__label">
    <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-info"/></svg>
    <span>Note</span>
  </p>
  <p>Module availability and AWS authentication are separate problems that fail at
different points. A task that imports the module and then reports access
denied has finished with this article.</p>
</div>
</div>

<p>The script works in your terminal. Task Scheduler reports that <code>Write-S3Object</code>
isn&rsquo;t recognized.</p>
<p>Before rewriting the script, check where you installed its dependencies. A
module beneath your Documents folder is an installation for you. The scheduled
task may run as someone else, using a different PowerShell executable.</p>
<h2 id="choose-awstools-for-a-new-installation">Choose AWS.Tools for a new installation<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#choose-awstools-for-a-new-installation"
     aria-label="Link to section: Choose AWS.Tools for a new installation" data-pagefind-ignore></a>
</h2>
<p>AWS currently recommends <code>AWS.Tools</code>, with separate service modules such as
<code>AWS.Tools.S3</code> and a shared <code>AWS.Tools.Common</code> dependency. The installer manages
dependencies and coordinates service-module versions. Follow the
<a href="https://docs.aws.amazon.com/powershell/v5/userguide/ps-installing-awstools.html" rel="external noopener" target="_blank">AWS modular installation guide<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>
for that workflow.</p>
<p>For a script that uploads to S3, install S3. Add <code>AWS.Tools.EC2</code> or another
service module when the script actually uses it.</p>
<p>The Windows installation options also include the large <code>AWSPowerShell.NetCore</code>
module and the legacy Windows-specific <code>AWSPowerShell</code> module. They are separate
packaging choices, not three prerequisites to install together. AWS lists them
in its <a href="https://docs.aws.amazon.com/powershell/v5/userguide/pstools-getting-set-up-windows.html" rel="external noopener" target="_blank">Windows setup overview<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>.</p>
<!-- style-check: procedure -->
<h2 id="use-the-same-powershell-host-as-the-scheduled-task">Use the same PowerShell host as the scheduled task<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#use-the-same-powershell-host-as-the-scheduled-task"
     aria-label="Link to section: Use the same PowerShell host as the scheduled task" data-pagefind-ignore></a>
</h2>
<p>Check the shell before installing:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$PSVersionTable</span> <span class="p">|</span> <span class="nb">Select-Object</span> <span class="n">PSVersion</span><span class="p">,</span> <span class="n">PSEdition</span>
</span></span><span class="line"><span class="cl"><span class="p">(</span><span class="nb">Get-Process</span> <span class="n">-Id</span> <span class="nv">$PID</span><span class="p">).</span><span class="py">Path</span>
</span></span><span class="line"><span class="cl"><span class="nv">$env:PSModulePath</span> <span class="n">-split</span> <span class="s1">&#39;;&#39;</span></span></span></code></pre></div></div>
  </div>
</div><p>For new automation, use a supported PowerShell 7 release. For an existing
Windows PowerShell 5.1 task, verify package and .NET requirements before changing
its dependencies. Do not assume a package&rsquo;s major-version upgrade is only a
packaging change.</p>
<p>Typical system-wide module locations differ:</p>
<div class="table-wrap" data-scrollable data-label="Table: Shell">
  <table>
    <thead>
      <tr><th scope="col">Shell</th><th scope="col">Usual AllUsers location</th></tr>
    </thead>
    <tbody>
      <tr><td>PowerShell 7 (<code>pwsh.exe</code>)</td><td><code>C:\Program Files\PowerShell\Modules</code></td></tr>
      <tr><td>Windows PowerShell 5.1 (<code>powershell.exe</code>)</td><td><code>C:\Program Files\WindowsPowerShell\Modules</code></td></tr>
    </tbody>
  </table>
</div>
<p>PowerShell discovers modules through <code>$env:PSModulePath</code>, and the sharing runs
one way: PowerShell 7 also searches the Windows PowerShell AllUsers folder, but
Windows PowerShell never searches PowerShell 7&rsquo;s. A successful import in one
edition is not proof that the other can load the same installation. Microsoft documents the defaults and
startup behavior in <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_psmodulepath" rel="external noopener" target="_blank">about_PSModulePath<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>.</p>
<p>Check the executable configured in Task Scheduler, including its architecture:
a 32-bit <code>powershell.exe</code> resolves <code>Program Files</code> to <code>Program Files (x86)</code>. Use
that host for the verification below.</p>
<h2 id="install-once-in-an-elevated-session">Install once in an elevated session<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#install-once-in-an-elevated-session"
     aria-label="Link to section: Install once in an elevated session" data-pagefind-ignore></a>
</h2>
<p>Run the commands in the answer box. Keep <code>-Scope AllUsers</code> on both installation
commands: installing the installer globally does not make the service package&rsquo;s
scope implicit.</p>
<p><code>Install-Module</code> comes from PowerShellGet. If it is missing, provision
PowerShellGet before running this workflow; an older installation may prompt
for a NuGet provider. Check that the repository is the one you intend to use:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-Command</span> <span class="nb">Install-Module</span>
</span></span><span class="line"><span class="cl"><span class="nb">Get-PSRepository</span> <span class="n">-Name</span> <span class="n">PSGallery</span></span></span></code></pre></div></div>
  </div>
</div><p>Review the Gallery prompt when it appears. A one-time installation does not
require changing the repository&rsquo;s trust policy permanently. The installer
itself comes from PSGallery, but <code>Install-AWSToolsModule</code> downloads the service
modules as one archive from <code>sdk-for-net.amazonwebservices.com</code>, which its help
says, and not from PSGallery. A server behind a proxy needs that host allowed
as well as the Gallery&rsquo;s own, which Microsoft lists under
<a href="https://learn.microsoft.com/en-us/powershell/gallery/getting-started#network-access-to-the-powershell-gallery" rel="external noopener" target="_blank">network access to the PowerShell Gallery<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>.
Microsoft&rsquo;s
<a href="https://learn.microsoft.com/en-us/powershell/module/powershellget/install-module" rel="external noopener" target="_blank">Install-Module documentation<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>
explains scope, repository selection, and installation prompts.</p>
<p>The installer pulls in <code>AWS.Tools.Common</code> with S3. You do not need to install
every AWS module. The example also omits <code>-CleanUp</code>, which removes older module
versions; decide on cleanup after checking whether existing jobs pin them.</p>
<h2 id="verify-the-module-loads-as-the-task-account">Verify the module loads as the task account<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#verify-the-module-loads-as-the-task-account"
     aria-label="Link to section: Verify the module loads as the task account" data-pagefind-ignore></a>
</h2>
<p>Close the elevated session. You can&rsquo;t open a console as SYSTEM, and a
scheduled task keeps none of its output. Put these lines at the top of the
task&rsquo;s script, start it with <code>Start-ScheduledTask</code>, and read the log it writes:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="p">&amp;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">Security.Principal.WindowsIdentity</span><span class="p">]::</span><span class="n">GetCurrent</span><span class="p">().</span><span class="py">Name</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$env:PSModulePath</span> <span class="n">-split</span> <span class="s1">&#39;;&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nb">Get-Module</span> <span class="n">-ListAvailable</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="n">Common</span><span class="p">,</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">S3</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Select-Object</span> <span class="n">Name</span><span class="p">,</span> <span class="n">Version</span><span class="p">,</span> <span class="n">ModuleBase</span> <span class="p">|</span> <span class="nb">Format-Table</span> <span class="n">-AutoSize</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nb">Import-Module</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">S3</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl">    <span class="p">(</span><span class="nb">Get-Module</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="n">S3</span><span class="p">).</span><span class="py">ModuleBase</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="p">*&gt;</span> <span class="p">(</span><span class="nb">Join-Path</span> <span class="nv">$env:ProgramData</span> <span class="s1">&#39;aws-tools-check.log&#39;</span><span class="p">)</span></span></span></code></pre></div></div>
  </div>
</div><p>Run as SYSTEM, the first line prints <code>NT AUTHORITY\SYSTEM</code>. On the test
server SYSTEM&rsquo;s module path had no Documents folder in it at all. Where it has
one, it&rsquo;s SYSTEM&rsquo;s own profile, not yours, so a module you installed for
yourself is invisible to the task either way. The <code>-ListAvailable</code> call lists every copy the account can find; more than one
row per module means more than one installation. The last line is the copy that
actually loaded. These checks load code and resolve a command; they do not
contact S3.</p>
<p>For unattended work, put the explicit import in the script. That gives a
missing or incompatible dependency a clear failure point before any work starts.</p>
<!-- style-check: end procedure -->
<h2 id="where-awspowershellnetcore-still-fits">Where AWSPowerShell.NetCore still fits<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#where-awspowershellnetcore-still-fits"
     aria-label="Link to section: Where AWSPowerShell.NetCore still fits" data-pagefind-ignore></a>
</h2>
<p>An existing script may explicitly import <code>AWSPowerShell.NetCore</code>. If retaining
that package is part of maintaining the script, install it from the appropriate
elevated host:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Install-Module</span> <span class="n">-Name</span> <span class="n">AWSPowerShell</span><span class="p">.</span><span class="py">NetCore</span> <span class="n">-Repository</span> <span class="n">PSGallery</span> <span class="n">-Scope</span> <span class="n">AllUsers</span></span></span></code></pre></div></div>
  </div>
</div><p>That&rsquo;s an alternative to the modular path. Start a fresh session before
switching package families; loading overlapping AWS assemblies and command
names complicates diagnosis. AWS still documents
<a href="https://docs.aws.amazon.com/powershell/v5/userguide/ps-installing-awspowershellnetcore.html" rel="external noopener" target="_blank">AWSPowerShell.NetCore installation<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#i-external-link"/></svg><span class="visually-hidden"> (opens in a new tab)</span></a>,
while directing new installations to <code>AWS.Tools</code>.</p>
<h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="installation-fails-with-access-denied">Installation fails with access denied<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#installation-fails-with-access-denied"
     aria-label="Link to section: Installation fails with access denied" data-pagefind-ignore></a>
</h3>
<p>The installation session isn&rsquo;t elevated.
The ordinary task doesn&rsquo;t need administrator rights merely because an
administrator installed its dependencies.</p>
<h3 id="module-installed-but-the-task-cant-find-it">Module installed, but the task can&rsquo;t find it<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#module-installed-but-the-task-cant-find-it"
     aria-label="Link to section: Module installed, but the task can’t find it" data-pagefind-ignore></a>
</h3>
<p>Compare the task&rsquo;s
executable, account, module path, and <code>ModuleBase</code> with your interactive session.
Use the same verification commands in the task&rsquo;s diagnostic output.</p>
<h3 id="import-fails-because-script-execution-is-disabled">Import fails because script execution is disabled<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#import-fails-because-script-execution-is-disabled"
     aria-label="Link to section: Import fails because script execution is disabled" data-pagefind-ignore></a>
</h3>
<p>Inspect
<code>Get-ExecutionPolicy -List</code> and follow the machine&rsquo;s approved policy. Installation
scope and script-execution policy solve different problems.</p>
<h3 id="import-works-but-aws-reports-missing-credentials-or-access-denied">Import works, but AWS reports missing credentials or access denied<a class="heading-anchor" href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/#import-works-but-aws-reports-missing-credentials-or-access-denied"
     aria-label="Link to section: Import works, but AWS reports missing credentials or access denied" data-pagefind-ignore></a>
</h3>
<p>The installation is no longer the issue. Configure authentication for the task&rsquo;s
identity and verify its permissions. Your interactive profile isn&rsquo;t evidence
that another account has working AWS access.</p>
<p>The useful completion check is the task account loading the expected module in
the expected shell. An installer success message is only the first step.</p>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2019 (10.0.17763)</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>Windows PowerShell 5.1</dd></div>
    <div class="tested__row"><dt>AWS Tools</dt> <dd>AWS.Tools.Installer 2.0.5, AWS.Tools.S3 5.0.304</dd></div>
    <div class="tested__row"><dt>Account</dt> <dd>SYSTEM, through a scheduled task</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>October 2026</dd></div>
  </dl>
</div>
]]></content:encoded>
    </item>
    
    <item>
      <title>Back Up a 7 Days to Die Dedicated Server to Amazon S3 with PowerShell</title>
      <link>https://looselydecoupled.com/backup-7-days-to-die-server-s3/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/backup-7-days-to-die-server-s3/</guid>
      <pubDate>Fri, 06 Feb 2026 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>Game servers</category>
      <category>AWS</category>
      <category>S3</category>
      <category>PowerShell</category>
      <category>Unattended</category>
      
      <description>The world lands in S3 every morning as an archive that restores onto a fresh server, and the task&#39;s result says whether that morning&#39;s copy arrived.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>A daily scheduled task runs a PowerShell script as SYSTEM.
The script zips <code>Saves</code> and <code>serverconfig.xml</code>. Then it writes the archive to S3 with <code>Write-S3Object</code> as <code>STANDARD_IA</code>.
Retention is three archives locally and thirty days in the bucket.
Every part is stock: <code>Compress-Archive</code>, AWS Tools for PowerShell and Task Scheduler.</p>
<p>SYSTEM has its own profile. Install the modules where SYSTEM can reach them, not where your own session puts them.
Write the credentials where SYSTEM can reach them as well.</p>

</div>

<p>I&rsquo;ve played 7 Days to Die since it came out, and years ago I set up my own
dedicated server, on the Windows Server 2019 VM it still runs on. For a long
time I updated and managed it by hand. Then one day I realized I knew how to
do it better, and started automating it.</p>
<p>The big part was updates. When it&rsquo;s time to play, the server should already
be up to date. There&rsquo;s nothing worse than getting ready to play and hitting
the update wait.</p>
<p>The goal is a server I can replace without a second thought, starting with a
move to Windows Server 2025, and backups are the first step. Steam can
reinstall the game on any machine, but it can&rsquo;t give back the world: the map,
the players&rsquo; bases and everything in their inventories. So every morning,
ahead of the update window, a scheduled task zips that part and copies it to
S3, where a new server can pick it up.</p>
<p>S3 because I already use it and like it. Nothing about the backup needs S3.
The zip, the schedule, the local retention and the logging work the same with
another drive or a share on a NAS or SAN, and
<a href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#use-a-different-destination">Use a different destination</a> covers what
changes. The VM runs outside AWS, which is why
credentials take a step of their own: there&rsquo;s no instance role to lean on.</p>
<h2 id="what-to-back-up">What to back up<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#what-to-back-up"
     aria-label="Link to section: What to back up" data-pagefind-ignore></a>
</h2>
<p>Two things hold state. The game writes the world, the players and their
inventories under <code>Saves</code>, and the server&rsquo;s settings live in
<code>serverconfig.xml</code> beside it. On this server both are under
<code>C:\7DaysToDieServer</code>. A server installed with the defaults keeps <code>Saves</code>
under <code>%APPDATA%\7DaysToDie</code> of the account that runs the game instead,
unless <code>UserDataFolder</code> in <code>serverconfig.xml</code> moves it. The script looks for
<code>Saves</code> beside <code>serverconfig.xml</code> and stops when it isn&rsquo;t there; on a default
install, pass the full path to <code>Saves</code> as <code>-SavesDir</code> in step 5. Everything
else in the server directory is the Steam installation, which SteamCMD reproduces on demand, and it&rsquo;s most of the disk.
The backup takes those two and nothing else, so the zip comes out at about
23 MB.</p>
<p>This server runs Navezgane, the shipped map. A random-gen world also keeps its
terrain in <code>GeneratedWorlds</code>, beside <code>Saves</code>, and a new server can&rsquo;t rebuild
the world without it, so add that directory to the archive and the restore.</p>
<!-- style-check: procedure -->
<h2 id="1-install-aws-tools-where-system-can-see-them">1. Install AWS Tools where SYSTEM can see them<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#1-install-aws-tools-where-system-can-see-them"
     aria-label="Link to section: 1. Install AWS Tools where SYSTEM can see them" data-pagefind-ignore></a>
</h2>
<p>The script reaches S3 through AWS Tools for PowerShell rather than the CLI.
<code>-Scope AllUsers</code> is the part that matters. A per-user install lands under
your own Documents folder, which SYSTEM cannot see, so the scheduled run fails
to import the modules while your own runs work.</p>
<p>On a fresh Server 2019 the gallery needs the NuGet provider first. The TLS
check before it adds TLS 1.2 only when the session has neither it nor the OS
default, so it never removes a protocol. On Server 2019 it changes nothing;
<a href="https://looselydecoupled.com/install-aws-tools-powershell-all-users-windows/">installing AWS Tools for all users</a>
explains when it matters:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$protocol</span> <span class="p">=</span> <span class="p">[</span><span class="no">Net.ServicePointManager</span><span class="p">]::</span><span class="n">SecurityProtocol</span>
</span></span><span class="line"><span class="cl"><span class="nv">$tls12</span> <span class="p">=</span> <span class="p">[</span><span class="no">Net.SecurityProtocolType</span><span class="p">]::</span><span class="n">Tls12</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nv">$protocol</span> <span class="o">-ne</span> <span class="s1">&#39;SystemDefault&#39;</span> <span class="o">-and</span> <span class="o">-not</span> <span class="p">(</span><span class="nv">$protocol</span> <span class="o">-band</span> <span class="nv">$tls12</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">Net.ServicePointManager</span><span class="p">]::</span><span class="n">SecurityProtocol</span> <span class="p">=</span> <span class="nv">$protocol</span> <span class="o">-bor</span> <span class="nv">$tls12</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">Install-PackageProvider</span> <span class="n">-Name</span> <span class="n">NuGet</span> <span class="n">-MinimumVersion</span> <span class="mf">2.8</span><span class="p">.</span><span class="py">5</span><span class="p">.</span><span class="py">201</span> <span class="n">-Force</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl"><span class="nb">Install-Module</span> <span class="n">-Name</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">Installer</span> <span class="n">-Repository</span> <span class="n">PSGallery</span> <span class="n">-Scope</span> <span class="n">AllUsers</span> <span class="n">-Force</span>
</span></span><span class="line"><span class="cl"><span class="nb">Install-AWSToolsModule</span> <span class="n">-Name</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="n">S3</span><span class="p">,</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">SecurityToken</span> <span class="n">-Scope</span> <span class="n">AllUsers</span> <span class="n">-CleanUp</span> <span class="n">-Force</span></span></span></code></pre></div></div>
  </div>
</div><p>Confirm they landed in the machine path rather than your profile:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-Module</span> <span class="n">-ListAvailable</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">S3</span> <span class="p">|</span> <span class="nb">Select-Object</span> <span class="n">Name</span><span class="p">,</span> <span class="n">Version</span><span class="p">,</span> <span class="n">Path</span></span></span></code></pre></div></div>
  </div>
</div><p><code>Path</code> should start <code>C:\Program Files\WindowsPowerShell\Modules\</code>.</p>
<h2 id="2-give-system-its-own-aws-credentials">2. Give SYSTEM its own AWS credentials<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#2-give-system-its-own-aws-credentials"
     aria-label="Link to section: 2. Give SYSTEM its own AWS credentials" data-pagefind-ignore></a>
</h2>
<p>The task runs as SYSTEM so it works whether or not anyone is signed in. SYSTEM
is a separate account with a separate profile, and the AWS Tools read
credentials from the profile of whoever is running them. Anything you run in
your own session writes to <code>%USERPROFILE%\.aws\</code>; SYSTEM never sees that.</p>
<p>A CloudFormation template creates both the bucket and a user who can reach only
that bucket. Save it as <code>backup-stack.yaml</code>:</p>
<!-- style-check: off -->
<div class="code-block" data-copyable data-copy-label="backup-stack.yaml">
  <div class="code-block__head"><span class="code-block__lang code-block__file">backup-stack.yaml</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="nt">AWSTemplateFormatVersion</span><span class="p">:</span><span class="w"> </span><span class="s1">&#39;2010-09-09&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nt">Description</span><span class="p">:</span><span class="w"> </span><span class="p">&gt;-</span><span class="sd">
</span></span></span><span class="line"><span class="cl"><span class="sd">  An S3 bucket for a game server&#39;s world backups and an IAM user that can do
</span></span></span><span class="line"><span class="cl"><span class="sd">  only what the backup and restore scripts do: list the bucket, write, read
</span></span></span><span class="line"><span class="cl"><span class="sd">  and delete its own archives. Archives expire after RetentionDays.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nt">Metadata</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">AWSToolsMetrics</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">AWSAgentToolkit</span><span class="p">:</span><span class="w"> </span><span class="l">aws-cloudformation@2</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nt">Parameters</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">RetentionDays</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Type</span><span class="p">:</span><span class="w"> </span><span class="l">Number</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Default</span><span class="p">:</span><span class="w"> </span><span class="m">30</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">MinValue</span><span class="p">:</span><span class="w"> </span><span class="m">1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Description</span><span class="p">:</span><span class="w"> </span><span class="l">Days an archive stays in the bucket before S3 deletes it.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nt">Resources</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">BackupBucket</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Type</span><span class="p">:</span><span class="w"> </span><span class="l">AWS::S3::Bucket</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">DeletionPolicy</span><span class="p">:</span><span class="w"> </span><span class="l">Retain</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">UpdateReplacePolicy</span><span class="p">:</span><span class="w"> </span><span class="l">Retain</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Metadata</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">com.aws.cloudformation.Context</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">why</span><span class="p">:</span><span class="w"> </span><span class="l">Holds the server&#39;s backup archives; retained on stack deletion so deleting the stack never deletes backups.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">must</span><span class="p">:</span><span class="w"> </span><span class="l">Never public. The expiry rule keeps running when the server, and its own pruning, does not.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Properties</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">PublicAccessBlockConfiguration</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">BlockPublicAcls</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">BlockPublicPolicy</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">IgnorePublicAcls</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">RestrictPublicBuckets</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">BucketEncryption</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">ServerSideEncryptionConfiguration</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="nt">ServerSideEncryptionByDefault</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span><span class="nt">SSEAlgorithm</span><span class="p">:</span><span class="w"> </span><span class="l">AES256</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">LifecycleConfiguration</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">Rules</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="nt">Id</span><span class="p">:</span><span class="w"> </span><span class="l">ExpireArchives</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">Status</span><span class="p">:</span><span class="w"> </span><span class="l">Enabled</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">ExpirationInDays</span><span class="p">:</span><span class="w"> </span>!<span class="l">Ref RetentionDays</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">AbortIncompleteMultipartUpload</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span><span class="nt">DaysAfterInitiation</span><span class="p">:</span><span class="w"> </span><span class="m">3</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">BackupBucketPolicy</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Type</span><span class="p">:</span><span class="w"> </span><span class="l">AWS::S3::BucketPolicy</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Metadata</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">com.aws.cloudformation.Context</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">why</span><span class="p">:</span><span class="w"> </span><span class="l">Refuses any request that is not over HTTPS.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Properties</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">Bucket</span><span class="p">:</span><span class="w"> </span>!<span class="l">Ref BackupBucket</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">PolicyDocument</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">Version</span><span class="p">:</span><span class="w"> </span><span class="s1">&#39;2012-10-17&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">Statement</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="nt">Sid</span><span class="p">:</span><span class="w"> </span><span class="l">DenyInsecureTransport</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">Effect</span><span class="p">:</span><span class="w"> </span><span class="l">Deny</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">Principal</span><span class="p">:</span><span class="w"> </span><span class="s1">&#39;*&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">Action</span><span class="p">:</span><span class="w"> </span><span class="s1">&#39;s3:*&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">Resource</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span>- !<span class="l">GetAtt BackupBucket.Arn</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span>- !<span class="l">Sub &#39;${BackupBucket.Arn}/*&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">Condition</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span><span class="nt">Bool</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">&#39;aws:SecureTransport&#39;</span><span class="p">:</span><span class="w"> </span><span class="s1">&#39;false&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">BackupUser</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Type</span><span class="p">:</span><span class="w"> </span><span class="l">AWS::IAM::User</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Metadata</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">com.aws.cloudformation.Context</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">why</span><span class="p">:</span><span class="w"> </span><span class="l">The identity the server&#39;s backup task and a restore run as. Its access key is created after the stack, so the secret never passes through CloudFormation.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">must</span><span class="p">:</span><span class="w"> </span><span class="kc">No</span><span class="w"> </span><span class="l">console access and no permission outside this one bucket.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Properties</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">Policies</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span>- <span class="nt">PolicyName</span><span class="p">:</span><span class="w"> </span><span class="l">BackupAndRestore</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">PolicyDocument</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">Version</span><span class="p">:</span><span class="w"> </span><span class="s1">&#39;2012-10-17&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">Statement</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span>- <span class="nt">Sid</span><span class="p">:</span><span class="w"> </span><span class="l">ListTheBucket</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">Effect</span><span class="p">:</span><span class="w"> </span><span class="l">Allow</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">Action</span><span class="p">:</span><span class="w"> </span><span class="s1">&#39;s3:ListBucket&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">Resource</span><span class="p">:</span><span class="w"> </span>!<span class="l">GetAtt BackupBucket.Arn</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span>- <span class="nt">Sid</span><span class="p">:</span><span class="w"> </span><span class="l">WriteReadPruneArchives</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">Effect</span><span class="p">:</span><span class="w"> </span><span class="l">Allow</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">Action</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                  </span>- <span class="s1">&#39;s3:PutObject&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                  </span>- <span class="s1">&#39;s3:GetObject&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                  </span>- <span class="s1">&#39;s3:DeleteObject&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">Resource</span><span class="p">:</span><span class="w"> </span>!<span class="l">Sub &#39;${BackupBucket.Arn}/*&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nt">Outputs</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">BucketName</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Description</span><span class="p">:</span><span class="w"> </span><span class="l">Goes on the first line of backup-config.txt.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Value</span><span class="p">:</span><span class="w"> </span>!<span class="l">Ref BackupBucket</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">UserName</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Description</span><span class="p">:</span><span class="w"> </span><span class="l">Create its access key with New-IAMAccessKey -UserName &lt;this&gt;.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">Value</span><span class="p">:</span><span class="w"> </span>!<span class="l">Ref BackupUser</span></span></span></code></pre></div></div>
  </div>
</div><!-- style-check: on -->
<p>It creates three things:</p>
<ul>
<li><strong>A private bucket.</strong> All public access is blocked, requests over plain HTTP
are refused, and an archive expires after <code>RetentionDays</code>. The expiry rule
keeps running when the script doesn&rsquo;t, and it also removes the fragments an
interrupted upload leaves, which are billed until removed. CloudFormation
leaves the bucket in place if you delete the stack.</li>
<li><strong>A user with no console access and no access key.</strong> The key comes from a
separate command, so the secret never passes through CloudFormation.</li>
<li><strong>A policy scoped to the one bucket.</strong> <code>ListBucket</code> acts on the bucket and
the object actions act on its contents, so the two resource lines differ.
Swapping them gets you <code>AccessDenied</code>.</li>
</ul>
<p><code>PutObject</code> writes the archive and <code>DeleteObject</code> is for the script&rsquo;s prune.
Reading each upload back to check it arrived is a listing, so <code>ListBucket</code>
covers that. <code>GetObject</code> is only for restoring, and it lets the same
credentials restore on a new machine. With it removed from the policy, a
download as SYSTEM failed with <code>is not authorized to perform: s3:GetObject</code>,
while listing the bucket still worked. The cost is that a stolen key can read
your old archives, which a write-only key could not.</p>
<p>Deploy it from your own session, with your own credentials. The backup user&rsquo;s
policy can&rsquo;t create a bucket or a user, and it shouldn&rsquo;t. The stack creates an
IAM user, so it needs <code>CAPABILITY_IAM</code>. The commands come from the
<code>AWS.Tools.CloudFormation</code> and <code>AWS.Tools.IdentityManagement</code> modules, which
you install the way step 1 installs the others:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$stackName</span> <span class="p">=</span> <span class="s1">&#39;game-server-backups&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$region</span> <span class="p">=</span> <span class="s1">&#39;us-west-2&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$template</span> <span class="p">=</span> <span class="nb">Get-Content</span> <span class="p">.\</span><span class="nb">backup-stack</span><span class="p">.</span><span class="py">yaml</span> <span class="n">-Raw</span>
</span></span><span class="line"><span class="cl"><span class="nb">New-CFNStack</span> <span class="n">-StackName</span> <span class="nv">$stackName</span> <span class="n">-TemplateBody</span> <span class="nv">$template</span> <span class="n">-Capability</span> <span class="n">CAPABILITY_IAM</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Region</span> <span class="nv">$region</span>
</span></span><span class="line"><span class="cl"><span class="nb">Wait-CFNStack</span> <span class="n">-StackName</span> <span class="nv">$stackName</span> <span class="n">-Region</span> <span class="nv">$region</span> <span class="n">-Timeout</span> <span class="mf">300</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Status</span> <span class="n">CREATE_COMPLETE</span><span class="p">,</span> <span class="n">ROLLBACK_COMPLETE</span>
</span></span><span class="line"><span class="cl"><span class="p">(</span><span class="nb">Get-CFNStack</span> <span class="n">-StackName</span> <span class="nv">$stackName</span> <span class="n">-Region</span> <span class="nv">$region</span><span class="p">).</span><span class="py">Outputs</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Select-Object</span> <span class="n">OutputKey</span><span class="p">,</span> <span class="n">OutputValue</span></span></span></code></pre></div></div>
  </div>
</div><p>The bucket is created in the stack&rsquo;s region, and the backup task calls the
region in SYSTEM&rsquo;s <code>config</code> file below, so use the same one in both places.</p>
<p>Add <code>-Parameter @{ ParameterKey = 'RetentionDays'; ParameterValue = '60' }</code> to
<code>New-CFNStack</code> to change the 30-day default. The script prunes too, at its own
<code>-S3KeepDays</code>, which is 30 unless you pass another number, so add the same
number to the task&rsquo;s arguments in step 5. Otherwise the script deletes archives
the bucket would have kept. The outputs are <code>BucketName</code>, which
step 3 uses, and <code>UserName</code>. I haven&rsquo;t run these cmdlets. The stack this
template makes was created through the CloudFormation API with
<code>CAPABILITY_IAM</code>, and it reached <code>CREATE_COMPLETE</code> with both outputs and the
default of 30 days.</p>
<p>Create the user&rsquo;s access key. The secret is shown once, so keep the output out
of any log:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">New-IAMAccessKey</span> <span class="n">-UserName</span> <span class="s1">&#39;&lt;UserName output&gt;&#39;</span></span></span></code></pre></div></div>
  </div>
</div><p>I didn&rsquo;t run that command either. The key isn&rsquo;t part of the stack, but deleting
the test stack with its key still in place removed the user and the key together
and left the bucket with its archives, so there is no separate step to undo it.</p>
<p>Then, from an elevated PowerShell, write that key where SYSTEM will look for
it: two ini-format files, written by hand. You need both. The second carries
the region, and without a region every call fails, however good the keys are.</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$systemAws</span> <span class="p">=</span> <span class="s1">&#39;C:\Windows\System32\config\systemprofile\.aws&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">New-Item</span> <span class="n">-ItemType</span> <span class="n">Directory</span> <span class="n">-Path</span> <span class="nv">$systemAws</span> <span class="n">-Force</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="sh">@&#34;
</span></span></span><span class="line"><span class="cl"><span class="sh">[default]
</span></span></span><span class="line"><span class="cl"><span class="sh">aws_access_key_id = AKIA...
</span></span></span><span class="line"><span class="cl"><span class="sh">aws_secret_access_key = ...
</span></span></span><span class="line"><span class="cl"><span class="sh">&#34;@</span> <span class="p">|</span> <span class="nb">Set-Content</span> <span class="n">-Path</span> <span class="s2">&#34;</span><span class="nv">$systemAws</span><span class="s2">\credentials&#34;</span> <span class="n">-Encoding</span> <span class="n">ascii</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="sh">@&#34;
</span></span></span><span class="line"><span class="cl"><span class="sh">[default]
</span></span></span><span class="line"><span class="cl"><span class="sh">region = us-west-2
</span></span></span><span class="line"><span class="cl"><span class="sh">&#34;@</span> <span class="p">|</span> <span class="nb">Set-Content</span> <span class="n">-Path</span> <span class="s2">&#34;</span><span class="nv">$systemAws</span><span class="s2">\config&#34;</span> <span class="n">-Encoding</span> <span class="n">ascii</span></span></span></code></pre></div></div>
  </div>
</div><p>The directory is hidden, so <code>dir</code> does not show it; <code>Get-ChildItem -Force</code>
does.</p>
<p>Two shortcuts look like they would do this and do not:</p>
<ul>
<li><code>Set-AWSCredential -StoreAs</code> writes to the SDK&rsquo;s own encrypted store under
<code>AppData</code>, not to these files. That store belongs to the Windows account
that wrote it.</li>
<li><code>Set-DefaultAWSRegion</code> lasts only for the session that ran it, so the
region is gone by the time the task runs.</li>
</ul>
<p>If you would rather not write into SYSTEM&rsquo;s profile, <code>-ProfileLocation</code> points a
call at a credentials file anywhere on disk. You then have to pass it on
every call, which suits a script you are writing more than one you are copying.</p>
<h2 id="3-name-the-bucket-for-the-script">3. Name the bucket for the script<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#3-name-the-bucket-for-the-script"
     aria-label="Link to section: 3. Name the bucket for the script" data-pagefind-ignore></a>
</h2>
<p>Write the <code>BucketName</code> output on the first line of <code>backup-config.txt</code>, beside
the script. The script reads it from there, so the script itself holds nothing
specific to your account. The examples in the rest of this article show
<code>7dtd-server-backups</code> where yours goes.</p>
<h2 id="4-save-the-script">4. Save the script<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#4-save-the-script"
     aria-label="Link to section: 4. Save the script" data-pagefind-ignore></a>
</h2>
<p>Save this as <code>C:\Scripts\backup-s3.ps1</code>, next to <code>backup-config.txt</code>. Each
step that could leave you without a backup stops the run where it failed, and
the exit code says how far it got:</p>
<ul>
<li><code>0</code>: the backup is in the bucket and old copies are pruned.</li>
<li><code>1</code>: no backup could be confirmed in the bucket.</li>
<li><code>2</code>: the backup is in the bucket, but pruning failed.</li>
</ul>
<p>Task Scheduler shows that number as <strong>Last Run Result</strong>, so you can spot a
partial run without opening the log.</p>
<!-- style-check: off -->
<div class="code-block" data-copyable data-copy-label="backup-s3.ps1">
  <div class="code-block__head"><span class="code-block__lang code-block__file">backup-s3.ps1</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="cm">&lt;#
</span></span></span><span class="line"><span class="cl"><span class="cm">.</span><span class="sd">SYNOPSIS</span><span class="cm">
</span></span></span><span class="line"><span class="cl"><span class="cm">    Back up a 7 Days to Die dedicated server&#39;s saves to Amazon S3.
</span></span></span><span class="line"><span class="cl"><span class="cm">
</span></span></span><span class="line"><span class="cl"><span class="cm">.</span><span class="sd">DESCRIPTION</span><span class="cm">
</span></span></span><span class="line"><span class="cl"><span class="cm">    Zips Saves and serverconfig.xml, writes the zip to S3 as STANDARD_IA,
</span></span></span><span class="line"><span class="cl"><span class="cm">    keeps three zips locally and thirty days in the bucket, keeps thirty days
</span></span></span><span class="line"><span class="cl"><span class="cm">    of logs. One log per run under &lt;ServerDir&gt;\backup-logs.
</span></span></span><span class="line"><span class="cl"><span class="cm">
</span></span></span><span class="line"><span class="cl"><span class="cm">    S3 is reached through AWS Tools for PowerShell (AWS.Tools.S3 and
</span></span></span><span class="line"><span class="cl"><span class="cm">    AWS.Tools.SecurityToken), installed with -Scope AllUsers so the account the
</span></span></span><span class="line"><span class="cl"><span class="cm">    task runs as can import them. Runs as SYSTEM from Task Scheduler, so the
</span></span></span><span class="line"><span class="cl"><span class="cm">    credentials and region it uses are SYSTEM&#39;s, from:
</span></span></span><span class="line"><span class="cl"><span class="cm">    C:\Windows\System32\config\systemprofile\.aws\ (credentials and config).
</span></span></span><span class="line"><span class="cl"><span class="cm">
</span></span></span><span class="line"><span class="cl"><span class="cm">    Exit codes: 0 success, 1 the backup could not be confirmed in S3, 2 the
</span></span></span><span class="line"><span class="cl"><span class="cm">    backup is in S3 but a prune step failed.
</span></span></span><span class="line"><span class="cl"><span class="cm">#&gt;</span>
</span></span><span class="line"><span class="cl"><span class="p">[</span><span class="nb">CmdletBinding</span><span class="p">()]</span>
</span></span><span class="line"><span class="cl"><span class="k">param</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$ServerDir</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$SavesDir</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$ConfigFile</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">string</span><span class="p">]</span><span class="nv">$Region</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$LocalKeep</span> <span class="p">=</span> <span class="mf">3</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$S3KeepDays</span> <span class="p">=</span> <span class="mf">30</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$LogKeepDays</span> <span class="p">=</span> <span class="mf">30</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c"># Beside the script unless the caller names one.</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$ConfigFile</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$ConfigFile</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="p">(</span><span class="nb">Split-Path</span> <span class="n">-Parent</span> <span class="nv">$MyInvocation</span><span class="p">.</span><span class="py">MyCommand</span><span class="p">.</span><span class="n">Path</span><span class="p">)</span> <span class="s1">&#39;backup-config.txt&#39;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c"># Region only when asked for. Left out, the AWS Tools resolve it the way the</span>
</span></span><span class="line"><span class="cl"><span class="c"># CLI did: the profile&#39;s config, then AWS_REGION, then the SDK&#39;s default.</span>
</span></span><span class="line"><span class="cl"><span class="nv">$aws</span> <span class="p">=</span> <span class="vm">@</span><span class="p">{}</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nv">$Region</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$aws</span><span class="p">.</span><span class="py">Region</span> <span class="p">=</span> <span class="nv">$Region</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nv">$BackupDir</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$ServerDir</span> <span class="s1">&#39;backups&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$LogDir</span>    <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$ServerDir</span> <span class="s1">&#39;backup-logs&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$Timestamp</span> <span class="p">=</span> <span class="nb">Get-Date</span> <span class="n">-Format</span> <span class="s1">&#39;yyyyMMdd-HHmmss&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$LogFile</span>   <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$LogDir</span> <span class="s2">&#34;backup-</span><span class="nv">$Timestamp</span><span class="s2">.log&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$Prefix</span>    <span class="p">=</span> <span class="s1">&#39;7days-backups/&#39;</span>
</span></span><span class="line"><span class="cl"><span class="c"># Anchored, and [^/] so it cannot reach into a nested key: a listing is</span>
</span></span><span class="line"><span class="cl"><span class="c"># recursive where the CLI&#39;s `s3 ls` was not, and -like&#39;s * spans a slash.</span>
</span></span><span class="line"><span class="cl"><span class="nv">$KeyPattern</span> <span class="p">=</span> <span class="s1">&#39;^&#39;</span> <span class="p">+</span> <span class="p">[</span><span class="no">regex</span><span class="p">]::</span><span class="n">Escape</span><span class="p">(</span><span class="nv">$Prefix</span><span class="p">)</span> <span class="p">+</span> <span class="s1">&#39;7dtd-backup-[^/]+\.zip$&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">foreach</span> <span class="p">(</span><span class="nv">$dir</span> <span class="k">in</span> <span class="nv">$BackupDir</span><span class="p">,</span> <span class="nv">$LogDir</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="p">(</span><span class="nb">Test-Path</span> <span class="nv">$dir</span><span class="p">))</span> <span class="p">{</span> <span class="nb">New-Item</span> <span class="n">-ItemType</span> <span class="n">Directory</span> <span class="n">-Path</span> <span class="nv">$dir</span> <span class="p">|</span> <span class="nb">Out-Null</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Write-Log</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">([</span><span class="no">string</span><span class="p">]</span><span class="nv">$Message</span> <span class="p">=</span> <span class="s1">&#39;&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Add-Content</span> <span class="n">-Path</span> <span class="nv">$LogFile</span> <span class="n">-Value</span> <span class="nv">$Message</span> <span class="n">-Encoding</span> <span class="n">UTF8</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Host</span> <span class="nv">$Message</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span><span class="w"> </span><span class="nb">Stop-Run</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">param</span><span class="p">([</span><span class="no">string</span><span class="p">]</span><span class="nv">$Message</span><span class="p">,</span> <span class="p">[</span><span class="no">int</span><span class="p">]</span><span class="nv">$Code</span> <span class="p">=</span> <span class="mf">1</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s2">&#34;ERROR: </span><span class="nv">$Message</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">exit</span> <span class="nv">$Code</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;========================================&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;7 Days to Die Server S3 Backup&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;Started: </span><span class="p">$(</span><span class="nb">Get-Date</span> <span class="n">-Format</span> <span class="s1">&#39;ddd MM/dd/yyyy HH:mm:ss.ff&#39;</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;========================================&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c"># Which account ran matters more than anything else when credentials fail.</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="p">([</span><span class="no">Security.Principal.WindowsIdentity</span><span class="p">]::</span><span class="n">GetCurrent</span><span class="p">().</span><span class="n">Name</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="p">(</span><span class="nb">Test-Path</span> <span class="nv">$ConfigFile</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;Config file not found at </span><span class="nv">$ConfigFile</span><span class="s2">. Write the bucket name on its first line&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nv">$Bucket</span> <span class="p">=</span> <span class="s2">&#34;</span><span class="p">$(</span><span class="nb">Get-Content</span> <span class="nv">$ConfigFile</span> <span class="n">-First</span> <span class="mf">1</span><span class="p">)</span><span class="s2">&#34;</span><span class="p">.</span><span class="py">Trim</span><span class="p">()</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="nv">$Bucket</span><span class="p">)</span> <span class="p">{</span> <span class="nb">Stop-Run</span> <span class="s1">&#39;S3 bucket name not configured&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;S3 Bucket: </span><span class="nv">$Bucket</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Import-Module</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="n">S3</span><span class="p">,</span> <span class="n">AWS</span><span class="p">.</span><span class="py">Tools</span><span class="p">.</span><span class="py">SecurityToken</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;AWS Tools for PowerShell not available to this account: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">. Install AWS.Tools.S3 and AWS.Tools.SecurityToken with -Scope AllUsers&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;Testing AWS credentials...&#39;</span>
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Get-STSCallerIdentity</span> <span class="nv">@aws</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;AWS credentials or region not usable by this account: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;AWS credentials OK&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nv">$BackupName</span> <span class="p">=</span> <span class="s2">&#34;7dtd-backup-</span><span class="nv">$Timestamp</span><span class="s2">.zip&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$BackupPath</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$BackupDir</span> <span class="nv">$BackupName</span>
</span></span><span class="line"><span class="cl"><span class="nv">$Key</span>        <span class="p">=</span> <span class="s2">&#34;</span><span class="nv">$Prefix$BackupName</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$Saves</span>      <span class="p">=</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$SavesDir</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$SavesDir</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="nb">Join-Path</span> <span class="nv">$ServerDir</span> <span class="s1">&#39;Saves&#39;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nv">$Config</span>     <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$ServerDir</span> <span class="s1">&#39;serverconfig.xml&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;Creating backup archive...&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;Destination: </span><span class="nv">$BackupPath</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="o">-not</span> <span class="p">(</span><span class="nb">Test-Path</span> <span class="nv">$Saves</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;Saves directory not found: </span><span class="nv">$Saves</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;Compressing: </span><span class="nv">$Saves</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$sources</span> <span class="p">=</span> <span class="vm">@</span><span class="p">(</span><span class="nv">$Saves</span><span class="p">,</span> <span class="nv">$Config</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Compress-Archive</span> <span class="n">-Path</span> <span class="nv">$sources</span> <span class="n">-DestinationPath</span> <span class="nv">$BackupPath</span> <span class="n">-CompressionLevel</span> <span class="n">Optimal</span> <span class="n">-Force</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;Failed to create backup archive: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nv">$localSize</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Get-Item</span> <span class="nv">$BackupPath</span><span class="p">).</span><span class="py">Length</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;Backup created: </span><span class="p">$([</span><span class="no">math</span><span class="p">]::</span><span class="n">Round</span><span class="p">(</span><span class="nv">$localSize</span> <span class="p">/</span> <span class="mf">1</span><span class="p">MB))</span><span class="s2"> MB&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;Uploading to S3...&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;S3 path: s3://</span><span class="nv">$Bucket</span><span class="s2">/</span><span class="nv">$Key</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-S3Object</span> <span class="n">-BucketName</span> <span class="nv">$Bucket</span> <span class="n">-Key</span> <span class="nv">$Key</span> <span class="o">-File</span> <span class="nv">$BackupPath</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">        <span class="n">-StorageClass</span> <span class="n">STANDARD_IA</span> <span class="nv">@aws</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;Failed to upload backup to S3: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c"># Read it back: the cmdlet returning is not the same as the bytes being there.</span>
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$remote</span> <span class="p">=</span> <span class="nb">Get-S3Object</span> <span class="n">-BucketName</span> <span class="nv">$Bucket</span> <span class="n">-Key</span> <span class="nv">$Key</span> <span class="nv">@aws</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;Upload returned but the object could not be read back: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="vm">$null</span> <span class="o">-eq</span> <span class="nv">$remote</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;Upload returned but the object is not in the bucket: </span><span class="nv">$Key</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nv">$remote</span><span class="p">.</span><span class="py">Size</span> <span class="o">-ne</span> <span class="nv">$localSize</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;Upload size mismatch: local </span><span class="nv">$localSize</span><span class="s2"> bytes, S3 </span><span class="p">$(</span><span class="nv">$remote</span><span class="p">.</span><span class="n">Size</span><span class="p">)</span><span class="s2"> bytes&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;Upload successful: </span><span class="p">$(</span><span class="nv">$remote</span><span class="p">.</span><span class="n">Size</span><span class="p">)</span><span class="s2"> bytes, </span><span class="p">$(</span><span class="nv">$remote</span><span class="p">.</span><span class="n">StorageClass</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c"># From here the backup is in the bucket. A failure below is reported, not</span>
</span></span><span class="line"><span class="cl"><span class="c"># fatal: exit 2 says &#34;backed up, but look at the log&#34;.</span>
</span></span><span class="line"><span class="cl"><span class="nv">$pruneFailed</span> <span class="p">=</span> <span class="vm">$false</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;Cleaning up old local backups...&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Get-ChildItem</span> <span class="nv">$BackupDir</span> <span class="n">-Filter</span> <span class="s1">&#39;7dtd-backup-*.zip&#39;</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Sort-Object</span> <span class="n">LastWriteTime</span> <span class="n">-Descending</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Select-Object</span> <span class="n">-Skip</span> <span class="nv">$LocalKeep</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">ForEach-Object</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$file</span> <span class="p">=</span> <span class="nv">$_</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Write-Log</span> <span class="s2">&#34;Deleting old backup: </span><span class="p">$(</span><span class="nv">$file</span><span class="p">.</span><span class="n">Name</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nb">Remove-Item</span> <span class="nv">$file</span><span class="p">.</span><span class="py">FullName</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nb">Write-Log</span> <span class="s2">&#34;WARNING: could not delete </span><span class="p">$(</span><span class="nv">$file</span><span class="p">.</span><span class="n">Name</span><span class="p">)</span><span class="s2">: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$pruneFailed</span> <span class="p">=</span> <span class="vm">$true</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;Cleaning up old S3 backups (older than </span><span class="nv">$S3KeepDays</span><span class="s2"> days)...&#34;</span>
</span></span><span class="line"><span class="cl"><span class="c"># Both sides in UTC. LastModified&#39;s Kind isn&#39;t guaranteed, and comparing a</span>
</span></span><span class="line"><span class="cl"><span class="c"># local time against a UTC one shifts the retention boundary by the</span>
</span></span><span class="line"><span class="cl"><span class="c"># machine&#39;s offset.</span>
</span></span><span class="line"><span class="cl"><span class="nv">$cutoff</span> <span class="p">=</span> <span class="p">[</span><span class="no">datetime</span><span class="p">]::</span><span class="n">UtcNow</span><span class="p">.</span><span class="py">AddDays</span><span class="p">(-</span><span class="nv">$S3KeepDays</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$old</span> <span class="p">=</span> <span class="nb">Get-S3Object</span> <span class="n">-BucketName</span> <span class="nv">$Bucket</span> <span class="n">-Prefix</span> <span class="nv">$Prefix</span> <span class="nv">@aws</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Where-Object</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$_</span><span class="p">.</span><span class="py">Key</span> <span class="o">-match</span> <span class="nv">$KeyPattern</span> <span class="o">-and</span>
</span></span><span class="line"><span class="cl">            <span class="nv">$_</span><span class="p">.</span><span class="py">LastModified</span><span class="p">.</span><span class="py">ToUniversalTime</span><span class="p">()</span> <span class="o">-lt</span> <span class="nv">$cutoff</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s2">&#34;WARNING: could not list S3 backups: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$pruneFailed</span> <span class="p">=</span> <span class="vm">$true</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$old</span> <span class="p">=</span> <span class="vm">@</span><span class="p">()</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="k">foreach</span> <span class="p">(</span><span class="nv">$object</span> <span class="k">in</span> <span class="nv">$old</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s2">&#34;Deleting old S3 backup: </span><span class="p">$(</span><span class="nv">$object</span><span class="p">.</span><span class="n">Key</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Remove-S3Object</span> <span class="n">-BucketName</span> <span class="nv">$Bucket</span> <span class="n">-Key</span> <span class="nv">$object</span><span class="p">.</span><span class="py">Key</span> <span class="nv">@aws</span> <span class="n">-Force</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nb">Write-Log</span> <span class="s2">&#34;WARNING: could not delete </span><span class="p">$(</span><span class="nv">$object</span><span class="p">.</span><span class="n">Key</span><span class="p">)</span><span class="s2">: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="nv">$pruneFailed</span> <span class="p">=</span> <span class="vm">$true</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">Get-ChildItem</span> <span class="nv">$LogDir</span> <span class="n">-Filter</span> <span class="s1">&#39;backup-*.log&#39;</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Where-Object</span> <span class="p">{</span> <span class="nv">$_</span><span class="p">.</span><span class="py">LastWriteTime</span> <span class="o">-lt</span> <span class="p">(</span><span class="nb">Get-Date</span><span class="p">).</span><span class="py">AddDays</span><span class="p">(-</span><span class="nv">$LogKeepDays</span><span class="p">)</span> <span class="o">-and</span> <span class="nv">$_</span><span class="p">.</span><span class="py">FullName</span> <span class="o">-ne</span> <span class="nv">$LogFile</span> <span class="p">}</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Remove-Item</span> <span class="n">-ErrorAction</span> <span class="n">SilentlyContinue</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;========================================&#39;</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nv">$pruneFailed</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s2">&#34;Backup completed with warnings: </span><span class="p">$(</span><span class="nb">Get-Date</span> <span class="n">-Format</span> <span class="s1">&#39;ddd MM/dd/yyyy HH:mm:ss.ff&#39;</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Write-Log</span> <span class="s1">&#39;========================================&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="n">exit</span> <span class="mf">2</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;Backup completed: </span><span class="p">$(</span><span class="nb">Get-Date</span> <span class="n">-Format</span> <span class="s1">&#39;ddd MM/dd/yyyy HH:mm:ss.ff&#39;</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s1">&#39;========================================&#39;</span>
</span></span><span class="line"><span class="cl"><span class="n">exit</span> <span class="mf">0</span></span></span></code></pre></div></div>
  </div>
</div><!-- style-check: on -->
<p>A few lines look odd until you know why they are there:</p>
<ul>
<li>The log function uses <code>Write-Host</code>, not <code>Write-Output</code>, so log lines do not
leak into whatever the script returns.</li>
<li>After the upload, the script fetches the object&rsquo;s details and compares its
size with the local file. That confirms an object with that key is in the
bucket. The upload cmdlet returning without an error does not prove that on
its own. It checks length, not content; S3 already verifies the
transfer&rsquo;s checksum.</li>
</ul>
<h2 id="5-register-the-task">5. Register the task<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#5-register-the-task"
     aria-label="Link to section: 5. Register the task" data-pagefind-ignore></a>
</h2>
<p>From an elevated PowerShell:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Unblock-File</span> <span class="n">C:</span><span class="p">\</span><span class="n">Scripts</span><span class="p">\</span><span class="nb">backup-s3</span><span class="p">.</span><span class="py">ps1</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nv">$action</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskAction</span> <span class="n">-Execute</span> <span class="s1">&#39;powershell.exe&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Argument</span> <span class="s1">&#39;-NoProfile -ExecutionPolicy RemoteSigned -File &#34;C:\Scripts\backup-s3.ps1&#34;&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$trigger</span> <span class="p">=</span> <span class="nb">New-ScheduledTaskTrigger</span> <span class="n">-Daily</span> <span class="n">-At</span> <span class="mf">11</span><span class="err">:</span><span class="mf">00</span>
</span></span><span class="line"><span class="cl"><span class="nb">Register-ScheduledTask</span> <span class="n">-TaskName</span> <span class="s1">&#39;7DaysToDieServerS3Backup&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Action</span> <span class="nv">$action</span> <span class="n">-Trigger</span> <span class="nv">$trigger</span> <span class="n">-User</span> <span class="s1">&#39;SYSTEM&#39;</span> <span class="n">-RunLevel</span> <span class="n">Highest</span></span></span></code></pre></div></div>
  </div>
</div><p>A script that arrives by download or inside a zip carries the mark of the
web. <code>RemoteSigned</code> refuses to run it until <code>Unblock-File</code> clears the mark.
<code>Bypass</code> would also work, but it would hide the next blocked file too. Steps
1 and 2 exist because of <code>-User 'SYSTEM'</code>. The VM&rsquo;s clock is UTC, so
11:00 is early morning Pacific, ahead of the server&rsquo;s own update window. Pick
an hour when nobody is playing.</p>
<p>Start the first run from the scheduler, not by hand. A run from your own
session uses your credentials, so it tests the script but not the task:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Start-ScheduledTask</span> <span class="n">7DaysToDieServerS3Backup</span>
</span></span><span class="line"><span class="cl"><span class="nb">Start-Sleep</span> <span class="mf">30</span>
</span></span><span class="line"><span class="cl"><span class="p">(</span><span class="nb">Get-ScheduledTask</span> <span class="n">7DaysToDieServerS3Backup</span> <span class="p">|</span> <span class="nb">Get-ScheduledTaskInfo</span><span class="p">).</span><span class="n">LastTaskResult</span></span></span></code></pre></div></div>
  </div>
</div><p><code>0</code>, and a new log under <code>C:\7DaysToDieServer\backup-logs</code> whose identity
line reads <code>NT AUTHORITY\SYSTEM</code>.</p>
<!-- style-check: end procedure -->
<h2 id="expected-result">Expected result<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#expected-result"
     aria-label="Link to section: Expected result" data-pagefind-ignore></a>
</h2>
<p>Each run writes one log. This one is from a morning when both prunes had
work to do: a fourth archive had built up on disk, and one in the bucket had
reached thirty days.</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">========================================
</span></span><span class="line"><span class="cl">7 Days to Die Server S3 Backup
</span></span><span class="line"><span class="cl">Started: Fri 09/25/2026 14:28:39.98
</span></span><span class="line"><span class="cl">========================================
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">NT AUTHORITY\SYSTEM
</span></span><span class="line"><span class="cl">S3 Bucket: 7dtd-server-backups
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Testing AWS credentials...
</span></span><span class="line"><span class="cl">AWS credentials OK
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Creating backup archive...
</span></span><span class="line"><span class="cl">Destination: C:\7DaysToDieServer\backups\7dtd-backup-20260925-142839.zip
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Compressing: C:\7DaysToDieServer\Saves
</span></span><span class="line"><span class="cl">Backup created: 23 MB
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Uploading to S3...
</span></span><span class="line"><span class="cl">S3 path: s3://7dtd-server-backups/7days-backups/7dtd-backup-20260925-142839.zip
</span></span><span class="line"><span class="cl">Upload successful: 23917749 bytes, STANDARD_IA
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Cleaning up old local backups...
</span></span><span class="line"><span class="cl">Deleting old backup: 7dtd-backup-20260924-145409.zip
</span></span><span class="line"><span class="cl">Cleaning up old S3 backups (older than 30 days)...
</span></span><span class="line"><span class="cl">Deleting old S3 backup: 7days-backups/7dtd-backup-20260826-110000.zip
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">========================================
</span></span><span class="line"><span class="cl">Backup completed: Fri 09/25/2026 14:28:45.92
</span></span><span class="line"><span class="cl">========================================</span></span></code></pre></div></div>
  </div>
</div><p>That&rsquo;s six seconds, start to finish. The account name near the top is there
because when a run fails on credentials, the first thing to find out is which
account ran it.</p>
<p>To list what&rsquo;s in the bucket:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-S3Object</span> <span class="n">-BucketName</span> <span class="n">7dtd-server-backups</span> <span class="n">-Prefix</span> <span class="n">7days-backups</span><span class="p">/</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Select-Object</span> <span class="n">Key</span><span class="p">,</span> <span class="n">Size</span><span class="p">,</span> <span class="n">LastModified</span></span></span></code></pre></div></div>
  </div>
</div><p>Expect one archive for each morning the machine was on, and about thirty
days of them.</p>
<h2 id="restore-a-backup">Restore a backup<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#restore-a-backup"
     aria-label="Link to section: Restore a backup" data-pagefind-ignore></a>
</h2>
<p>Each archive is a plain zip holding <code>Saves</code> and <code>serverconfig.xml</code>, so a
restore is a download and an <code>Expand-Archive</code>. Run this in your own session
if its credentials can read the bucket, and you want to be watching. The backup
user&rsquo;s credentials in SYSTEM&rsquo;s profile can read it too, so a scheduled task
that runs as SYSTEM can do the download on a machine that has only those.</p>
<ol>
<li>
<p>Stop the server.</p>
</li>
<li>
<p>Move the current saves out of the way, so the restored tree stands alone
and the old one is still there if you need it:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$saves</span> <span class="p">=</span> <span class="s1">&#39;C:\7DaysToDieServer\Saves&#39;</span>   <span class="c"># or the path you passed as -SavesDir</span>
</span></span><span class="line"><span class="cl"><span class="nb">Rename-Item</span> <span class="nv">$saves</span> <span class="n">Saves</span><span class="p">.</span><span class="nb">before-restore</span></span></span></code></pre></div></div>
  </div>
</div></li>
<li>
<p>Download the archive you want and expand it into a temporary directory:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$name</span> <span class="p">=</span> <span class="s1">&#39;7dtd-backup-20260925-142839.zip&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$zip</span>  <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$env:TEMP</span> <span class="nv">$name</span>
</span></span><span class="line"><span class="cl"><span class="nv">$dir</span>  <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$env:TEMP</span> <span class="s1">&#39;7dtd-restore&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Read-S3Object</span> <span class="n">-BucketName</span> <span class="n">7dtd-server-backups</span> <span class="n">-Key</span> <span class="s2">&#34;7days-backups/</span><span class="nv">$name</span><span class="s2">&#34;</span> <span class="o">-File</span> <span class="nv">$zip</span>
</span></span><span class="line"><span class="cl"><span class="nb">Expand-Archive</span> <span class="nv">$zip</span> <span class="n">-DestinationPath</span> <span class="nv">$dir</span> <span class="n">-Force</span></span></span></code></pre></div></div>
  </div>
</div></li>
<li>
<p>Move <code>Saves</code> into place:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Move-Item</span> <span class="p">(</span><span class="nb">Join-Path</span> <span class="nv">$dir</span> <span class="s1">&#39;Saves&#39;</span><span class="p">)</span> <span class="nv">$saves</span></span></span></code></pre></div></div>
  </div>
</div></li>
<li>
<p>Only if you want the old settings back, copy the old <code>serverconfig.xml</code>
over the current one:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Copy-Item</span> <span class="p">(</span><span class="nb">Join-Path</span> <span class="nv">$dir</span> <span class="s1">&#39;serverconfig.xml&#39;</span><span class="p">)</span> <span class="n">C:</span><span class="p">\</span><span class="n">7DaysToDieServer</span><span class="p">\</span> <span class="n">-Force</span></span></span></code></pre></div></div>
  </div>
</div></li>
<li>
<p>Start the server.</p>
</li>
</ol>
<p>Do a practice restore on a scratch machine before you need one for real.
Until you&rsquo;ve done that, you don&rsquo;t know that the backup works.</p>
<h2 id="use-a-different-destination">Use a different destination<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#use-a-different-destination"
     aria-label="Link to section: Use a different destination" data-pagefind-ignore></a>
</h2>
<p>S3 appears in steps 1 to 3, the script&rsquo;s setup checks, its upload and its
S3 prune. Everything else works with any destination. To write to another
drive or a share instead:</p>
<ul>
<li>
<p>Skip steps 1 to 3. In the script, delete everything between the line that
logs the account name and <code>$BackupName</code>: the <code>backup-config.txt</code> check, the
module import and the credentials test. Left in, the missing config file
stops every run before the copy.</p>
</li>
<li>
<p>Replace everything from <code>Uploading to S3...</code> through <code>Upload successful</code>
with a copy, checked the same way:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$Destination</span> <span class="p">=</span> <span class="s1">&#39;\\nas\backups\7dtd&#39;</span>
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Copy-Item</span> <span class="nv">$BackupPath</span> <span class="n">-Destination</span> <span class="nv">$Destination</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl">    <span class="nv">$remote</span> <span class="p">=</span> <span class="nb">Get-Item</span> <span class="p">(</span><span class="nb">Join-Path</span> <span class="nv">$Destination</span> <span class="nv">$BackupName</span><span class="p">)</span> <span class="n">-ErrorAction</span> <span class="n">Stop</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;Failed to copy backup to </span><span class="nv">${Destination}</span><span class="s2">: </span><span class="p">$(</span><span class="nv">$_</span><span class="p">.</span><span class="py">Exception</span><span class="p">.</span><span class="n">Message</span><span class="p">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nv">$remote</span><span class="p">.</span><span class="py">Length</span> <span class="o">-ne</span> <span class="nv">$localSize</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Run</span> <span class="s2">&#34;Copy size mismatch: local </span><span class="nv">$localSize</span><span class="s2"> bytes, destination </span><span class="p">$(</span><span class="nv">$remote</span><span class="p">.</span><span class="n">Length</span><span class="p">)</span><span class="s2"> bytes&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">Write-Log</span> <span class="s2">&#34;Copy successful: </span><span class="p">$(</span><span class="nv">$remote</span><span class="p">.</span><span class="n">Length</span><span class="p">)</span><span class="s2"> bytes&#34;</span></span></span></code></pre></div></div>
  </div>
</div></li>
<li>
<p>Replace the S3 prune with a date-based <code>Get-ChildItem</code> prune on the
destination, like the one the script uses for its log files.</p>
</li>
</ul>
<p>A share needs one more decision, because the task runs as SYSTEM. On a
domain, SYSTEM reaches the network as the computer account (<code>SERVER$</code>), so
grant that account write access on the share. Outside a domain, SYSTEM has
no identity a NAS will accept. Run the task as a local user that can write to
the share instead.</p>
<p>A second disk in the same machine protects you from a failed drive. It
doesn&rsquo;t help if you lose the whole machine.</p>
<h2 id="why-it-is-built-this-way">Why it is built this way<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#why-it-is-built-this-way"
     aria-label="Link to section: Why it is built this way" data-pagefind-ignore></a>
</h2>
<p><strong>A zip a day, not a sync.</strong> A sync keeps one current copy of each file, so
a save that corrupts on Tuesday overwrites Monday&rsquo;s good copy on Tuesday
night. A dated zip each day gives you thirty separate restore points without
setting up versioning. At 23 MB a day, a whole month is under a gigabyte.</p>
<p><strong><code>STANDARD_IA</code>, because the retention matches.</strong> Infrequent Access charges
for at least 30 days of storage per object. Objects pruned at exactly 30 days
pay that minimum and nothing more, at a lower per-gigabyte rate than
Standard. A restore reads one object once, so the retrieval charge stays
small.</p>
<p><strong>Retention in two places.</strong> The script prunes the bucket at 30 days, and so
does the lifecycle rule. On 2026-09-10 the VM was switched off, and it stayed
off for twelve days. The script didn&rsquo;t run, so its prune didn&rsquo;t either, but
the lifecycle rule kept deleting. When the machine came back, the bucket held
only the archives from the last thirty days, about twelve short of thirty. If
retention lived only in the script, old archives would pile up whenever the
script stopped running.</p>
<p><strong>Three exit codes, not two.</strong> Once the upload succeeds, the backup exists,
and a later failure shouldn&rsquo;t be reported the same way as an earlier one.
Exit 2 means &ldquo;backed up, check the log&rdquo;. Task Scheduler still shows it as a
non-zero result, so you notice it.</p>
<h2 id="what-the-batch-file-it-replaced-got-wrong">What the batch file it replaced got wrong<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#what-the-batch-file-it-replaced-got-wrong"
     aria-label="Link to section: What the batch file it replaced got wrong" data-pagefind-ignore></a>
</h2>
<p>A batch file, <code>backup-s3.bat</code>, did this job from 2026-02-06 to 2026-09-22.
It called PowerShell only for <code>Compress-Archive</code> and a date comparison, and
it never missed a morning the machine was on. If you run something like it,
it probably has the same three defects:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="BAT">
  <div class="code-block__head"><span class="code-block__lang">BAT</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bat" data-lang="bat"><span class="line"><span class="cl"><span class="k">set</span> <span class="nv">TIMESTAMP</span><span class="p">=</span><span class="nv">%date:~-4,4%%date:~-10,2%%date:~-7,2%</span>-<span class="nv">%time:~0,2%%time:~3,2%%time:~6,2%</span></span></span></code></pre></div></div>
  </div>
</div><ul>
<li>The timestamp cut <code>%date%</code> up by character position. That only works with
the en-US format, <code>Tue 09/22/2026</code>. With any other system locale, the
filenames come out scrambled.</li>
<li>The S3 prune ran <code>aws s3 rm</code> in a loop without checking any results, and
the file always ended with <code>exit /b 0</code>. If the <code>s3:DeleteObject</code>
permission had been missing, nobody would have noticed, because the
lifecycle rule would have done the deleting instead.</li>
<li>Each log carried ninety lines of the CLI&rsquo;s progress bar around the one
line that mattered.</li>
</ul>
<p>None of the three ever caused a failure. The AWS CLI went too, the day after
the switch. <code>aws s3 cp</code> reports failure only through an exit code, which has
to be checked after every call. A script that misses one check reports
success for an upload that didn&rsquo;t happen. <code>Write-S3Object</code> throws an error
instead, and one <code>try</code>/<code>catch</code> handles it.</p>
<h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="aws-tools-for-powershell-not-available-but-the-module-imports-fine-for-you"><code>AWS Tools for PowerShell not available</code>, but the module imports fine for you<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#aws-tools-for-powershell-not-available-but-the-module-imports-fine-for-you"
     aria-label="Link to section: AWS Tools for PowerShell not available, but the module imports fine for you" data-pagefind-ignore></a>
</h3>
<p>The modules were installed per-user instead of with <code>-Scope AllUsers</code>, so
they&rsquo;re under your Documents folder, where SYSTEM can&rsquo;t see them.
<code>Get-Module -ListAvailable AWS.Tools.S3</code> shows the path.</p>
<h3 id="aws-credentials-or-region-not-usable-by-this-account-but-the-same-call-works-for-you"><code>AWS credentials or region not usable by this account</code>, but the same call works for you<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#aws-credentials-or-region-not-usable-by-this-account-but-the-same-call-works-for-you"
     aria-label="Link to section: AWS credentials or region not usable by this account, but the same call works for you" data-pagefind-ignore></a>
</h3>
<p>The task isn&rsquo;t running as you, so it doesn&rsquo;t use your credentials. Go back to
step 2. The account name at the top of the log shows who ran it. The message
mentions the region because a missing region fails at the same point as a
missing key. It&rsquo;s easy to spend an hour in the credentials file when the
problem is in <code>config</code>.</p>
<h3 id="task-arguments-come-out-mangled">Task arguments come out mangled<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#task-arguments-come-out-mangled"
     aria-label="Link to section: Task arguments come out mangled" data-pagefind-ignore></a>
</h3>
<p>On this server, <code>schtasks /Change /TR</code> with a quoted path inside the string
produced <code>-File &quot; C:\Scripts\backup-s3.ps1\</code>, with a leading space and a stray
backslash. <code>New-ScheduledTaskAction</code> sets <code>Execute</code> and <code>Arguments</code> as
separate values, so the quoting survives. Use <code>Set-ScheduledTask -Action</code> to
apply it to an existing task.</p>
<h3 id="after-an-outage-the-result-reads-the-operator-or-administrator-has-refused-the-request">After an outage, the result reads <code>The operator or administrator has refused the request</code><a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#after-an-outage-the-result-reads-the-operator-or-administrator-has-refused-the-request"
     aria-label="Link to section: After an outage, the result reads The operator or administrator has refused the request" data-pagefind-ignore></a>
</h3>
<p>The machine was off at 11:00. On boot, the scheduler recorded event 153,
&ldquo;Missed task start rejected&rdquo;, because the task&rsquo;s &ldquo;run as soon as possible
after a scheduled start is missed&rdquo; setting is off. Nothing failed, and the
next 11:00 run goes ahead normally. Turn the setting on if you want a
catch-up run, at the cost of a backup taken while the server is still
starting.</p>
<h3 id="compress-archive-fails-on-one-large-file"><code>Compress-Archive</code> fails on one large file<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#compress-archive-fails-on-one-large-file"
     aria-label="Link to section: Compress-Archive fails on one large file" data-pagefind-ignore></a>
</h3>
<p><code>Compress-Archive</code> can&rsquo;t add a single file over 2 GB. The limit comes from
the .NET API underneath it, in both Windows PowerShell 5.1 and PowerShell 7.
Nothing under <code>Saves</code> comes near that on this server. If one of your files
does, use <code>tar.exe</code>, which ships with Windows Server 2019 and later and has
no such limit.</p>
<h3 id="saves-are-captured-mid-write">Saves are captured mid-write<a class="heading-anchor" href="https://looselydecoupled.com/backup-7-days-to-die-server-s3/#saves-are-captured-mid-write"
     aria-label="Link to section: Saves are captured mid-write" data-pagefind-ignore></a>
</h3>
<p>The server keeps running and writing while the archive is taken, so a
restored save can be a few minutes stale. If that matters for your world,
stop the server before the backup, or accept the gap.</p>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2019 (10.0.17763), VM</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>Windows PowerShell 5.1</dd></div>
    <div class="tested__row"><dt>AWS Tools</dt> <dd>AWS.Tools.S3 and AWS.Tools.SecurityToken 5.0.304</dd></div>
    <div class="tested__row"><dt>Task</dt> <dd>daily 11:00 UTC as SYSTEM; batch 2026-02-06 to 2026-09-22, PowerShell from 2026-09-22</dd></div>
    <div class="tested__row"><dt>Saves</dt> <dd>about 23 MB zipped</dd></div>
    <div class="tested__row"><dt>Rerun</dt> <dd>7 Days to Die V 3.4.0 (b9) on Windows Server 2025, a new world, 1.8 MB zipped</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>September 2026</dd></div>
  </dl>
</div>
]]></content:encoded>
    </item>
    
    <item>
      <title>How to Install Visual Studio Code Silently for All Users with PowerShell</title>
      <link>https://looselydecoupled.com/install-vscode-silently-powershell/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/install-vscode-silently-powershell/</guid>
      <pubDate>Sat, 18 Nov 2023 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>Unattended</category>
      <category>PowerShell</category>
      
      <description>Windows Server 2022 has no winget, but VS Code&#39;s own installer takes switches that install it for every account without showing a window.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>In an elevated PowerShell session:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$installer</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$env:TEMP</span> <span class="s1">&#39;VSCodeSetup-x64.exe&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Invoke-WebRequest</span> <span class="n">-OutFile</span> <span class="nv">$installer</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Uri</span> <span class="s1">&#39;https://code.visualstudio.com/sha/download?build=stable&amp;os=win32-x64&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Start-Process</span> <span class="n">-FilePath</span> <span class="nv">$installer</span> <span class="n">-Wait</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-ArgumentList</span> <span class="s1">&#39;/VERYSILENT&#39;</span><span class="p">,</span> <span class="s1">&#39;/NORESTART&#39;</span><span class="p">,</span> <span class="s1">&#39;/MERGETASKS=!runcode,addtopath&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Remove-Item</span> <span class="nv">$installer</span></span></span></code></pre></div></div>
  </div>
</div><p><code>/VERYSILENT</code> shows no window. <code>/NORESTART</code> never reboots the machine. <code>!runcode</code> stops the installer from opening VS Code when it finishes. <code>addtopath</code> puts <code>code</code> on the system PATH for the next sign-in.</p>

</div>

<p>On a machine that has winget, <code>winget install Microsoft.VisualStudioCode --scope machine --silent</code>
does this job with less to know. Windows Server 2022 doesn&rsquo;t ship winget.
VS Code&rsquo;s Windows installer is an Inno
Setup package, and Inno Setup has had stable command-line switches for
decades. The whole job is fetching the right build, running it with those
switches, and knowing which of its optional tasks to turn on or off.</p>
<!-- style-check: procedure -->
<h2 id="download-the-system-installer">Download the system installer<a class="heading-anchor" href="https://looselydecoupled.com/install-vscode-silently-powershell/#download-the-system-installer"
     aria-label="Link to section: Download the system installer" data-pagefind-ignore></a>
</h2>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$installer</span> <span class="p">=</span> <span class="nb">Join-Path</span> <span class="nv">$env:TEMP</span> <span class="s1">&#39;VSCodeSetup-x64.exe&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Invoke-WebRequest</span> <span class="n">-OutFile</span> <span class="nv">$installer</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-Uri</span> <span class="s1">&#39;https://code.visualstudio.com/sha/download?build=stable&amp;os=win32-x64&#39;</span></span></span></code></pre></div></div>
  </div>
</div><p>That URL is Microsoft&rsquo;s documented direct-download link for the current stable
<strong>system</strong> installer, which puts VS Code under <code>Program Files</code> for every
account on the machine. Change <code>os=win32-x64</code> to <code>os=win32-x64-user</code> for the
per-user installer, which needs no elevation and installs under one account&rsquo;s
<code>%LocalAppData%</code>. For a server or a shared workstation the system build is the
one you want.</p>
<p>On Windows PowerShell 5.1 the download is faster with the progress bar off:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$ProgressPreference</span> <span class="p">=</span> <span class="s1">&#39;SilentlyContinue&#39;</span></span></span></code></pre></div></div>
  </div>
</div><h2 id="run-it-without-a-window">Run it without a window<a class="heading-anchor" href="https://looselydecoupled.com/install-vscode-silently-powershell/#run-it-without-a-window"
     aria-label="Link to section: Run it without a window" data-pagefind-ignore></a>
</h2>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Start-Process</span> <span class="n">-FilePath</span> <span class="nv">$installer</span> <span class="n">-Wait</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">    <span class="n">-ArgumentList</span> <span class="s1">&#39;/VERYSILENT&#39;</span><span class="p">,</span> <span class="s1">&#39;/NORESTART&#39;</span><span class="p">,</span> <span class="s1">&#39;/MERGETASKS=!runcode,addtopath&#39;</span></span></span></code></pre></div></div>
  </div>
</div><p>Inno Setup reads its switches before it draws anything, so <code>/VERYSILENT</code> with
<code>/NORESTART</code> is a complete unattended install with no answer file. <code>-Wait</code>
matters. Without it the script moves on while the installer is still
running, and anything after — a settings file, an extension install — races
it.</p>
<p>The switches:</p>
<div class="table-wrap" data-scrollable data-label="Table: Switch">
  <table>
    <thead>
      <tr><th scope="col">Switch</th><th scope="col">Effect</th></tr>
    </thead>
    <tbody>
      <tr><td><code>/VERYSILENT</code></td><td>No wizard, no progress window. <code>/SILENT</code> shows progress only.</td></tr>
      <tr><td><code>/NORESTART</code></td><td>Never reboot, even when the installer requests one.</td></tr>
      <tr><td><code>/MERGETASKS=…</code></td><td>Turn the optional tasks on or off; a leading <code>!</code> turns one off.</td></tr>
    </tbody>
  </table>
</div>
<p>The installer offers six tasks. After install, <code>runcode</code> launches the editor,
<code>addtopath</code> edits PATH, and <code>associatewithfiles</code> registers Code as an editor
for supported file types. The other three, <code>desktopicon</code>,
<code>addcontextmenufiles</code> and <code>addcontextmenufolders</code>, add the shortcut and the
&ldquo;Open with Code&rdquo; entries in Explorer. On a headless install <code>runcode</code> leaves an
editor window nobody will ever see, and it is on by default, so turn it off.
Turning <code>runcode</code> off leaves every other task as it was, because <code>/MERGETASKS</code>
applies your changes on top of the installer&rsquo;s defaults. The <code>/TASKS</code> switch
would replace them wholesale.</p>
<h2 id="verify">Verify<a class="heading-anchor" href="https://looselydecoupled.com/install-vscode-silently-powershell/#verify"
     aria-label="Link to section: Verify" data-pagefind-ignore></a>
</h2>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Remove-Item</span> <span class="nv">$installer</span>
</span></span><span class="line"><span class="cl"><span class="nb">Test-Path</span> <span class="s2">&#34;</span><span class="nv">$env:ProgramFiles</span><span class="s2">\Microsoft VS Code\Code.exe&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">&amp;</span> <span class="s2">&#34;</span><span class="nv">$env:ProgramFiles</span><span class="s2">\Microsoft VS Code\bin\code.cmd&#34;</span> <span class="p">-</span><span class="n">-version</span></span></span></code></pre></div></div>
  </div>
</div><p>The version check calls the launcher by path because the PATH change from
<code>addtopath</code> is not visible in the session that ran the installer.</p>
<!-- style-check: end procedure -->
<h2 id="expected-result">Expected result<a class="heading-anchor" href="https://looselydecoupled.com/install-vscode-silently-powershell/#expected-result"
     aria-label="Link to section: Expected result" data-pagefind-ignore></a>
</h2>
<p><code>Code.exe</code> exists under <code>Program Files\Microsoft VS Code</code>, the uninstall entry
reports the version you expected, and <code>code --version</code> works in a new shell.
A new one, because <code>addtopath</code> edits the machine PATH and the session that ran
the installer still has the old one.</p>
<h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/install-vscode-silently-powershell/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="script-hangs-at-start-process">Script hangs at <code>Start-Process</code><a class="heading-anchor" href="https://looselydecoupled.com/install-vscode-silently-powershell/#script-hangs-at-start-process"
     aria-label="Link to section: Script hangs at Start-Process" data-pagefind-ignore></a>
</h3>
<p>The installer is showing a dialog you can&rsquo;t see. Usually VS Code is already
running under this account and Inno Setup is asking whether to close it. Stop
<code>Code.exe</code> first, or add <code>/CLOSEAPPLICATIONS</code>.</p>
<h3 id="access-denied-under-program-files">Access denied under <code>Program Files</code><a class="heading-anchor" href="https://looselydecoupled.com/install-vscode-silently-powershell/#access-denied-under-program-files"
     aria-label="Link to section: Access denied under Program Files" data-pagefind-ignore></a>
</h3>
<p>The session isn&rsquo;t elevated. The system installer needs it; the user installer
doesn&rsquo;t.</p>
<h3 id="code-isnt-recognized-after-the-install"><code>code</code> isn&rsquo;t recognized after the install<a class="heading-anchor" href="https://looselydecoupled.com/install-vscode-silently-powershell/#code-isnt-recognized-after-the-install"
     aria-label="Link to section: code isn’t recognized after the install" data-pagefind-ignore></a>
</h3>
<p>Either <code>addtopath</code> wasn&rsquo;t in <code>/MERGETASKS</code>, or you&rsquo;re in the same shell that
ran the installer. Open a new one. On Windows Server the change reaches
services and scheduled tasks only after they restart.</p>
<h3 id="download-is-a-few-kilobytes-of-html">Download is a few kilobytes of HTML<a class="heading-anchor" href="https://looselydecoupled.com/install-vscode-silently-powershell/#download-is-a-few-kilobytes-of-html"
     aria-label="Link to section: Download is a few kilobytes of HTML" data-pagefind-ignore></a>
</h3>
<p>The download URL redirected to an error page, from a proxy or an outbound rule
blocking the CDN. Check the signature before running it:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-AuthenticodeSignature</span> <span class="nv">$installer</span> <span class="p">|</span> <span class="nb">Select-Object</span> <span class="n">Status</span><span class="p">,</span> <span class="n">SignerCertificate</span></span></span></code></pre></div></div>
  </div>
</div><p>The real installer reports <code>Valid</code>, signed by Microsoft Corporation. Anything
else means the file isn&rsquo;t the installer; don&rsquo;t run it.</p>
<div class="tested" id="tested">
  <p class="label label--seam">Tested with</p><dl class="tested__rows">
    <div class="tested__row"><dt>OS</dt> <dd>Windows Server 2019 (10.0.17763)</dd></div>
    <div class="tested__row"><dt>PowerShell</dt> <dd>Windows PowerShell 5.1</dd></div>
    <div class="tested__row"><dt>VS Code</dt> <dd>1.139.0 upgraded to 1.140.0</dd></div>
    <div class="tested__row"><dt>Installer</dt> <dd>system, Inno Setup</dd></div>
    <div class="tested__row"><dt>Date</dt> <dd>October 2026</dd></div>
  </dl>
</div>
]]></content:encoded>
    </item>
    
    <item>
      <title>How to Show File Extensions in File Explorer with PowerShell</title>
      <link>https://looselydecoupled.com/show-file-extensions-windows-powershell/</link>
      <guid isPermaLink="true">https://looselydecoupled.com/show-file-extensions-windows-powershell/</guid>
      <pubDate>Sat, 04 Nov 2023 00:00:00 +0000</pubDate>
      <dc:creator>Emmanuel Tsouris</dc:creator>
      <category>Unattended</category>
      <category>PowerShell</category>
      
      <description>HideFileExt set to 0 shows file extensions for your account, and one Active Setup entry sets it for every account on the machine at its next sign-in.</description>
      <content:encoded><![CDATA[<div class="answer" data-answer="true">
  <p class="answer__label" data-pagefind-ignore>TL;DR</p>
  <p>For the account you are signed in as:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$advanced</span> <span class="p">=</span> <span class="s1">&#39;HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Set-ItemProperty</span> <span class="n">-Path</span> <span class="nv">$advanced</span> <span class="n">-Name</span> <span class="n">HideFileExt</span> <span class="n">-Value</span> <span class="mf">0</span> <span class="n">-Type</span> <span class="n">DWord</span>
</span></span><span class="line"><span class="cl"><span class="nb">Stop-Process</span> <span class="n">-Name</span> <span class="n">explorer</span> <span class="n">-Force</span></span></span></code></pre></div></div>
  </div>
</div><p>Windows restarts the shell. Every window then shows <code>report.txt.exe</code> as what it is. Run the command unelevated. The setting is per user and lives in the hive of whoever runs the command. An unelevated session can stop only its own Explorer.</p>

</div>

<p>Windows hides the extension of known file types by default, so <code>invoice.pdf</code>
and <code>invoice.pdf.exe</code> look the same in Explorer. Turning that off is the first
thing to do on any machine you&rsquo;ll administer from the desktop, and the
setting is one DWORD.</p>
<h2 id="where-the-setting-lives">Where the setting lives<a class="heading-anchor" href="https://looselydecoupled.com/show-file-extensions-windows-powershell/#where-the-setting-lives"
     aria-label="Link to section: Where the setting lives" data-pagefind-ignore></a>
</h2>
<div class="code-block" data-copyable data-copy-label="Text">
  <div class="code-block__head"><span class="code-block__lang">Text</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
</span></span><span class="line"><span class="cl">    HideFileExt    REG_DWORD    0 = show extensions, 1 = hide</span></span></code></pre></div></div>
  </div>
</div><p>Explorer reads the value when it starts, which is why the answer restarts it:
a write from PowerShell notifies nothing, and open windows stay as they were.
Stopping it with <code>Stop-Process -Name explorer</code> ends the shell process;
Winlogon relaunches it (<code>AutoRestartShell</code>, on by default), so the taskbar is
back within a second or two.</p>
<div class="admonition admonition--warning" role="note">
  <p class="admonition__label">
    <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><use href="https://looselydecoupled.com/show-file-extensions-windows-powershell/#i-triangle-alert"/></svg>
    <span>Warning</span>
  </p>
  <p>Elevated, <code>Stop-Process -Name explorer -Force</code> stops every user&rsquo;s Explorer
on the machine, not only yours — on a server with other people signed in
over RDP, that is their desktop vanishing. From an elevated session, stop
only the one in your session:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Get-Process</span> <span class="n">-Name</span> <span class="n">explorer</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Where-Object</span> <span class="n">SessionId</span> <span class="o">-eq</span> <span class="p">(</span><span class="nb">Get-Process</span> <span class="n">-Id</span> <span class="nv">$PID</span><span class="p">).</span><span class="py">SessionId</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">    <span class="nb">Stop-Process</span> <span class="n">-Force</span></span></span></code></pre></div></div>
  </div>
</div>
</div><!-- style-check: procedure -->
<h2 id="for-every-account-including-ones-that-do-not-exist-yet">For every account, including ones that do not exist yet<a class="heading-anchor" href="https://looselydecoupled.com/show-file-extensions-windows-powershell/#for-every-account-including-ones-that-do-not-exist-yet"
     aria-label="Link to section: For every account, including ones that do not exist yet" data-pagefind-ignore></a>
</h2>
<p><code>HKCU</code> is the current user&rsquo;s hive, so the command above changes one account.
On a server where several administrators sign in, put the same command where
Windows runs it once for each user at their next sign-in, before Explorer
starts. That is Active Setup, and it is a key under <code>HKLM</code>, so it is set with
the registry provider from an elevated session:</p>
<div class="code-block" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$stub</span> <span class="p">=</span> <span class="s1">&#39;HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\ShowFileExtensions&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">New-Item</span> <span class="n">-Path</span> <span class="nv">$stub</span> <span class="n">-Force</span> <span class="p">|</span> <span class="nb">Out-Null</span>
</span></span><span class="line"><span class="cl"><span class="nb">Set-ItemProperty</span> <span class="n">-Path</span> <span class="nv">$stub</span> <span class="n">-Name</span> <span class="s1">&#39;(Default)&#39;</span>   <span class="n">-Value</span> <span class="s1">&#39;Show file extensions&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Set-ItemProperty</span> <span class="n">-Path</span> <span class="nv">$stub</span> <span class="n">-Name</span> <span class="s1">&#39;IsInstalled&#39;</span> <span class="n">-Value</span> <span class="mf">1</span> <span class="n">-Type</span> <span class="n">DWord</span>
</span></span><span class="line"><span class="cl"><span class="nb">Set-ItemProperty</span> <span class="n">-Path</span> <span class="nv">$stub</span> <span class="n">-Name</span> <span class="s1">&#39;Version&#39;</span>     <span class="n">-Value</span> <span class="s1">&#39;1&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$advanced</span> <span class="p">=</span> <span class="s1">&#39;HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">$command</span> <span class="p">=</span> <span class="s2">&#34;Set-ItemProperty -Path &#39;</span><span class="nv">$advanced</span><span class="s2">&#39; -Name HideFileExt -Value 0&#34;</span>
</span></span><span class="line"><span class="cl"><span class="nb">Set-ItemProperty</span> <span class="n">-Path</span> <span class="nv">$stub</span> <span class="n">-Name</span> <span class="s1">&#39;StubPath&#39;</span> <span class="n">-Value</span> <span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="s1">&#39;powershell.exe -NoProfile -WindowStyle Hidden -Command &#34;&#39;</span> <span class="p">+</span> <span class="nv">$command</span> <span class="p">+</span> <span class="s1">&#39;&#34;&#39;</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span></span></span></code></pre></div></div>
  </div>
</div><p>At each sign-in Windows compares <code>Version</code> here against the copy under that
user&rsquo;s <code>HKCU\Software\Microsoft\Active Setup\Installed Components</code>. When the
user has none, or an older one, it runs <code>StubPath</code> as that user and records
the version. So the command runs once per account: existing accounts at their
next sign-in, new accounts at their first. It runs while the shell is still
starting, before the desktop is shown, so the first Explorer window a user
opens already shows extensions. To run it again for everyone, raise <code>Version</code>;
to stop it running for anyone new, delete the key under <code>HKLM</code>. Users who
already ran it keep the setting either way.</p>
<p>A console window can flash for a moment at sign-in while the stub runs;
<code>-WindowStyle Hidden</code> hides it as soon as PowerShell has started, not before.</p>
<p>This is the whole mechanism Windows uses to seed per-user settings from a
machine-wide install. It is the one route to &ldquo;every account&rdquo; that needs no
hive loading and no tool outside PowerShell. Group Policy Preferences does the
same job on a domain-joined machine.</p>
<!-- style-check: end procedure -->
<h2 id="common-failures">Common failures<a class="heading-anchor" href="https://looselydecoupled.com/show-file-extensions-windows-powershell/#common-failures"
     aria-label="Link to section: Common failures" data-pagefind-ignore></a>
</h2>
<h3 id="value-is-0-and-extensions-are-still-hidden">Value is <code>0</code> and extensions are still hidden<a class="heading-anchor" href="https://looselydecoupled.com/show-file-extensions-windows-powershell/#value-is-0-and-extensions-are-still-hidden"
     aria-label="Link to section: Value is 0 and extensions are still hidden" data-pagefind-ignore></a>
</h3>
<p>You ran the command elevated as a different account. An elevated PowerShell
opened with &ldquo;Run as administrator&rdquo; and a second set of credentials writes to
that account&rsquo;s <code>HKCU</code>, not yours. Run it unelevated in your own session.</p>
<h3 id="taskbar-didnt-come-back-after-stop-process">Taskbar didn&rsquo;t come back after <code>Stop-Process</code><a class="heading-anchor" href="https://looselydecoupled.com/show-file-extensions-windows-powershell/#taskbar-didnt-come-back-after-stop-process"
     aria-label="Link to section: Taskbar didn’t come back after Stop-Process" data-pagefind-ignore></a>
</h3>
<p><code>AutoRestartShell</code> is off on that machine, or the process was ended from
outside the session it belonged to. Start it by hand:</p>
<div class="code-block code-block--wrap" data-copyable data-copy-label="PowerShell">
  <div class="code-block__head"><span class="code-block__lang">PowerShell</span>
  </div>
  <div class="code-block__scroll">
    <div data-copy-source><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">Start-Process</span> <span class="n">explorer</span></span></span></code></pre></div></div>
  </div>
</div><p>On Server Core there&rsquo;s no Explorer to stop and no setting to change;
<code>Stop-Process</code> reports that no such process exists.</p>
<h3 id="extensions-still-hidden-for-another-user">Extensions still hidden for another user<a class="heading-anchor" href="https://looselydecoupled.com/show-file-extensions-windows-powershell/#extensions-still-hidden-for-another-user"
     aria-label="Link to section: Extensions still hidden for another user" data-pagefind-ignore></a>
</h3>
<p>The user hasn&rsquo;t signed out and in since it was written; Active Setup runs at
sign-in and nowhere else. Or the stub ran under a policy that blocks
<code>powershell.exe</code> for that user. Check
<code>HKCU\Software\Microsoft\Active Setup\Installed Components\ShowFileExtensions</code>
in their hive: present means the stub was launched, absent means it wasn&rsquo;t.</p>
]]></content:encoded>
    </item>
    
  </channel>
</rss>
