0

I'm trying to create this .ps1 file: see the full .ps1 markup

# Definieer het pad waar de bestanden worden gekopieerd
$sourcePath = "C:\Users\Mr.Fox\AppData\Local\Hogwarts Legacy\Saved"

# Definieer het pad waar de bestanden naartoe worden gekopieerd
$destinationPath = "D:\Games\Saved HL"

# Zoek naar de laatst gebruikte mapnummer
$latestFolder = Get-ChildItem $destinationPath | Where-Object { $_.PSIsContainer } | Sort-Object { [int]($_.Name -replace '^\D+') } -Descending | Select-Object -First 1
if ($latestFolder -eq $null) {
    $folderNumber = 1
} else {
    $folderNumber = [int]($latestFolder.Name -replace '^\D+') + 1
}

# Maak de nieuwe doelmap aan
$newFolderName = "Backup_$("{0:D2}" -f $folderNumber)"
$newFolderPath = Join-Path $destinationPath $newFolderName
if (-not (Test-Path $newFolderPath)) {
    New-Item -ItemType Directory -Path $newFolderPath | Out-Null
}

# Voeg uitvoer toe aan het logbestand
$logFile = Join-Path $destinationPath "backuplog.txt"
$date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "$date - Backup gemaakt naar map $newFolderPath"
Add-Content $logFile $logEntry

# Vraag de gebruiker om bevestiging voordat het script wordt uitgevoerd
$confirm = Read-Host "Weet je zeker dat je het script wilt uitvoeren? Typ 'ja' om door te gaan."
Write-Host "Bevestiging: $confirm"

if ($confirm -eq "ja") {
    # Kopieer de bestanden van de bron naar de nieuwe doelmap
    Copy-Item $sourcePath $newFolderPath -Recurse -Force

    Write-Host "Het backupproces is voltooid en de uitvoer is toegevoegd aan het logbestand."
} else {
    Write-Host "Script uitvoering geannuleerd."
}

# Zet de PowerShell uitvoeringsbeleid terug naar de oorspronkelijke instelling
if ((Get-ExecutionPolicy -Scope CurrentUser) -eq "RemoteSigned") {
    Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Restricted
}

Read-Host "Druk op een toets om door te gaan..."

Then I try to click run with PowerShell, but it closes on me and what Get-ExecutionPolicy -List is telling me is that the current user's policy is Restricted, but when I try to enable it, it just goes back to Restricted, and I don't know why.

Can you help me out?

PS C:\WINDOWS\system32> Get-ExecutionPolicy -List

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser      Restricted
 LocalMachine    RemoteSigned

I try to search online for a solution but didn't get very; I tried: https://stackoverflow.com/a/27755459

still the same problem

I get this response back when running Set-ExecutionPolicy Unrestricted

Execution Policy Change The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): y Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of Restricted. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more information ple ase see "Get-Help Set-ExecutionPolicy". At line:1 char:1

  • Set-ExecutionPolicy Unrestricted
  • + CategoryInfo          : PermissionDenied: (:) [Set-ExecutionPolicy], >SecurityException
    + FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
    

in regedit standard has no value but 'ExecutionPolicy' is already to Unrestricted though but still i cant run the script

TylerH
  • 20,799
  • 66
  • 75
  • 101

2 Answers2

0

Set execution policy to LocalMachine scope to Unrestricted. This scope is more important than the current user.

Set-ExecutionPolicy Unrestricted 
# by default its set to LocalMachine scope
  • @GrowITSupport this is what comes up i opened PowerShell as admin see the new awnser i made above – Xmaster1004 Feb 27 '23 at 07:18
  • Open regedit and go to `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell` (instead of 1 there may also be another number, check under each). Find 'ExecutionPolicy' key and change value to "Unrestricted". – GrowITSupport Feb 27 '23 at 10:43
  • @GrowITSupport standard has no value but `'ExecutionPolicy' is already to to Unrestricted` – Xmaster1004 Feb 27 '23 at 13:55
  • And if you set `Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unestricted` then this scope back to Restricted? Is your computer on a domain? – GrowITSupport Feb 27 '23 at 14:04
  • A policy set in the `CurrentUser` scope takes precedence over one in the `LocalMachine` scope. `Get-ExecutionPolicy -List` lists the scopes in order of precedence. – mklement0 Jul 24 '23 at 21:52
0

tl;dr

  • Remove the following from your script, given that it explicitly reverts the current user's execution policy to Restricted, preventing future execution of scripts:

    if ((Get-ExecutionPolicy -Scope CurrentUser) -eq "RemoteSigned") {
        Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Restricted
    }
    
    • Note that if your script is invoked with a process scoped execution policy - namely via the CLI's -ExecutionPolicy parameter (e.g. powershell.exe -ExecutionPolicy Bypass ...), which is the equivalent of -Scope Process - such a policy by definition applies to that process only, so you needn't worry about restoring any persistently defined policies.
  • Then open a PowerShell window and execute the following, which - given what your Get-ExecutionPolicy -List output shows - will change the effective execution policy for your user account to RemoteSigned, which permits script execution, except for scripts downloaded from the web:

Set-ExecutionPolicy -Scope CurrentUser Undefined -Force

Read on for an explanation and alternatives.


Background info:

PowerShell's execution policies can be defined in multiple scopes, but only one scope's policy is the effective one in a given session.

  • Get-ExecutionPolicy without arguments lists the effective policy.

  • Get-ExecutionPolicy -List lists the policies defined for all scopes, in descending order of precedence:

    • That is, the first scope that has a value other than Undefined is also the effective one.
    • If no execution policy has ever been set, in any scope, the built-in defaults apply: Restricted (meaning that execution of script is disallowed) in desktop editions of Windows, and RemoteSigned in server editions.

Your Get-ExecutionPolicy -List shows that Restricted is defined in the CurrentUser scope (specific to the current user), and RemoteSigned in the LocalMachine scope.

Therefore, Restricted is the effective policy for you, preventing script execution.

You have three options, depending on your needs:

  • If the LocalMachine-scope policy, RemoteSigned, works for you (it allows execution of script originating on the local file-system or network shares, but blocks script downloaded via a web browser, email client, or messenger application):

    • Simply undefine the CurrentUser policy, which then makes the LocalMachine policy take effect:

      Set-ExecutionPolicy -Scope CurrentUser Undefined -Force
      
  • If you want to retain a current-user policy but change it to allow script execution, run something like the following, specifying the desired policy (RemoteSigned in this example):

      Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force
    

If you additionally want to change the LocalMachine-scope policy, you'll need to do so from an elevated session (run as adminstrator).

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • @Xmaster1004. Yes, you can run it via Task Scheduler, and the most robust way to do that is to use a _process_-scoped execution policy that overrides whichever one is _persistently_ in effect, _for the given call only_, which is what the `-ExecutionPolicy` CLI parameter does (e.g., `powershell.exe -ExecutionPolicy Bypass -File ...`) – mklement0 Feb 27 '23 at 16:40
  • More detailed procces on how to do this with task Scheduler cuz i'm lost i cant get it to wok for some reason – Xmaster1004 Feb 28 '23 at 10:42
  • @Xmaster1004, [this answer](https://stackoverflow.com/a/75089634/45375) has sample code that sets up a scheduled task that calls PowerShell. If that doesn't help, I encourage you to ask a new question. – mklement0 Feb 28 '23 at 15:17