> For the complete documentation index, see [llms.txt](https://help.nightfall.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.nightfall.ai/data-exfiltration-prevention/exfiltration_endpoint/install-nightfall-ai-agent-for-windows-os/nightfall-windows-agent-deployment-msi.md).

# Nightfall Windows Agent Deployment: MSI

Install, verify, and uninstall the Nightfall agent on Windows devices with the MSI installer.

Nightfall provides the Windows agent as an MSI installer, `NightfallAgent.msi`. Every installation requires the `API_KEY` and `COMPANY_ID` properties, which connect the agent to your Nightfall account, and the `REGION` property. You can pass them through a PowerShell script, a Group Policy (GPO) startup script, or a one-line command, depending on how you manage your devices.

## What you will learn in this topic

By the end of this topic, you will know:

* The steps to install the agent with a PowerShell script, from a local MSI, a network share, or a URL.
* The steps to deploy the agent through GPO.
* How to install the agent on a single device for testing.
* How to verify the installation.
* How to uninstall the agent, whether or not the `.msi` file is on the device.

***

## Before you begin

* Make sure that you have the MSI installer, `NightfallAgent.msi`, and its install command. You can download both from the Nightfall console. The install command contains your values for `API_KEY`, `COMPANY_ID`, and `REGION`.
* You must have *Administrator* rights on the device.

***

## Choose a deployment method

Nightfall provides the following methods for MSI deployment. From this list, you can choose the one that matches where you keep the MSI and how you manage your devices:

| Method                                       | Use It When                                                                                        |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| Install from a local MSI                     | You or your remote monitoring and management (RMM) tool place the `.msi` file on the device first. |
| Install from a network share                 | You keep the MSI on a file server.                                                                 |
| Install from a URL                           | You host the MSI on an internal HTTPS server or a content delivery network (CDN).                  |
| Deploy with a startup script                 | You manage domain-joined devices. Nightfall recommends this method for them.                       |
| Deploy with Software Installation and an MST | You have an MST transform that embeds `API_KEY`, `COMPANY_ID`, and `REGION`.                       |
| Install on a single device                   | You want to test the installation on one device.                                                   |

***

## Install the agent with PowerShell

Each script installs the agent silently (`/qn /norestart`) and writes a verbose log (`/l*v`) that you can use for troubleshooting.

{% hint style="info" %}
**Note**:

* In each script, replace the placeholders with the values from the install command on the Nightfall console. Replace `$region` with your tenant's region in lowercase, for example `us` or `uk`.
* If `REGION` does not match a supported region, the agent service does not start. If you leave out `REGION`, the agent connects to the US region.
  {% endhint %}

{% tabs %}
{% tab title="Install from a local MSI" %}
Use this script if you or your RMM tool place the `.msi` file on the device before the script runs.

```powershell
# Install-NightfallAgent-Local.ps1

$msiPath   = "C:\Temp\NightfallAgent.msi"
$apiKey    = "REPLACE_WITH_API_KEY"
$companyId = "REPLACE_WITH_COMPANY_ID"
$region    = "<REGION>"

$logDir = "C:\Windows\Temp\Nightfall"
$logFile = Join-Path $logDir "NightfallAgent_Install.log"

New-Item -ItemType Directory -Path $logDir -Force | Out-Null

if (Test-Path $msiPath) {
    Write-Output "MSI found at $msiPath. Starting install..."
    $args = "/i `"$msiPath`" API_KEY=`"$apiKey`" COMPANY_ID=`"$companyId`" REGION=`"$region`" INSTALL_NF_DRIVER=`"1`" /qn /norestart /l*v `"$logFile`""
    $proc = Start-Process "msiexec.exe" -ArgumentList $args -Wait -PassThru -NoNewWindow
    if ($proc.ExitCode -eq 0) {
        Write-Output "Nightfall agent installed successfully."
    } else {
        Write-Output "Installer returned exit code $($proc.ExitCode). Check log: $logFile"
        exit $proc.ExitCode
    }
} else {
    Write-Output "MSI not found at $msiPath. Skipping install."
    exit 2
}
```

{% endtab %}

{% tab title="Install from a network share" %}
Use this script if you keep the MSI on a file server. Make sure that Domain Computers or the target devices have read access to the share.

{% hint style="info" %}
**Note**:

Use UNC paths, such as `\\server\share\...`. Mapped drives do not work for GPO startup scripts.
{% endhint %}

```powershell
# Install-NightfallAgent-FromShare.ps1

$sourceMsi = "\\fileserver\software\Nightfall\NightfallAgent.msi"
$localMsi  = "C:\Temp\NightfallAgent.msi"
$apiKey    = "YOUR_API_KEY_HERE"
$companyId = "YOUR_SECRET_VALUE"
$region    = "<REGION>"

$logDir = "C:\Windows\Temp\Nightfall"
$logFile = Join-Path $logDir "NightfallAgent_Install.log"

New-Item -ItemType Directory -Path $logDir -Force | Out-Null
New-Item -ItemType Directory -Path (Split-Path $localMsi) -Force | Out-Null

Write-Output "Copying MSI from $sourceMsi to $localMsi..."
Copy-Item -Path $sourceMsi -Destination $localMsi -Force -ErrorAction Stop

if (Test-Path $localMsi) {
    Write-Output "Copy complete. Starting install..."
    $args = "/i `"$localMsi`" API_KEY=`"$apiKey`" COMPANY_ID=`"$companyId`" REGION=`"$region`" INSTALL_NF_DRIVER=`"1`" /qn /norestart /l*v `"$logFile`""
    $proc = Start-Process "msiexec.exe" -ArgumentList $args -Wait -PassThru -NoNewWindow
    if ($proc.ExitCode -eq 0) {
        Write-Output "Nightfall agent installed successfully."
    } else {
        Write-Output "Installer returned exit code $($proc.ExitCode). Check log: $logFile"
        exit $proc.ExitCode
    }
} else {
    Write-Output "MSI copy failed. Check share permissions and path."
    exit 3
}
```

{% endtab %}

{% tab title="Install from a URL" %}
Use this script if you host the MSI on an internal HTTPS server or a CDN. The script downloads the MSI, checks that the file is a valid MSI, and then installs the agent silently. Run it with administrator rights. It also works as a GPO startup script.

```powershell
# Install-NightfallAgent-FromUrl.ps1
# Purpose: Download the Nightfall MSI from a URL, validate it looks like a real MSI, then install silently.
# Notes:
#   - Run elevated (admin). Works as a GPO Startup script.

# --- EDIT THESE VALUES ---
$downloadUrl = "https://example.com/NightfallAgent.msi"  # <-- Replace with your direct MSI URL
$localMsi    = "C:\Temp\NightfallAgent.msi"
$apiKey      = "<API_KEY>"        # <-- Replace
$companyId   = "<COMPANY_ID>"     # <-- Replace
$region      = "<REGION>"         # <-- Replace
# --------------------------

$ErrorActionPreference = "Stop"

# Paths for logging
$logDir  = "C:\Windows\Temp\Nightfall"
$logFile = Join-Path $logDir "NightfallAgent_Install.log"

# Ensure folders exist
New-Item -ItemType Directory -Path (Split-Path $localMsi) -Force | Out-Null
New-Item -ItemType Directory -Path $logDir -Force | Out-Null

# Helper: quick MSI signature + size sanity check
function Test-IsMsi {
    param([string]$Path)
    if (-not (Test-Path $Path)) { return $false }
    $len = (Get-Item $Path).Length
    if ($len -lt 1MB) { return $false } # tiny files are likely HTML/error pages

    # MSI is a CFBF (OLE) container: header D0 CF 11 E0 A1 B1 1A E1
    $fs = [System.IO.File]::Open($Path, 'Open', 'Read', 'ReadWrite')
    try {
        $buf = New-Object byte[] 8
        [void]$fs.Read($buf, 0, 8)
        $hex = ($buf | ForEach-Object { $_.ToString("X2") }) -join " "
        return ($hex -eq "D0 CF 11 E0 A1 B1 1A E1")
    } finally {
        $fs.Close()
    }
}

Write-Output "Downloading MSI from $downloadUrl ..."
try {
    # Use HttpClient for robust redirects + streaming
    Add-Type -AssemblyName System.Net.Http
    $handler = New-Object System.Net.Http.HttpClientHandler
    $handler.AllowAutoRedirect = $true
    $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor `
                                      [System.Net.DecompressionMethods]::Deflate -bor `
                                      [System.Net.DecompressionMethods]::Brotli
    $client = New-Object System.Net.Http.HttpClient($handler)
    $client.Timeout = [TimeSpan]::FromMinutes(10)
    $client.DefaultRequestHeaders.UserAgent.ParseAdd("Nightfall-Agent-Installer/1.0")

    $response = $client.GetAsync($downloadUrl, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult()
    if (-not $response.IsSuccessStatusCode) {
        throw "HTTP $([int]$response.StatusCode) $($response.ReasonPhrase)"
    }

    $stream = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
    $tmp = "$localMsi.download"
    $fs = [System.IO.File]::Open($tmp, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
    try {
        $buffer = New-Object byte[] (1024*256) # 256 KB chunks
        while (($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) {
            $fs.Write($buffer, 0, $read)
        }
    } finally {
        $fs.Dispose()
        $stream.Dispose()
        $client.Dispose()
        $handler.Dispose()
    }

    if (Test-Path $localMsi) { Remove-Item $localMsi -Force }
    Move-Item $tmp $localMsi -Force

} catch {
    Write-Error "Download failed: $($_.Exception.Message)"
    exit 100
}

# Validate the download looks like a real MSI
if (-not (Test-IsMsi -Path $localMsi)) {
    $size = (Get-Item $localMsi).Length
    Write-Error "Downloaded file does not look like a valid MSI (size=$size bytes). The URL may be a landing page or error."
    exit 101
}

# Remove MOTW just in case
try { Unblock-File -Path $localMsi -ErrorAction SilentlyContinue } catch {}

# Install silently with logging
Write-Output "MSI validated. Installing Nightfall Agent..."
$args = "/i `"$localMsi`" API_KEY=`"$apiKey`" COMPANY_ID=`"$companyId`" REGION=`"$region`" INSTALL_NF_DRIVER=`"1`" /qn /norestart /l*v `"$logFile`""
$proc = Start-Process "msiexec.exe" -ArgumentList $args -Wait -PassThru -NoNewWindow

switch ($proc.ExitCode) {
    0     { Write-Output "Nightfall Agent installed successfully."; exit 0 }
    1603  { Write-Error "Fatal error during installation (1603). See log: $logFile"; exit 1603 }
    1618  { Write-Error "Another installation is already in progress (1618)."; exit 1618 }
    1620  { Write-Error "Package could not be opened (1620). File may be invalid. See log: $logFile"; exit 1620 }
    default { Write-Error "Installer returned exit code $($proc.ExitCode). See log: $logFile"; exit $proc.ExitCode }
}
```

{% endtab %}
{% endtabs %}

***

## Deploy the agent through Group Policy

For domain-joined Windows devices, Nightfall recommends a GPO startup script. The built-in **Software Installation** GPO cannot pass custom properties such as `API_KEY`, unless you use an MST transform.

{% tabs %}
{% tab title="Deploy with a startup script" %}
Complete the following steps:

1. Place the script, for example `Install-NightfallAgent-FromShare.ps1`, in `\\<domain>\SYSVOL\<domain>\scripts\Nightfall\`.
2. Make sure that Domain Computers have read access to the script.
3. In Group Policy Management, navigate to **Computer Configuration** → **Policies** → **Windows Settings** → **Scripts (Startup/Shutdown)**.
4. Add a startup script with the following values:
   * **Script name**: `powershell.exe`
   * **Script parameters**: `-ExecutionPolicy Bypass -File "\\SYSVOL<domain>\scripts\Nightfall\Install-NightfallAgent-FromShare.ps1"`
5. Apply the GPO to the target organizational unit (OU).
6. Run `gpupdate /force` or restart a target device.
   {% endtab %}

{% tab title="Deploy with Software Installation and an MST (Advanced)" %}
If you have an MST transform that embeds `API_KEY`, `COMPANY_ID`, and `REGION`, you can deploy the MSI by navigating to **Computer Configuration** → **Policies** → **Software Settings** → **Software installation**.

Complete the following steps:

1. Add the MSI through a UNC path.
2. Open its **Properties** → **Modifications**, and add your `.mst` file.

Without an MST, use a GPO startup script instead.
{% endtab %}
{% endtabs %}

***

## Install on a single device for testing

Run the following command manually on one device, in an elevated PowerShell window. Replace the placeholders with the values from the install command on the Nightfall console.

```
$msiPath="C:\Temp\NightfallAgent.msi"; Start-Process msiexec.exe -ArgumentList "/i `"$msiPath`" API_KEY=`"YOUR_API_KEY_HERE`" COMPANY_ID=`"YOUR_SECRET_VALUE`" REGION=`"<REGION>`" INSTALL_NF_DRIVER=`"1`" /qn /norestart /l*v `"`"C:\Windows\Temp\Nightfall\NightfallAgent_Install.log`"`"" -Wait
```

***

## Verify the installation

After the installation, check the device by completing the following steps:

1. Check that the expected services are present:

{% code fullWidth="false" %}

```powershell
Get-Service Nightfall*
```

{% endcode %}

2. Confirm that the Nightfall AI icon appears in the system tray. It can take a few seconds to appear.
3. Double-click the icon. The agent shows a connected status, as in the following image.

<figure><img src="https://3764378997-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZeqNSdo8J8cLJPU3Gs5M%2Fuploads%2FZYYdTA1M0SkuWHkMnyLC%2FScreenshot%202025-09-05%20at%208.03.06%E2%80%AFPM.png?alt=media&amp;token=bb9e026e-ac0c-4a18-bc13-64da4e23ddb9" alt="Nightfall agent window showing a connected status" width="269"><figcaption></figcaption></figure>

***

## Uninstalling the Nightfall AI agent

Use the `Uninstall-NightfallAgent.ps1` script below to uninstall the Nightfall agent. The script finds the installed agent through Windows Installer, so you can run it whether or not the `.msi` file is on the device. It runs the standard MSI uninstall, which also removes the installer registration, so you can reinstall the agent afterward without any manual cleanup.

Run the script as an *Administrator*. If tamper protection is enabled for the agent, pass your maintenance token with the `-AuthToken` parameter. Otherwise, leave the parameter out.

```powershell
# Without tamper protection
.\Uninstall-NightfallAgent.ps1

# With tamper protection
.\Uninstall-NightfallAgent.ps1 -AuthToken "<MAINTENANCE_TOKEN>"
```

To run the script from a deployment tool, such as SCCM, use the following command:

```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File Uninstall-NightfallAgent.ps1
```

{% hint style="info" %}
**Note**:

Do not delete Nightfall files or registry entries by hand. Manual cleanup can leave the installer registration behind, and the next install then fails with error `1603`.
{% endhint %}

Use the following script to uninstall the Nightfall AI agent:

```powershell
# Uninstall-NightfallAgent.ps1
# Uninstalls the NightfallAI Agent. Run as administrator.
param(
    # Maintenance token. Required only if tamper protection is enabled for this agent;
    # otherwise optional and can be left out. Example: .\Uninstall-NightfallAgent.ps1 -AuthToken "<token>"
    [string]$AuthToken
)

# Administrator rights are required to uninstall.
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Warning "Run this script as administrator."
    exit 5
}

# A double quote in the token cannot be passed to msiexec reliably, and a malformed command line can leave msiexec
# waiting forever, so such a token is refused before anything runs.
if ($AuthToken -and $AuthToken.Contains('"')) {
    Write-Warning "The maintenance token contains a double quote character, which msiexec cannot be given reliably. Use a token without one."
    exit 87
}

$ProductName = "NightfallAI Agent"

# Uninstall logs are written here.
$LogDir = "C:\Windows\Temp\Nightfall"
New-Item -ItemType Directory -Path $LogDir -Force | Out-Null

$script:Failed = $false

# Returns the installed products whose name exactly matches the given name.
function Get-MatchingProducts($name) {
    Write-Host "Searching for products named: '$name'..."
    $installer = New-Object -ComObject WindowsInstaller.Installer
    # PowerShell cannot read this property directly, so it is read through InvokeMember.
    $codes = $installer.GetType().InvokeMember('Products', 'GetProperty', $null, $installer, $null)
    foreach ($code in $codes) {
        try { $productName = $installer.ProductInfo($code, 'ProductName') } catch { continue }
        if ($productName -eq $name) {
            [pscustomobject]@{ Name = $productName; IdentifyingNumber = $code }
        }
    }
}

# Uninstalls a product by its ProductCode.
function Uninstall-Product($product) {
    $name = $product.Name
    $productCode = $product.IdentifyingNumber

    if ($productCode) {
        $logFile = Join-Path $LogDir ("NightfallAgent_Uninstall_{0}.log" -f $productCode.Trim('{}'))
        # /norestart: do not restart the computer automatically
        $msiArgs = "/x $productCode /qn /norestart /l*v `"$logFile`""
        if ($AuthToken) { $msiArgs += " AUTH_TOKEN=`"$AuthToken`"" }

        Write-Host "Uninstalling '$name' (ProductCode: $productCode)..." -ForegroundColor Green
        $proc = Start-Process "msiexec.exe" -ArgumentList $msiArgs -Wait -PassThru -NoNewWindow

        switch ($proc.ExitCode) {
            { $_ -in 0, 3010, 1641 } {
                Write-Host "Uninstalled: $name" -ForegroundColor Green
                if ($_ -ne 0) { Write-Warning "A restart is required to finish removing '$name'." }
            }
            1605 { Write-Host "Already removed: $name" }
            default {
                $hint = switch ($proc.ExitCode) {
                    1603 { " (blocked: the maintenance token is missing or wrong, or the agent is damaged or its files were removed. If the token is correct, contact Nightfall support)" }
                    1618 { " (another installation is already in progress; try again in a few minutes)" }
                    1730 { " (run this script as administrator)" }
                    default { "" }
                }
                Write-Warning "msiexec exited with $($proc.ExitCode) for '$name'$hint. Log: $logFile"
                $script:Failed = $true
            }
        }
    } else {
        Write-Warning "Skipping ${name}: missing ProductCode."
    }
}

$products = @(Get-MatchingProducts -name $ProductName)

if ($products.Count -eq 0) {
    # A service that is still there means the installer registration is damaged, which is not the same as already removed.
    if (Get-Service -Name "NightfallAgent" -ErrorAction SilentlyContinue) {
        Write-Warning "No installed product named '${ProductName}' was found, but the NightfallAgent service is still present. The agent's installer registration may be damaged. Contact Nightfall support."
        exit 1
    }
    Write-Host "'${ProductName}' is not installed. Nothing to uninstall."
    exit 0
}

foreach ($product in $products) {
    Uninstall-Product -product $product
}

if ($script:Failed) { exit 1 }
```

The script writes the uninstall log to `C:\Windows\Temp\Nightfall\NightfallAgent_Uninstall_<ProductCode>.log`. If the uninstall needs a restart to finish, the script shows a warning. Restart the device to complete the removal.

The script exits with one of the following codes:

| Exit Code | Meaning                                                                                                                                                                                            |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `0`       | The agent was uninstalled, or it was not installed.                                                                                                                                                |
| `1`       | The uninstall failed, or the `NightfallAgent` service is still present but no installed agent was found. In the second case, the installer registration may be damaged. Contact Nightfall support. |
| `5`       | The script was not run as an administrator.                                                                                                                                                        |
| `87`      | The maintenance token contains a double quote character. Use a token without one.                                                                                                                  |

When the uninstall fails, the script shows the Windows Installer error code and the path to the log. The most common codes are:

| Error Code | Meaning                                                                                                                                                                      |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `1603`     | The uninstall was blocked. The maintenance token is missing or wrong, or the agent is damaged or its files were removed. If the token is correct, contact Nightfall support. |
| `1618`     | Another installation is already in progress. Try again in a few minutes.                                                                                                     |
| `1730`     | The script was not run as an administrator.                                                                                                                                  |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://help.nightfall.ai/data-exfiltration-prevention/exfiltration_endpoint/install-nightfall-ai-agent-for-windows-os/nightfall-windows-agent-deployment-msi.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
