确定是否已从桌面或命令行运行 PowerShell 脚本

Rob*_*son 7 powershell

Windows 资源管理器(桌面)可以通过右键单击并选择“使用 PowerShell 运行”来运行 PowerShell 脚本。但是,由于脚本完成后窗口关闭,因此所有消息都将丢失。所以人们可以在最后贴上“按任意键”。但是,当从 PowerShell 命令提示符运行时,这会很烦人。

PowerShell 有没有办法确定它是从哪里运行的?具体来说,桌面?

Jos*_*efZ 6

使用PowerShell运行小号$myinvocation.line从相应的注册表键拍摄。例如,在(我的)Windows 8.1PS 版本 5.1 上

PS D:\PShell> $auxRegKey='\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\0\Command'
PS D:\PShell> (get-itemproperty -literalpath HKLM:$auxRegKey).'(default)'
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
PS D:\PShell>
Run Code Online (Sandbox Code Playgroud)

以下代码片段可能会有所帮助:

'script ouput here'
$auxRegKey='\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\0\Command'
$auxRegVal=(get-itemproperty -literalpath HKLM:$auxRegKey).'(default)'
$auxRegCmd=$auxRegVal.Split(' ',3)[2].Replace('%1', $MyInvocation.MyCommand.Definition)
if ("`"$($myinvocation.Line)`"" -eq $auxRegCmd) {
    $MyInvocation.MyCommand.Definition + ': supposedly run via explorer right click'
    $x = Read-Host
} else {
    $MyInvocation.MyCommand.Definition + ': run from CLI'    # optional
}
Run Code Online (Sandbox Code Playgroud)

脚本之所以这么说,因为我们可以想象从打开的窗口(或者甚至是提示符中的等价物)执行以下(不可能的)命令:cmdPowerShell

==> "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & 'D:\PShell\SF\q866281.ps1'"
script ouput here
D:\PShell\SF\q866281.ps1: supposedly run via explorer right click

==>
Run Code Online (Sandbox Code Playgroud)

  • 在版本 2004 中,您必须检查这些键:Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\SystemFileAssociations\.ps1\Shell\0\Command (2认同)