powershellwindows-services

Powershell get current DOMAIN OR COMPUTER NAME\USER and the difference between the two


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

Solution

  • 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'