Powershell在运行.ps1文件时自动关闭

huangapple go评论59阅读模式
英文:

Powershell closing automatic when running .ps1 file

问题

抱歉,以下是您提供的.ps1文件的部分翻译,不包括代码部分:

# 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..."

关于你在PowerShell执行策略的问题,你提到的策略已经在“Restricted”状态。在执行 Set-ExecutionPolicy Unrestricted 时,你收到了警告,提示有更特定范围的策略覆盖了全局策略。这可能是因为你的计算机上有其他策略设置。

为了解决这个问题,你可以尝试以下步骤:

  1. 以管理员身份打开 PowerShell。
  2. 运行 Get-ExecutionPolicy -List 以查看所有范围的执行策略。

看一下哪个范围的执行策略被设置为 "Restricted",然后尝试在该范围中运行 Set-ExecutionPolicy Unrestricted 以更改策略。

请确保在管理员权限下运行 PowerShell 来更改执行策略。如果仍然遇到问题,可能需要检查计算机上的策略设置,确保没有其他策略覆盖了全局策略。

英文:

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

答案1

得分: 0

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

设置执行策略为LocalMachine范围为Unrestricted。此范围比当前用户更重要。

Set-ExecutionPolicy Unrestricted
# 默认情况下,它设置为LocalMachine范围
英文:

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

答案2

得分: 0

不要有别的内容,只返回翻译好的部分:

  1. tl;dr

    • 从您的脚本中 移除 以下内容,因为它明确将当前用户的执行策略还原为 Restricted,从而阻止将来执行脚本:

      如果 ((Get-ExecutionPolicy -Scope CurrentUser) -eq "RemoteSigned") {
      Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Restricted
      }

    • 请注意,如果通过 CLI 的 -ExecutionPolicy 参数(例如 powershell.exe -ExecutionPolicy Bypass ...)调用您的脚本,它将使用 进程 范围的执行策略(即 -Scope Process),这等效于 仅适用于该进程 的策略,因此无需担心还原任何 持久性 定义的策略。

    • 然后打开 PowerShell 窗口并执行以下命令,根据您的 Get-ExecutionPolicy -List 输出显示的内容,这将更改您的用户帐户的有效执行策略为 RemoteSigned,允许执行脚本,但不允许执行从网络下载的脚本:

    Set-ExecutionPolicy -Scope CurrentUser Undefined -Force
    

    请继续阅读以了解解释和替代方案。

  2. Background info:

    PowerShell 的 执行策略 可以在 多个范围 中定义,但在给定会话中只有一个范围的策略是 有效 的。

    • Get-ExecutionPolicy 无需参数 会列出 有效 策略。

    • Get-ExecutionPolicy -List 会列出 所有 范围中定义的策略,按 优先级降序 排列:

      • 也就是说,第一个具有非 Undefined 值的范围也是有效的。
      • 如果 任何 范围中从未设置执行策略,内置默认策略适用于 桌面 版本的 Windows,策略为 Restricted(表示 禁止 执行脚本),以及 服务器 版本中的 RemoteSigned

    您的 Get-ExecutionPolicy -List 显示 RestrictedCurrentUser 范围(特定于当前用户),以及 RemoteSignedLocalMachine 范围中定义。

    因此,对您来说,Restricted有效 的策略,阻止脚本执行。

    根据您的需求,您有三种选项:

    • 如果 LocalMachine 范围的策略 RemoteSigned 对您有效(它允许执行源自本地文件系统或网络共享的脚本,但会阻止通过网络浏览器、电子邮件客户端或消息应用程序下载的脚本):

      • 简单地 取消定义 CurrentUser 策略,这将使 LocalMachine 策略生效:

        Set-ExecutionPolicy -Scope CurrentUser Undefined -Force

    • 如果您想保留当前用户策略但更改以允许执行脚本,运行类似以下内容的命令,指定所需的策略(在此示例中为 RemoteSigned):

      Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force

    如果还要更改 LocalMachine 范围的策略,您需要从 以管理员身份运行的 会话中执行此操作。

英文:

<!-- language-all: sh -->

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 &quot;RemoteSigned&quot;) {
        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).

huangapple
  • 本文由 发表于 2023年2月27日 05:22:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定