Run the script block as a specific user with Powershell

I don't get anywhere when using the Start-Process / Start-Job cmdlets with -Credential $ cred

Problem

I have a service account in a deployment (automatic mode). It was previously added to the local administrator group. I want to reduce the potential damage that I could do by removing this user from the administration group and explicitly assigning folder access rights to this user.

  • I rather get a permission error than doing something that happens by accident. Delete item "$ notdefined \ *"

However, in the same powershell script, I want to be able to raise in order to accomplish things like:

  • sc.exe
  • restarting the application pool that requires an administrator.

One of my failed attempts

$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" 
+1
source share
3 answers

I ended up turning on WinRM using WinRM quickconfig

Then I was able to use 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
source

Hi, this might be an example that might work for you, let me know if that happens.

 $global:credentials = new-object -typename System.Management.Automation.PSCredential $job = Start-Job -ScriptBlock {Get-Service} -Credential $credentials Wait-Job $job Receive-Job $job 
0
source

While in PowerShell 2.0, version 3.0 (currently in RC, most likely RTW is very soon, given that Windows 8 RTW will appear on MSDN / Technet tomorrow) there is no simple and easy way, it supports the idea of โ€‹โ€‹setting up remote endpoints using individual identifier. This will be done with the Register-PSSessionConfiguration on the computer where you want to run this command, and it can be a local computer. Then, using Invoke-Command , specify the session with the -Session parameter. The session is created using the New-PSSession , which allows you to specify the computer and configuration name (which is associated with a user identifier.)

Remove like dirt?

0
source

Source: https://habr.com/ru/post/1206825/


All Articles