You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Intune运行PowerShell脚本时如何保存到客户端指定路径并创建登录计划任务

解决方案

根本原因

Intune 通过 Intune 管理扩展 (IME) 下发的 PowerShell 脚本默认直接在内存中执行,不会在本地磁盘生成临时脚本文件,因此$PSCommandPath、$MyInvocation.PSCommandPath等依赖本地脚本文件路径的变量均会返回空值,你之前的测试逻辑无法生效。

可行实现方案

不需要读取源脚本文件路径,直接通过$MyInvocation.MyCommand.Definition获取当前运行脚本的完整内容,直接写入目标路径即可,完整实现代码如下:

# 定义目标存储路径
$targetDir = "C:\ProgramData\script"
$targetScriptPath = Join-Path $targetDir "auto_run_script.ps1"

# 不存在目标目录则创建
if (-not (Test-Path $targetDir)) {
    New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
}

# 将当前脚本完整内容写入目标路径
$currentScriptContent = $MyInvocation.MyCommand.Definition
$currentScriptContent | Out-File -FilePath $targetScriptPath -Encoding utf8 -Force

# 创建用户登录触发的计划任务
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -WindowStyle Hidden -File `"$targetScriptPath`""
$trigger = New-ScheduledTaskTrigger -AtLogOn
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$principal = New-ScheduledTaskPrincipal -UserId "BUILTIN\Users" -LogonType Interactive -RunLevel Highest

# 注册计划任务,避免重复创建
if (Get-ScheduledTask -TaskName "用户登录自动执行脚本" -ErrorAction SilentlyContinue) {
    Unregister-ScheduledTask -TaskName "用户登录自动执行脚本" -Confirm:$false
}
Register-ScheduledTask -TaskName "用户登录自动执行脚本" -Action $action -Trigger $trigger -Settings $settings -Principal $principal | Out-Null

# ---------------------- 以下为你原本的业务脚本逻辑 ----------------------
# 此处写入你原本需要执行的脚本内容

注意事项

  • 脚本通过Intune运行时默认持系统权限,写入C:\ProgramData目录、创建计划任务均无需额外提权
  • 如果你需要后台静默执行不需要用户交互,可以修改New-ScheduledTaskPrincipal的UserId参数为SYSTEM,触发条件也可按需调整为开机启动
  • 脚本后续迭代直接修改Intune中下发的脚本内容即可,重新运行后会自动覆盖目标路径的旧脚本并更新计划任务配置

内容的提问来源于stack exchange,提问作者Justin E

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:09:03