我有一个运行在Windows服务(Jenkins)上的脚本,需要以特定用户身份运行一个命令。
我尝试过这样做,但是不起作用:
$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
选项。
我有什么遗漏吗?
Write-Host“User:$([Environment] ::UserName)”
的结果中可以看出),而当我尝试在本地运行时,它可以工作,因为相同的命令返回我的用户名。构建脚本需要访问本地网络上的一个脚本文件,该文件的权限设置允许我的帐户访问它。 - Uflex