Security – Granting permission for Windows service

iispowershellSecuritywindows-server-2008

I am on yet another obstacle. I have a non-admin IIS identity account, to which I would like to grant permission to start, stop, restart, and read the status of one Windows Service. I followed the solution posted here. However, I would like to achieve this via PowerShell to automate, because I have so many servers. I was able to get SID of non-admin account, and get the output of command and save it under a variable. I converted to string, but cannot apply any functions such as StartsWith, split, insert, etc. Here is my code:

#Getting the SID for non-admin ISS identity account
$objUser = New-Object System.Security.Principal.NTAccount("non-admin")
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$sid = $strSID.Value
#output retuned = S-1-5-21-2103278432-2794320136-1883075150-1000

#Storing the output of cmd prompt
$cmd = cmd.exe /c "sc sdshow <Service_Name>"
$test = $cmd | Out-String
#output returned = D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

#Storing the value that needs to be inserted in $CMD
$str = "(A;;RPWPCR;;;$sid)"

I would like to insert $str just before "S:" in $test and I have been unsuccessful. I would like to achieve this by PowerShell and not SubInAcl. Any help would be appreciated. The final code should look like below:

sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)($str)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

Best Answer

Assuming that your $test variable contains D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD), you could do:

$sid = "S-1-5-21-2103278432-2794320136-1883075150-1000"
$test = "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"
$str = "(A;;RPWPCR;;;$sid)"

$newstring = $test -replace "S:","$($str)S:"

$newstring

returns:

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)