2

I'm making a script for registering my API as a windows service. I followed this guide here and filled it to the best of my ability since i'm new to PS:

$acl = Get-Acl "$PSScriptRoot"
$aclRuleArgs = {DOMAIN OR COMPUTER NAME\USER}, "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "$PSScriptRoot"

New-Service -Name MyAPIService -BinaryPathName $PSScriptRoot\MyAPIService.exe -Credential {DOMAIN OR COMPUTER NAME\USER} -Description "API" -DisplayName "API Service" -StartupType Automatic

What I would like to know is how would i get the current domain or computer name, like i get the current directory with $PSScriptRoot. The service would be running on Windows 10.
I also don't know whether i should use the domain or computer name\user? In what situation would i need one or the other?

EDIT: With @Patrick help I made it work, here is the working script:

$acl = Get-Acl "$PSScriptRoot"
$aclRuleArgs = "$env:COMPUTERNAME\$env:USERNAME", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "$PSScriptRoot"

New-Service -Name MyAPIService -BinaryPathName $PSScriptRoot\MyAPIService.exe Description "API" -DisplayName "API Service" -StartupType Automatic
Luka Rakic
  • 473
  • 7
  • 15

2 Answers2

4

Take a look here: About Environment Variables

$env:COMPUTERNAME
$env:USERNAME
$env:USERDNSDOMAIN

About the user:
Is it a local or a domain user? If local, use 'COMPUTERNAME\USERNAME'. Otherwiese 'DOMAIN\USERNAME'

Community
  • 1
  • 1
Patrick
  • 2,128
  • 16
  • 24
  • Thanks, these work. I tried this $aclRuleArgs= $env:COMPUTERNAME + '\' + $env:USERNAME and the output is COMPUTERNAME\USERNAME. Thats how it should be, right? I cant figure it out from the documentation. @Patrick – Luka Rakic Oct 18 '19 at 08:31
  • 1
    Might this helps how to create the rule: [powershell-setting-advanced-ntfs-permissions](https://stackoverflow.com/questions/26543127/powershell-setting-advanced-ntfs-permissions) / [How to Handle NTFS Folder Permissions, Security Descriptors and ACLs in PowerShell](https://blogs.technet.microsoft.com/josebda/2010/11/12/how-to-handle-ntfs-folder-permissions-security-descriptors-and-acls-in-powershell/) – Patrick Oct 18 '19 at 09:17
1
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

It should include computer or domain name - so no need to build these yourself. This is for the currently logged in user however - just like the environmental variables you've been advised to use in other places.

Furthermore - it can't be edited by simply overwriting the environmental variable.

user3012708
  • 793
  • 1
  • 11
  • 33