使用Powershell作为特定用户运行脚本块

时间:2012-08-14 08:38:09

标签: powershell deployment

使用带有-Credential $ cred

的Start-Process / Start-Job cmdlet时,我无法到达任何地方

问题

我在部署中使用服务帐户(无人参与模式)。以前它已添加到本地管理员组。我希望通过从admin组中删除此用户并明确为此用户分配文件夹权限来减少可能造成的潜在损害。

  • 我宁愿得到一个权限错误,也不会执行意外触及的内容。 删除项目“$ notdefined \ *”

然而,在同一个PowerShell脚本中,我希望能够提升执行以下内容:

  • sc.exe
  • app pool restart 这需要管理员用户。

我失败的尝试之一

$job = Start-Job -ScriptBlock { 

param(
    [string]$myWebAppId
)

Import-Module WebAdministration

Write-Host "Will get the application pool of: IIS:\Sites\$myWebAppId and try to restart"
$appPoolName = Get-ItemProperty "IIS:\Sites\$myWebAppId" ApplicationPool 
Restart-WebAppPool "$($appPoolName.applicationPool)" 
Write-Host "restart of apppool succeeded."

} -Credential $cred -ArgumentList @("appname")

Write-Host "started completed"

Wait-Job $job

Write-Host "wait completed"

Receive-Job $job -Verbose

Write-Host "receive completed"

3 个答案:

答案 0 :(得分:1)

我最终使用WinRM quickconfig

启用WinRM

然后我可以使用Invoke-Command

    $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

Invoke-Command {
    param(
        [string]$WebAppName 
    )
     #elevated command here

} -comp $computerName -cred $cred  -ArgumentList @("$myWebAppId")

答案 1 :(得分:0)

嗨,这可能是一个可能对您有用的示例,如果有,请告诉我。

$global:credentials = new-object -typename System.Management.Automation.PSCredential 


$job = Start-Job -ScriptBlock {Get-Service} -Credential $credentials

Wait-Job $job

Receive-Job $job

答案 2 :(得分:0)

虽然没有快速简便的方法在PowerShell 2.0中实现这一点,3.0版本(目前在RC中,很可能很快就会出现RTW,因为Windows 8 RTW明天将出现在MSDN / Technet上)支持配置远程端点的概念自定义标识。这可以通过计算机上要运行命令的Register-PSSessionConfiguration cmdlet来完成,该计算机可能是本地计算机。然后,在使用Invoke-Command时,请提供具有-Session参数的会话。会话是使用New-PSSession cmdlet创建的,该cmdlet允许您指定计算机和配置名称(与自定义标识绑定。)

清除泥土?