如何使用用户凭据在Powershell中运行启动进程? [英] How to run Start-Process in Powershell using user credentials?

查看:80
本文介绍了如何使用用户凭据在Powershell中运行启动进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows服务(Jenkins),该服务运行一个脚本,该脚本需要以特定用户的身份运行命令.

I've got a Windows service (Jenkins) that runs a script which needs to run a command as a specific user.

我试图这样做,但是不起作用:

I tried to do this but it doesn't work:

$secpasswd = ConvertTo-SecureString "myPassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential("DOMAIN\myUsername", $secpasswd)

$Arguments = @()
$Arguments += "-Command"
$Arguments += "pwd"
$Arguments += ">"
$Arguments += "output.txt"
Start-Process powershell.exe -ArgumentList $Arguments -Credential $mycreds -NoNewWindow -WorkingDirectory $workingDir
Start-Sleep 2
Get-Content "$workingDir\output.txt"

我得到以下输出:

Start-Process : This command cannot be executed due to the error: Access is denied.
At C:\Windows\TEMP\hudson2382859596554223918.ps1:32 char:14
+ Start-Process <<<<  powershell.exe -ArgumentList $Arguments -Credential $mycreds -NoNewWindow -WorkingDirectory $workingDir
    + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

现在,如果我删除-Credential $mycreds,它将正常工作.最后出现Start-Sleep的原因是,我在阅读关于SO的问题后删除了-Wait

Now if I remove -Credential $mycreds it works fine. The reason why there is that Start-Sleep at the end is that I removed the -Wait after reading this question on SO.

我在这里想念东西吗?

推荐答案

最终找到了解决方案:默认情况下,Jenkins作为服务运行,并且以本地系统帐户"身份登录.要对此进行更改,请启动服务应用程序(在开始菜单中键入服务"),查找Jenkins,双击它,然后转到登录"选项卡.

Finally found the solution: by default, Jenkins is run as a service log on as the "Local System account". To change this launch the services application (type "services" in the start menu), look for Jenkins, double click on it and go to the "Log On" tab.

您现在应该查看该服务正在使用什么帐户.更改为此帐户",然后填写您的帐户详细信息,瞧!

You should now see what account the service is using. Change to "This account" and fill in your account details and voila!

出于记录目的,我最初尝试运行的命令现在可以正常运行,而不必在顶部添加任何更改用户"的内容.

For the record the command I was originally trying to run works fine now, without having to add any of the "changing user" things on top.

特别感谢 @Poorkenny ,这使我对他的评论走上了正确的轨道,谢谢!! Stackoverflow令人毛骨悚然! (那是在感谢某人的那一刻,您刚刚解决了一个问题,使您整日解决问题的那一刻……)

Special thanks to @Poorkenny that put me on the correct track with his comment, THANK YOU! Stackoverflow rocks! (that moment when thanks to someone you just solved an issue that took you the whole day to figure it out...)

这篇关于如何使用用户凭据在Powershell中运行启动进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆