How to run a Powershell Script block with elevated privileges
<p>I am writing a PowerShell script to archive compressed C2 Audit files to a file share. What is possibly the last problem I am having is giving the .Net compression routine the privilege to manipulate the files. During development, I could flaunt my account's admin role to propagate Full Access privileges to the files in the DATA directory. However, the script is to run from a PowerShell step in an Agent job, and I want to automate the ACL change as well.  </p>

<p>For an added level of difficulty, I am doing this under SQL Server 2012, so I am stuck with PowerShell 2.0. I am using .Net 4.5 compression routines via a process of loading $RunActivationConfigPath with a temporary config file. I was not able to find a way to change that config file to promote the admin role, though.</p>

<p>This is a segment of a script by Benjamin Armstrong that checks if the connection is using Administrator privileges.</p>

<pre><code># Get the ID and security principal of the current user account
$runtimeWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$runtimeWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($runtimeWindowsID);
# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;

Write-Output ("Running under "+$runtimeWindowsID.Name)
Write-Output ("PS Version "+$PSVersionTable.PSVersion.Major)

# Check to see if we are currently running as an administrator
if ($runtimeWindowsPrincipal.IsInRole($adminRole) -eq $true) {
  Write-Output "We are strong."
} else {
  Write-Output "We are not strong."
}
</code></pre>

<p>Running the script as an Agent Job step produces:</p>

<blockquote>
  <p>Running under NT Service\SQLSERVERAGENT<br>
  PS Version 2<br>
  We are not strong.</p>
</blockquote>

<p>Running the script from sqlps in Admin mode produces:</p>

<blockquote>
  <p>Running under DOMAIN\myusername<br>
  PS Version 2<br>
  We are strong.</p>
</blockquote>

<p>All the ways I've seen to elevate a script involve using a script file. For example, creating a new process and executing it with RunAs as the Verb. I want to avoid script files and have everything in the step. I like the added security (however small) of needing SSMS privileges to view the code.</p>

<p>So, here are my questions:</p>

<p>1) Is there a way to elevate commands in a <em>script block</em>?</p>

<p>2) Is there a way to have the PowerShell step in an Agent Job run in Admin mode?</p>

<p>Extra credit question:</p>

<p>3) If I do need to add the Agent service account to a Windows User Group, which of the two dozen groups would give that account the minimum privileges needed to alter an ACL for a file, then eventually delete it?</p>