PowerShell hardening gives you repeatable checks for script loading, signer trust, and Windows application control. Check Windows PowerShell 5.1 and each installed PowerShell 7 runtime before changing settings.
Execution policy checks script loading. Signatures identify signers and help detect changed contents. App Control for Business enforces application rules, including PowerShell language limits. Start with read-only checks, test signing in a separate lab, and prove recovery before enforcement. There’s some paperwork. Keep it with the policy.
Execution-policy enforcement only happens on Windows. On Linux and macOS, PowerShell reports Unrestricted, the policy can’t be changed, and the checks in this guide don’t provide an equivalent control there. On Linux, rely on file permissions, controlled install sources, and your distribution’s own integrity or application-control tooling instead.
| Control | What it establishes | Main limitation |
|---|---|---|
| Execution policy | Rules for loading scripts and configuration files | It isn’t a security boundary |
| Script signing | Signer details and integrity of signed contents | A valid signature doesn’t prove safety |
| Publisher trust | Whether the endpoint trusts the signing publisher | Trust doesn’t automatically authorize content under App Control |
| App Control | Which content the Windows application-control policy allows | Compatibility and recovery need testing |
| Constrained Language Mode | Limits on available PowerShell language features | A manual session setting doesn’t enforce rules system-wide |
Microsoft explains these distinctions in its PowerShell security overview.
Check the Windows prerequisites for PowerShell security hardening
1. Inventory Windows and the running PowerShell session
Run these commands in your existing admin session. Use the account you’re checking. These checks don’t change policy.
Get-CimInstance -ClassName Win32_OperatingSystem |
Format-List Caption, Version, BuildNumber, OSArchitecture
$PSVersionTable
$PSHOME
Get-ExecutionPolicy
Get-ExecutionPolicy -List
$ExecutionContext.SessionState.LanguageMode
Record:
- The Windows product, build, and architecture.
- The PowerShell version, edition, and install directory.
- The effective execution policy.
- Every execution-policy scope.
- The session’s language mode.
Windows PowerShell 5.1 normally reports Desktop as its edition. PowerShell 7 normally reports Core. Record the actual version and compare it with Microsoft’s PowerShell support lifecycle to confirm the release is still supported. A version in a documentation URL doesn’t tell you which release you’re running.
An ordinary session without lockdown reports FullLanguage. Profiles, session configurations, AppLocker, and App Control can change that result. Check why a session reports ConstrainedLanguage, but don’t judge the full application-control setup from that value alone.
Check your Windows and PowerShell versions against Microsoft’s PowerShell support lifecycle. Windows PowerShell 5.1 follows Windows servicing. PowerShell 7 has a separate lifecycle.
2. Repeat discovery inside PowerShell 7
If PowerShell 7 is installed and on your command path, open a separate session:
pwsh.exe -NoProfile
-NoProfile skips profile scripts. That gives you a cleaner comparison without changing execution policy.
Inside that session, run:
$PSVersionTable
$PSHOME
Get-ExecutionPolicy
Get-ExecutionPolicy -List
$ExecutionContext.SessionState.LanguageMode
Expected result: the version table shows the installed PowerShell 7 version and the Core edition.
If pwsh.exe isn’t found, record that result. Don’t install another runtime on production just to complete the comparison. Use your approved software deployment process to prepare the required, supported runtime in the lab.
Repeat these checks where real work runs. An interactive admin session doesn’t show what a scheduled task or service account sees.
3. Identify the execution-policy scope that wins
These scope checks apply to Windows. On non-Windows systems, Get-ExecutionPolicy returns Unrestricted and Set-ExecutionPolicy isn’t supported.
Get-ExecutionPolicy -List displays scopes in precedence order, from highest to lowest:
| Priority | Scope | Policy scope and where to resolve changes |
|---|---|---|
| 1 | MachinePolicy | Group Policy for all users of the computer |
| 2 | UserPolicy | Group Policy for the current user |
| 3 | Process | Current PowerShell session ($env:PSExecutionPolicyPreference) |
| 4 | CurrentUser | Current user’s local registry preference |
| 5 | LocalMachine | Default local registry scope for all users of the computer |
The highest-precedence configured (non-Undefined) scope wins. PowerShell doesn’t choose the most restrictive value across all scopes.
When Group Policy scopes (MachinePolicy and UserPolicy) aren’t configured, Process has the highest precedence, followed by CurrentUser and then LocalMachine. Group Policy settings, when present, override those local and session scopes.
For example, this is illustrative output, not a captured machine:
Scope ExecutionPolicy
----- ---------------
MachinePolicy AllSigned
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine Undefined
With exactly these scope values and no other process override, the effective result is:
AllSigned
A Process, CurrentUser, or LocalMachine change can’t override that MachinePolicy value. An elevated shell doesn’t change precedence.
Use the actual effective result rather than assuming a Windows default. Microsoft’s execution-policy documentation explains scopes and precedence.
Execution policy helps prevent unintended script loading. It doesn’t stop a determined user from running code, so it provides no security boundary.
4. Inspect an existing script without executing it
Choose a script that reflects normal admin work. Enter its full path when prompted:
$scriptPath = Read-Host 'Enter the full path to an existing PowerShell script'
Get-AuthenticodeSignature -FilePath $scriptPath |
Format-List Status, StatusMessage, SignerCertificate
Get-Item -LiteralPath $scriptPath -Stream *
The first command reports signature status and signer details. An unsigned script reports NotSigned.
The second command lists NTFS alternate data streams, such as Zone.Identifier. It’s Windows/NTFS-specific and won’t show origin metadata on other filesystems. Review any origin metadata without removing it.
A signature error, an untrusted publisher, and internet-origin metadata describe different conditions. Keep them separate in your notes.
Prepare an isolated Windows lab before changing trust or policy
5. Create the lab and establish recovery access
Prepare a disposable Windows machine through your organization’s approved VM or lab setup process. Match the production Windows build and required PowerShell runtimes where practical.
Before signing, changing certificate trust, or applying policy:
- Keep production credentials and signing keys out of the disposable image.
- Copy scripts and modules that reflect real workloads into the lab through an approved transfer process.
- Record the runtime and policy details from Steps 1–3.
- Create a baseline you can restore using the lab platform’s documented process.
- Test console or recovery access without relying on PowerShell remoting.
- Assign an admin who can restore the lab if application control blocks normal access.
A VM snapshot helps with isolated tests. Production recovery still needs its own procedure.
If the lab runs on a local VM host, a UPS helps protect that host during testing. Store exported evidence on your managed backup target or NAS drive. Don’t leave the only copy inside the disposable VM.
Expected result: you can restore the lab and reach its console before any hardening change occurs.
6. Create a harmless local test script
In the lab, create a small script that shows its runtime and language mode:
$labDirectory = Join-Path $env:USERPROFILE 'PowerShellHardeningLab'
New-Item -Path $labDirectory -ItemType Directory -Force | Out-Null
$samplePath = Join-Path $labDirectory 'Get-HardeningState.ps1'
@'
Write-Output 'PowerShell hardening lab sample'
$PSVersionTable
$ExecutionContext.SessionState.LanguageMode
'@ | Set-Content -LiteralPath $samplePath -Encoding UTF8
Get-AuthenticodeSignature -FilePath $samplePath |
Format-List Status, StatusMessage, SignerCertificate
Expected signature status before signing:
Status : NotSigned
Don’t run the file yet. Its path and contents are now fixed for the signing exercise.
This sample checks basic execution and reports context. It doesn’t test every language restriction or replace workload compatibility tests.
Sign and validate a PowerShell script in the lab
7. Verify the certificate prerequisites
Use a code-signing certificate chosen through your approved certificate process.
Before continuing, confirm:
- The certificate belongs to the intended signing identity.
- Its intended use includes code signing.
- The signing environment can access its private key.
- Its validity period and chain meet your organization’s requirements.
- The lab endpoints have the required chain trust.
- Publisher trust has been considered separately.
- Key protection, renewal, revocation, and timestamping have assigned owners.
For enterprise distribution, use your certificate team’s approved signing and timestamping workflow. The exercise below shows signing mechanics without a timestamp service.
Protect the production key through an approved signing service, hardware security module, or supported hardware token. The trade-off is extra setup and recovery work.
8. Select the exact certificate by thumbprint
Select the certificate in the lab’s signing session. This example expects the approved certificate in the current user’s Personal store.
First, inspect the available code-signing certificates:
Get-ChildItem -Path Cert:\CurrentUser\My -CodeSigningCert |
Format-List Subject, Thumbprint, NotBefore, NotAfter, HasPrivateKey
Compare the certificate with the identity supplied by your certificate admin. Then enter its thumbprint:
$thumbprint = Read-Host 'Enter the approved code-signing certificate thumbprint'
$certificate = Get-Item -LiteralPath "Cert:\CurrentUser\My\$thumbprint"
$certificate |
Format-List Subject, Thumbprint, NotBefore, NotAfter, HasPrivateKey
Expected result: the subject and thumbprint match the approved certificate, and HasPrivateKey is True.
Stop if the certificate doesn’t match. Don’t select an arbitrary first certificate from the store.
If your organization uses another store or a managed signing service, follow that approved procedure. Keep the production key out of this lab.
9. Sign the sample and inspect the result
Use the same session where $certificate contains the selected certificate:
$samplePath = Join-Path $env:USERPROFILE 'PowerShellHardeningLab\Get-HardeningState.ps1'
Set-AuthenticodeSignature -FilePath $samplePath -Certificate $certificate
Get-AuthenticodeSignature -FilePath $samplePath |
Format-List Status, StatusMessage, SignerCertificate
The target result is Valid, with the expected signer certificate. Valid also depends on certificate validity, chain trust, and revocation checks. It confirms the signer and unchanged contents, not that the script is safe.
If the check reports another status, resolve that condition before execution. A completed signing command alone doesn’t prove the signature is valid.
Keep these three decisions separate:
| Decision | Question it answers |
|---|---|
| Signature validation | Do the signed contents pass signature and applicable certificate checks? |
| Publisher trust | Does this endpoint trust that signing publisher? |
| App Control authorization | Does the deployed application-control policy allow this content? |
A valid signature doesn’t prove the script is harmless. A trusted publisher doesn’t automatically gain permission under every App Control policy.
Microsoft explains policy-controlled trust in Use App Control to secure PowerShell.
10. Test integrity checking on a separate copy
Preserve the signed original. Modify a disposable copy:
$samplePath = Join-Path $env:USERPROFILE 'PowerShellHardeningLab\Get-HardeningState.ps1'
$changedPath = Join-Path $env:USERPROFILE 'PowerShellHardeningLab\Get-HardeningState-Changed.ps1'
Copy-Item -LiteralPath $samplePath -Destination $changedPath
Add-Content -LiteralPath $changedPath -Value '# Lab integrity check'
Get-AuthenticodeSignature -FilePath $changedPath |
Format-List Status, StatusMessage, SignerCertificate
Expected result: the changed copy no longer validates as the unchanged signed file. Inspect the actual status and message.
Don’t execute that copy. This exercise checks whether signed contents changed. It doesn’t assess malicious code.
Test AllSigned without creating a persistent local policy
11. Apply AllSigned to one lab process
Open a fresh lab session in the runtime you’re testing. Record its starting state, then set the process scope:
Get-ExecutionPolicy
Get-ExecutionPolicy -List
Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope Process
Get-ExecutionPolicy
Get-ExecutionPolicy -List
Read the confirmation prompt before accepting it.
Expected result, when Group Policy doesn’t override it:
- The
Processrow showsAllSigned. Get-ExecutionPolicyreportsAllSigned.
A Group Policy setting can prevent the process preference from taking effect. If that happens, record the winning scope. Resolve the lab setup through its policy owner.
The process setting ends when this PowerShell process closes. It doesn’t change centrally managed policy or App Control.
12. Execute the unchanged signed sample
Recreate the file path in this fresh session and execute the signed original:
$samplePath = Join-Path $env:USERPROFILE 'PowerShellHardeningLab\Get-HardeningState.ps1'
Get-AuthenticodeSignature -FilePath $samplePath |
Format-List Status, StatusMessage, SignerCertificate
& $samplePath
The & call operator executes the script at the supplied path.
When the effective policy, signature, publisher trust, and other controls permit execution, the sample prints:
PowerShell hardening lab sample
It then displays the actual runtime table and language mode.
Depending on file origin, host, certificate state, and policy, you may see a publisher prompt. It means the endpoint hasn’t already classified that publisher as required for this run. Verify the signer and use your enterprise publisher-trust process. Don’t make unattended jobs depend on a prompt.
13. Compare AllSigned with RemoteSigned
Use the policy requirements to choose your enterprise target:
| Behavior | AllSigned | RemoteSigned |
|---|---|---|
| Locally created scripts | Requires valid signatures | Can run unsigned |
| Scripts identified as internet downloads | Requires valid signatures | Requires valid signatures |
| Publisher prompts and trust | Separate certificate/trust behavior; varies by host, certificate state, and policy context | Separate certificate/trust behavior for signed files; varies by host, certificate state, and policy context |
| Origin metadata dependency | Local files also need valid signatures | Download classification determines whether a signature is required |
| Operational cost | More signing and release work | Less friction for local development |
This table summarizes the signature requirement only. Zone metadata and trust handling can have additional host-specific effects. Both policies determine whether valid signatures are required to load scripts and configuration files. Neither policy decides whether signed behavior is safe.
Publisher prompts and trust configuration are separate certificate and trust behaviors, not a uniform requirement of either execution policy. Verify how publisher prompts and trust behave in your target runtime and automation context before configuring broad publisher trust.
I’d use AllSigned only when signing can support routine maintenance, emergency changes, and unattended automation. Otherwise, admins inherit a queue where a working release process should be.
Review the exact behavior in Microsoft’s execution-policy reference.
Prepare App Control for enforced Constrained Language Mode
14. Complete the target-specific deployment and recovery record
App Control deployment depends on the Windows target, policy format, management system, and policy protection settings. Follow the deployment guidance linked from Microsoft’s PowerShell application-control documentation. Choose the procedure for your environment.
Before applying a lab policy, fill in this record:
| Required item | Record before deployment |
|---|---|
| Target eligibility | Windows product, edition, build, and supported capabilities |
| Runtime coverage | Windows PowerShell 5.1 and each installed PowerShell 7 version |
| Deployment mechanism | Approved tool, required permissions, and exact deployment procedure |
| Policy identity | Policy identifier, version, and source artifact |
| Script enforcement | Confirmed settings for the intended PowerShell behavior |
| Audit configuration | How the policy enters audit mode |
| Enforcement configuration | How the reviewed policy enters enforcement |
| Recovery | Exact replacement or removal procedure for that policy type |
| Recovery access | Console access, required credentials, and protected recovery material |
Have the policy owner supply the exact deployment and recovery commands. Test those commands on the disposable machine before using them in a pilot.
Don’t proceed until you’ve proved the policy’s recovery procedure works. Recovery from a signed policy can need different preparation from replacing an ordinary configuration file.
Microsoft recommends App Control for new application-control work. Existing AppLocker deployments need their own assessment. Don’t silently replace their rules during this exercise.
15. Deploy audit mode and collect runtime-specific evidence
Apply the approved audit policy through the deployment procedure recorded in Step 14. Confirm its identity and audit state through that management tool.
Next, discover the available event channels:
Get-WinEvent -ListLog '*PowerShell*' |
Format-Table LogName, IsEnabled, RecordCount -AutoSize
Get-WinEvent -ListLog '*CodeIntegrity*' |
Format-Table LogName, IsEnabled, RecordCount -AutoSize
These commands list channels. They don’t enable logging or establish what an event means.
For each runtime, verify the relevant PowerShell, application-control, and restriction-event sources. Set up collection through your approved logging process.
Once you’ve confirmed a relevant channel and what its events mean, inspect recent entries:
$logName = Read-Host 'Enter the verified event log channel name'
Get-WinEvent -FilterHashtable @{
LogName = $logName
StartTime = (Get-Date).AddMinutes(-30)
} -MaxEvents 50 |
Format-List TimeCreated, ProviderName, Id, Message
Expected result: available events include their provider, timestamp, identifier, and message. Investigate an empty result. It doesn’t prove compatibility.
PowerShell 7.4 and later provides App Control audit-mode diagnostics and logs would-be restriction information for applicable policy decisions. Exact behavior depends on the policy mode, script context, enforcement configuration, and whether the relevant event channel is enabled.
Distinguish an App Control policy audit run from ordinary Constrained Language Mode execution, and don’t apply PowerShell 7.4+ audit expectations to Windows PowerShell 5.1. Verify the exact policy mode, runtime, event source, and behavior for each workload, because a successful audit-mode run can still reveal failures that enforcement would cause.
16. Run a separate compatibility matrix for each runtime
Run workloads that reflect real use, under their actual accounts and launch methods.
| Workload | What to verify |
|---|---|
| Interactive administration | Required commands work under the intended language restrictions |
| Scheduled tasks | Account, runtime path, publisher trust, and noninteractive behavior |
| Module loading | Imports, dependencies, and exported functions |
| Dot-sourced scripts | Cross-file behavior under policy |
| API-dependent scripts | Required language operations and API access |
| Signed releases | Signature validation, publisher handling, and policy authorization |
| Policy-untrusted content | Actual allow, constrain, or block decision |
| Emergency maintenance | Recovery tools remain available |
For each test, record the runtime version, account, script version, policy identity, result, and related events.
Windows PowerShell 5.1 and PowerShell 7 need separate rows. PowerShell 7 also has version-specific application-control integration, so test each installed 7.x release separately rather than assuming one row covers them all.
Don’t assume every unapproved file will run under CLM. The runtime and policy decision can cause execution to be blocked.
Verify enforcement in fresh PowerShell sessions
17. Enforce the reviewed policy in the disposable lab
Resolve audit findings first. Then apply the reviewed enforcement policy using the recorded deployment procedure.
Warning: Application-control enforcement can interrupt administration and automation. Complete the lab recovery test before expanding deployment.
Complete any restart required by that procedure. Open fresh sessions in each runtime and run:
$PSVersionTable
Get-ExecutionPolicy
Get-ExecutionPolicy -List
$ExecutionContext.SessionState.LanguageMode
For a normal interactive session under enforced App Control script restrictions, the expected language-mode result is:
ConstrainedLanguage
That result depends on the deployed policy, lockdown state, script-enforcement options, and session context. Policy-approved scripts can still run in FullLanguage, and untrusted content may be blocked outright rather than constrained. A session result alone doesn’t prove the policy handles your workloads correctly, so check it alongside the deployed policy’s identity, enforcement state, and relevant events.
Run the workload matrix again. Check both behavior and logs.
Scripts and modules trusted by the application-control policy can receive FullLanguage treatment. Signing a script doesn’t automatically grant that permission. The allow decision depends on the policy’s rules, such as publisher or hash conditions, its policy options, and the runtime context, not on the certificate alone.
A standalone assignment to LanguageMode only changes the affected session context. It doesn’t enforce lasting application control across new sessions and runspaces. Microsoft’s language-mode documentation explains the distinction.
18. Prove recovery before starting a pilot
Test the documented recovery procedure on the lab machine.
Then open fresh sessions and repeat:
$PSVersionTable
Get-ExecutionPolicy
Get-ExecutionPolicy -List
$ExecutionContext.SessionState.LanguageMode
Run the required maintenance workloads again. Compare the results with the baseline.
Recovery must match the changed control:
| Changed control | Recovery action |
|---|---|
| Process-scoped execution policy | Close the test process |
| Persistent local execution policy | Restore the recorded value at its original scope |
| Group Policy execution policy | Restore through the original policy management system |
| Certificate trust | Reverse the specific trust deployment through its owner |
| App Control | Use the documented policy replacement or removal procedure |
| Script release | Redeploy the approved artifact and revalidate its signature |
Set-ExecutionPolicy can’t reverse App Control enforcement.
Start the production pilot only after lab enforcement and recovery pass. Use a small group that reflects your workloads. Review its evidence, then expand through your normal change process.
Fix common PowerShell hardening failures
19. Resolve “execution policy is overridden” at the winning scope
Run these commands in the affected runtime and account:
Get-ExecutionPolicy
Get-ExecutionPolicy -List
Find the highest-precedence configured scope. If MachinePolicy or UserPolicy supplies the value, resolve it through Group Policy management.
Repeated local changes won’t override the centrally managed setting.
20. Fix a local script rejected under AllSigned
Inspect the rejected file:
$scriptPath = Read-Host 'Enter the full path to the rejected script'
Get-AuthenticodeSignature -FilePath $scriptPath |
Format-List Status, StatusMessage, SignerCertificate
If it reports NotSigned, submit it through the approved signing workflow. If validation fails, restore or rebuild the approved artifact and investigate the signature status.
AllSigned includes locally created scripts. Don’t weaken policy as the routine repair.
21. Resolve a publisher prompt before scheduling the job
Inspect the signer with the command from Step 20. Compare it with the approved publisher identity.
Have the certificate or endpoint management owner apply the required publisher-trust settings. Then rerun the script using the actual automation account.
Expected result: the approved job completes without an interactive publisher decision.
22. Investigate a signed script that fails under CLM
Check the affected session:
$PSVersionTable
$ExecutionContext.SessionState.LanguageMode
Then match the failure with the verified policy and restriction logs.
Reproduce it using the same runtime, account, module versions, and policy. Adapt the script to permitted operations or submit a narrowly scoped permission change for review.
A valid signature alone doesn’t justify broader language access.
23. Investigate audit success followed by enforcement failure
Compare the audit events with the enforcement error and policy decision.
For PowerShell 7.4 and later, inspect logged audit-mode restriction diagnostics for applicable policy decisions even when the audit run completed successfully. For Windows PowerShell 5.1, use its separately established test expectations.
Return the policy change to the lab workflow. Expand deployment only after you’ve resolved the enforcement failure and confirmed recovery still works.
Add JEA when administrators need delegated commands
24. Identify tasks that need a restricted endpoint
Keep delegated endpoint administration separate from system-wide App Control and Constrained Language Mode. App Control and CLM govern script execution and language restrictions across hosts, whereas Just Enough Administration (JEA) scopes a specific remoting endpoint to approved commands for delegated tasks.
Microsoft documents restricted JEA configurations as using NoLanguage mode, which restricts sessions to command invocations rather than general scripting. Use a dedicated JEA delegation guide for endpoint setup alongside the official language-mode reference when assessing that boundary.
Wrapping Up
Keep the runtime inventory, policy artifact, signing identity, and recovery procedure together. I’d include that evidence in each release approval. It helps limit configuration drift and makes failures easier to trace.
| Step | Action | Applies To |
|---|---|---|
| Discover | Record versions, effective scopes, and language mode | Every runtime and execution account |
| Sign | Validate the artifact and publisher handling | Approved script releases |
| Audit | Review events and workload compatibility | Each target policy and runtime |
| Enforce | Verify fresh sessions and actual workload outcomes | Lab, then staged pilot |
| Recover | Test the control-specific recovery procedure | Every enforcement change |