Powershell脚本可执行文件自毁



我正在使用PS2EXE将.ps1脚本转换为exe。运行完可执行文件后,我希望它删除自己。我试着用"-LiteralPath";以及"$PSScriptRoot";但两者在运行时都作为可执行文件返回null。

感谢您的回复。

在您的代码中。。。

  1. 在可执行文件启动时,创建一个计划任务(执行删除项(以在记录事件时启动。使用现有的事件日志,或者创建自己的事件日志
  2. 在您的计划任务中,您分配自己要编写的代码到事件日志
  3. 在您的代码中,完成后,您将写入事件日志
  4. 当您写入日志时,任务应该启动

。。。或者在代码中,创建一个计划任务(删除项目(作为代码中的最后一个操作,在创建后1分钟执行。

根据我对您的路径问题的后续评论进行更新。

"你能举个例子吗?路径必须是其当前路径位置,当它被执行时可能是未知的">

Tested-在PS2EXE中转换为可执行程序的示例代码。

注:有报道称,AV解决方案现在正在警告这种类型的ps1到exe的转换用例。

Powershell脚本hello.ps1转换为exe

# Get executable process path
$ExecutablePath = (Get-Process -ProcessName hello).path
# Check for an existing task
Function Remove-ExecutableTask
{
Try   
{
Get-ScheduledTask -TaskName 'RemoveCurrentExecutable' -ErrorAction Stop
Unregister-ScheduledTask -TaskName RemoveCurrentExecutable -Confirm:$false
}  
Catch {$PSItem.Exception.Message}
}
# Create Scheduled task
Function New-ExecutableTask
{
$ExecutableAction = $(New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "-NoProfile -command & {Remove-Item -Path $ExecutablePath}")
$Trigger          = New-ScheduledTaskTrigger -Once -At $("{0:hhtt}" -f (get-date).AddHours(1))
Register-ScheduledTask -Action $ExecutableAction -Trigger $Trigger -TaskName 'RemoveCurrentExecutable' -Description 'Remove the target executable.'
}

Remove-ExecutableTask
New-ExecutableTask
'Hello World!'
"Hello World ran from: $ExecutablePath"
# Test run from the PowerShell consolehost and Results
<#
Try{(Get-ChildItem -Path 'D:temphello.exe' -ErrorAction Stop).FullName;&{D:temphello.exe}}Catch{$PSItem.Exception.Message}
Cannot find path 'D:temphello.exe' because it does not exist.
Try{Get-ScheduledTask -TaskName 'RemoveCurrentExecutable' -ErrorAction Stop}Catch{$PSItem.Exception.Message}
No MSFT_ScheduledTask objects found with property 'TaskName' equal to 'RemoveCurrentExecutable'.  Verify the value of the property and retry.
# Convert the script using PS2EXE and execute it
Try{(Get-ChildItem -Path 'D:temphello.exe' -ErrorAction Stop).FullName;&{D:temphello.exe}}Catch{$PSItem.Exception.Message}
D:temphello.exe
Try{Get-ScheduledTask -TaskName 'RemoveCurrentExecutable' -ErrorAction Stop}Catch{$PSItem.Exception.Message}
TaskPath                                       TaskName                          State     
--------                                       --------                          -----     
                                              RemoveCurrentExecutable           Ready     
(Get-ChildItem -Path D:Temphello.exe).FullName
D:Temphello.exe
# Execute the scheduled task
Start-ScheduledTask -TaskName RemoveCurrentExecutable
Try{(Get-ChildItem -Path 'D:temphello.exe' -ErrorAction Stop).FullName;&{D:temphello.exe}}Catch{$PSItem.Exception.Message}
Cannot find path 'D:temphello.exe' because it does not exist.
#>

当然,我只是手动启动了脚本,但它会在定义的时间执行。

相关内容

最新更新