# OneDrive Health Check – ConnectWise Automate Deployment

## What it checks (per logged-on user)
| Check | Result if it fails |
|---|---|
| OneDrive.exe running in the user's session | FAIL |
| OneDrive for Business account signed in, sync folder exists | FAIL |
| Known Folder Move covers Desktop + Documents | WARN (FAIL with `-RequireKFM`) |
| Newest file change inside OneDrive older than `-StaleDays` (default 30) | WARN |
| Files saved to local Desktop/Documents outside OneDrive in the last 7 days | WARN |
| OneDrive running but no client log activity in 3+ days (hung client) | WARN |

Output line 1 is always `ODSTATUS=OK|WARN|FAIL|NOUSER|ERROR`. Exit code: 0 OK/NOUSER, 1 WARN, 2 FAIL, 3 ERROR. `ERROR` means the script itself hit an unexpected problem (the line says where); treat it like FAIL.

## Security / privacy notes
- Read-only. No downloads, network calls, credentials or secrets.
- Never outputs file names or paths of customer data — only timestamps.
- Outputs the signed-in account email for triage. Add `-MaskEmail` to show `j***@domain.com` instead.
- Reads file *metadata* only; online-only (Files On-Demand) files are never downloaded.

## Automate setup
1. **Script:** Automation → Scripts → New Script, name it `Bitswift - OneDrive Health Check`.
2. **Step 1 – run it:** add an *Execute Script* step (Script Type: PowerShell, run as Admin/SYSTEM), paste in `OneDriveHealthCheck.ps1`, and save the output to a variable, e.g. `ODResult`.
   - Parameters: **`-SingleLine -MaskEmail -WriteEventLog`**. `-SingleLine` is required when saving to an EDF: it prints one short line with no backslashes, quotes or line breaks, which Automate's SQL insert can handle. The full multi-line report still goes to the Windows Application event log.
   - Example output: `ODSTATUS=WARN | AzureAD/JRogan: KFM_OFF(Desktop,Documents) STALE_45d | Last=2026-09-05`
   - Issue codes: `NOT_RUNNING`, `NOT_SIGNED_IN`, `FOLDER_MISSING`, `KFM_OFF(..)`, `STALE_<n>d`, `EMPTY`, `SCAN_LIMIT`, `LOCAL_SAVES`, `HUNG_<n>d`, `NO_LOGS`, `NO_PROFILE`, `NET_REDIRECT(..)` (Desktop/Documents redirected to a network share)
   - If your Automate version only has the *Shell* function, use *File Write Text* to drop the script into `%windir%\LTSvc\scripts\OneDriveHealthCheck.ps1`, then run it with
     `%windir%\SysNative\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%windir%\LTSvc\scripts\OneDriveHealthCheck.ps1"`.
     The script also relaunches itself in 64-bit PowerShell automatically when it's started from a 32-bit host, but only when it runs from a file.
3. **Step 2 – store it:** set an Extra Data Field (e.g. `OneDrive Health`, computer level) to `@ODResult@`, so you can view and search it per machine.
4. **Step 3 – alert:**
   - `IF @ODResult@ contains ODSTATUS=FAIL` → create a ticket / alert (high priority).
   - `IF @ODResult@ contains ODSTATUS=ERROR` → create a ticket too: the check could not complete, so the machine is unverified.
   - `IF @ODResult@ contains ODSTATUS=WARN` → create a ticket / alert (normal priority), or just report on it.
   - `ODSTATUS=NOUSER` → do nothing (no one was logged on to check).
### Working script layout (tested)
Create the Extra Data Field first: **Tools → Extra Data Fields → Add**. Set Form: Computers, Name: `OneDrive Health`, Type: Text. Then run **Tools → Reload Cache**.

In the script editor, add rows with **right-click → Add**. Double-clicking an empty row does nothing. New rows go to the bottom, and you can use **Move Up/Down** to reorder them.

| # | Function | Settings |
|---|---|---|
| 1 | Execute Script (PowerShell) | Script To Execute: Text (paste the .ps1). Parameters: `-SingleLine -MaskEmail -WriteEventLog`. Run as Admin. Variable: `ODResult` |
| 2 | Extra Data Field Set | Extra Field: **OneDrive Health** (pick it from the dropdown). ID: `%computerid%`. Value: `@ODResult@` |
| 3 | Variable Check | `@ODResult@` **Contains** `ODSTATUS=FAIL` → Jump to `:Ticket Create` |
| 4 | Variable Check | `@ODResult@` **Contains** `ODSTATUS=ERROR` → Jump to `:Ticket Create` |
| 5 | Script Exit | |
| 6 | Label | `Ticket Create` (must match the jump target exactly) |
| 7 | Ticket Create | **Client ID: `%clientid%`. Computer ID: `%computerid%`** (client comes first). Email: your support mailbox. Subject: `OneDrive check - %computername%`. Body: `@ODResult@` |
| 8 | Script Exit | |

Common mistakes:
- In row 2, the ID field must be `%computerid%`, not the field name. Otherwise you get "SQL Execute failed processing query".
- In row 7, a blank Computer ID causes "Conversion from string "" to type Integer is not valid".
- A jump to a label that doesn't exist fails the script on the first FAIL.
- **Don't add percent-wrapped tokens (like `%name%`) to the script text if you edit it.** Before running a script, Automate replaces anything in that form with its own variables, even inside PowerShell code and comments. That broke version 2026-11-26b on some machines ("Unrecognized escape sequence" at line 150). The script now contains no `%` characters at all.

**Schedule:** run it daily during business hours (e.g. 11:00 AM, when users are logged in) against a search or group of client workstations that use OneDrive. Weekly is enough for the 30-day stale check, but daily catches "not running / signed out" quickly.

### Alternative: event log monitor
Run with `-WriteEventLog`, then point an Automate event log monitor at:
- Log: Application, Source: `BitswiftOneDriveMonitor`
- Event ID 3000 = FAIL (Error), 2000 = WARN (Warning), 1000 = OK (Information)

## Verify the download (SHA-256)
Current version: 2026-11-26c (fixes Automate variable substitution breaking the script on some machines; ODSTATUS=ERROR safety net; access-denied fix; NET_REDIRECT).

Before you run the script or paste it into Automate, check that its hash matches the published value.

| File | SHA-256 |
|---|---|
| `OneDriveHealthCheck.ps1` | `04ad2634931913dc6ab6cb59f0b6610b399a1693fc66dd15fbd1e45306015398` |

In PowerShell, from the folder holding the file:
```powershell
$expected = '04ad2634931913dc6ab6cb59f0b6610b399a1693fc66dd15fbd1e45306015398'
$actual   = (Get-FileHash .\OneDriveHealthCheck.ps1 -Algorithm SHA256).Hash
if ($actual -eq $expected) { 'OK - hash matches' } else { "MISMATCH - do not run. Got $actual" }
```
(`-eq` is case-insensitive, so the uppercase `Get-FileHash` output still compares correctly.)

Notes:
- The hash covers the exact bytes of the file as published (LF line endings). Opening and re-saving it in an editor that converts it to CRLF will change the hash. Verify first, then edit.
- Every new version of the script gets a new hash. This table and `SHA256SUMS.txt` are updated with each release.
- A hash proves the file wasn't altered or corrupted in transit, but only if you got the hash from a trusted place. If someone could change the file, they could change a hash sitting next to it too. Publish the hash somewhere separate (for example, your internal KB). For proof of *who* wrote the file, sign it with Authenticode (see below).

### Optional: Authenticode signing
Signing with a Bitswift code-signing certificate lets Windows verify the publisher itself, and it works on clients where Group Policy enforces `AllSigned`:
```powershell
$cert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Select-Object -First 1
Set-AuthenticodeSignature .\OneDriveHealthCheck.ps1 -Certificate $cert -TimestampServer 'http://timestamp.digicert.com' -HashAlgorithm SHA256
```
Signing adds a signature block to the file, so recompute the SHA-256 after signing and publish that value. The private key stays in your certificate store or HSM. Never commit or distribute it.

## Test first
On a test machine, while a user is logged in, run in an elevated PowerShell:
```
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\OneDriveHealthCheck.ps1 -MaskEmail
```
Add `-SingleLine` to see the compact EDF version. Then sign out of OneDrive (or quit it) and run it again. You should see `ODSTATUS=FAIL`.

## Known limits
- Only checks users who are logged on when it runs (explorer.exe running). Machines with nobody logged in report `NOUSER`.
- It can't see OneDrive's internal "paused" or "sign-in required" state directly. Those cases show up as a stale-data or hung-heartbeat WARN instead.
- Very large libraries are scanned up to 250,000 files / 180 s total. A partial scan is labelled `(partial scan)` and won't raise a false "stale" alarm.
- An inactive user (on vacation, in a role that rarely saves files) will trigger the 30-day stale WARN. That's expected, so treat it as "check with the user."
