Troubleshooting

PowerShell Hardening: CLM, Execution Policies, and Script Signing

The Back Room Tech Staff · Edited by Aseem Kishore
18 min read

The Back Room Tech is reader-supported. We may earn a commission when you buy through links on our site. Learn more.

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.

ControlWhat it establishesMain limitation
Execution policyRules for loading scripts and configuration filesIt isn’t a security boundary
Script signingSigner details and integrity of signed contentsA valid signature doesn’t prove safety
Publisher trustWhether the endpoint trusts the signing publisherTrust doesn’t automatically authorize content under App Control
App ControlWhich content the Windows application-control policy allowsCompatibility and recovery need testing
Constrained Language ModeLimits on available PowerShell language featuresA 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.

Actual Windows PowerShell 5.1 read-only discovery showing PSVersion, PSEdition, PSHOME, effective execution policy, all policy scopes, and language mode

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.

Actual installed PowerShell 7 version and edition alongside effective execution policy, policy scopes, PSHOME, and language mode

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:

PriorityScopePolicy scope and where to resolve changes
1MachinePolicyGroup Policy for all users of the computer
2UserPolicyGroup Policy for the current user
3ProcessCurrent PowerShell session ($env:PSExecutionPolicyPreference)
4CurrentUserCurrent user’s local registry preference
5LocalMachineDefault 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.

Actual lab signature inspection showing Status, StatusMessage, and approved signer information with sensitive certificate details removed

Keep these three decisions separate:

DecisionQuestion it answers
Signature validationDo the signed contents pass signature and applicable certificate checks?
Publisher trustDoes this endpoint trust that signing publisher?
App Control authorizationDoes 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 Process row shows AllSigned.
  • Get-ExecutionPolicy reports AllSigned.

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:

BehaviorAllSignedRemoteSigned
Locally created scriptsRequires valid signaturesCan run unsigned
Scripts identified as internet downloadsRequires valid signaturesRequires valid signatures
Publisher prompts and trustSeparate certificate/trust behavior; varies by host, certificate state, and policy contextSeparate certificate/trust behavior for signed files; varies by host, certificate state, and policy context
Origin metadata dependencyLocal files also need valid signaturesDownload classification determines whether a signature is required
Operational costMore signing and release workLess 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 itemRecord before deployment
Target eligibilityWindows product, edition, build, and supported capabilities
Runtime coverageWindows PowerShell 5.1 and each installed PowerShell 7 version
Deployment mechanismApproved tool, required permissions, and exact deployment procedure
Policy identityPolicy identifier, version, and source artifact
Script enforcementConfirmed settings for the intended PowerShell behavior
Audit configurationHow the policy enters audit mode
Enforcement configurationHow the reviewed policy enters enforcement
RecoveryExact replacement or removal procedure for that policy type
Recovery accessConsole 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.

Actual verified runtime-specific audit event showing provider, timestamp, event identifier, and script or policy decision with sensitive paths removed

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.

WorkloadWhat to verify
Interactive administrationRequired commands work under the intended language restrictions
Scheduled tasksAccount, runtime path, publisher trust, and noninteractive behavior
Module loadingImports, dependencies, and exported functions
Dot-sourced scriptsCross-file behavior under policy
API-dependent scriptsRequired language operations and API access
Signed releasesSignature validation, publisher handling, and policy authorization
Policy-untrusted contentActual allow, constrain, or block decision
Emergency maintenanceRecovery 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.

Fresh lab session showing actual PowerShell version and observed language mode under the enforced policy, paired with separately confirmed policy identity

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 controlRecovery action
Process-scoped execution policyClose the test process
Persistent local execution policyRestore the recorded value at its original scope
Group Policy execution policyRestore through the original policy management system
Certificate trustReverse the specific trust deployment through its owner
App ControlUse the documented policy replacement or removal procedure
Script releaseRedeploy 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.

StepActionApplies To
DiscoverRecord versions, effective scopes, and language modeEvery runtime and execution account
SignValidate the artifact and publisher handlingApproved script releases
AuditReview events and workload compatibilityEach target policy and runtime
EnforceVerify fresh sessions and actual workload outcomesLab, then staged pilot
RecoverTest the control-specific recovery procedureEvery enforcement change