使用 Powershell 以特定用户身份运行脚本块

问题描述 投票:0回答:4

使用带有 -Credential $cred 的 Start-Process / Start-Job cmdlet 时,我没有任何进展

问题

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

  • 我宁愿得到权限错误,也不愿执行意外伸出的东西。 删除项目“$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
4个回答
1
投票

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

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


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

Wait-Job $job

Receive-Job $job

1
投票

我最终使用 WinRM 快速配置启用了 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")

0
投票

虽然在 PowerShell 2.0 中没有快速简便的方法来执行此操作,但版本 3.0(目前处于 RC 状态,鉴于 Windows 8 RTW 明天将出现在 MSDN/Technet 上,很可能很快就会出现 RTW)支持使用自定义配置远程处理端点的概念身份。这可以通过您想要运行命令的计算机(可能是本地计算机)上的

Register-PSSessionConfiguration
cmdlet 来完成。然后,在使用
Invoke-Command
时,提供带有
-Session
参数的会话。该会话是使用
New-PSSession
cmdlet 创建的,它允许您指定计算机和配置名称(与自定义身份绑定)。

清澈如泥?


0
投票

对于管理员帐户,有一个快速但肮脏的解决方案:

$Var1 = 1
$Var2 = 2
$Var3 = 3

Start-Process -FilePath 'pwsh.exe' -Verb 'RunAs' "-Command & {
    Some-Command -Arg $Var1
    Some-Command -Arg $Var2
    Some-Command -Arg $Var3
}"

创建一个

ScriptBlock
并通过传递给它的参数来调用它,相比之下是很痛苦的。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.