解决会话 0 中使用 PowerShell Start-Process -Credential 时的问题
2024-03-04 02:48:14
在会话 0 中使用 PowerShell Start-Process -Credential
问题:
在 Windows 启动脚本中使用 Start-Process -Credential
运行命令时,可能会遇到在会话 0 中无法运行的问题。
原因:
Start-Process -Credential
在会话 0 中存在运行问题。
解决方案:
1. 使用 Schtasks 计划任务
创建一个计划任务,在系统启动时使用指定的凭据运行命令。此方法不会涉及会话问题。
2. 使用 -ParentID 选项
添加 -ParentID
选项,使新进程成为父进程的子进程。这可能解决会话 0 问题。
3. 在非会话 0 中启动 PowerShell
启动两个 PowerShell 进程,一个在会话 0 中,另一个在非会话 0 中。然后,在非会话 0 进程中使用 Invoke-Command
启动带有凭据的命令。
4. 使用 Invoke-Command 选项
直接使用 Invoke-Command
在本地计算机上启动命令,指定会话和凭据。
代码示例:
# 使用 Schtasks 计划任务
schtasks /create /tn "MyTask" /sc onstart /tr "powershell -NoProfile -Command {echo 'it works' | Out-File test.txt}" /ru "adfs\setupadmin" /rp "[redacted]"
# 使用 -ParentID 选项
Start-Process powershell '-NoProfile', '-Command', {echo 'it works' | Out-File test.txt} -Credential $Credential -ParentID (Get-Process powershell).Id -Wait
# 在非会话 0 中启动 PowerShell
$session = New-PSSession -ComputerName localhost
Invoke-Command -Session $session -ScriptBlock {Start-Process powershell '-NoProfile', '-Command', {echo 'it works' | Out-File test.txt} -Credential $Credential -Wait} -Wait
# 使用 Invoke-Command 选项
Invoke-Command -ComputerName localhost -ScriptBlock {Start-Process powershell '-NoProfile', '-Command', {echo 'it works' | Out-File test.txt} -Credential $Credential -Wait}
结论:
通过遵循这些解决方案中的一个,你可以成功地在会话 0 中使用 Start-Process -Credential
运行命令。选择最适合你特定情况的方法。
常见问题解答:
1. 为什么 Start-Process -Credential
在会话 0 中不起作用?
原因尚不清楚,但可能是由于会话 0 的限制或 Start-Process
的行为。
2. 我可以同时使用哪个解决方案?
所有解决方案都是可行的,你可以根据你的需要和偏好进行选择。
3. 哪个解决方案最可靠?
Invoke-Command
选项通常被认为是最可靠的。
4. 这些解决方案是否适用于所有版本的 Windows?
是的,这些解决方案适用于大多数 Windows 版本。
5. 我需要其他帮助,在哪里可以找到它?
你可以参考 Microsoft 文档、技术论坛或联系技术支持以获得进一步的帮助。