【问题标题】:run script block as a specific user with Powershell使用 Powershell 以特定用户身份运行脚本块
【发布时间】:2012-08-14 08:38:09
【问题描述】:

将 Start-Process / Start-Job cmdlet 与 -Credential $cred 一起使用时,我没有得到任何结果

问题

我在部署中使用了一个服务帐户(无人值守模式)。以前它已添加到本地管理员组。我想通过从管理员组中删除该用户并明确分配文件夹权限给该用户来减少可能造成的损害。

  • 我宁愿得到一个权限错误也不愿执行一些意外的事情。 删除项目“$notdefined\*”

但是,在同一个 powershell 脚本中,我希望能够提升以执行以下操作:

  • sc.exe
  • 应用程序池重启 这需要管理员用户。

我的一次失败尝试

$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"

【问题讨论】:

标签: powershell deployment


【解决方案1】:

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

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


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

Wait-Job $job

Receive-Job $job

【讨论】:

  • Get-Service 不需要提升权限 - 尝试 Stop-Service $serviceName -Force 。还是不行……
【解决方案2】:

我最终使用 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")

【讨论】:

    【解决方案3】:

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

    清如泥?

    【讨论】:

      猜你喜欢
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多