Xmaster1004
Xmaster1004

Reputation: 3

Powershell closing automatic when running .ps1 file

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

Upvotes: 0

Views: 639

Answers (2)

mklement0
mklement0

Reputation: 437688

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).

Upvotes: 0

GrowITSupport
GrowITSupport

Reputation: 136

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

Upvotes: 0

Related Questions