You can only impersonate as service account from a Windows service typically, like this post mentions:
The trick is to run your code as Local System and from there you can impersonate the service accounts by using the appropriate username with no password. One way to run your code as the Local System account is to create a command line shell by using the technique shown below (taken from this orginal post), and execute your assembly from there. Calling System.Diagnostics.Debugger.Break() in your code allows you to debug.
To create a command-line shell that runs under the local system account, open a new command line window and enter:
A new command window should have opened up. In that window run your application.exe - you'll see that you're now running as the built-in System user account. After you've finished testing, you can delete the test service you created by entering:
c:\sc delete testsvc
If you try to do that in your own user context, then such attempts should fail.
I know this is an old thread but it is the top result for this problem and I wanted to be able to run a command using PowerShell without having to install any additional tools on our Windows Server. I came up with the following PowerShell script that creates a scheduled task, runs it, and then deletes it. It is also written to allow you to run the command under different user accounts.
function InstallDotNetCoreGlobalTool($PackageId, $Action = "install", $User = "NT AUTHORITY\NETWORK SERVICE", $Password = "")
{
$TaskName = "AzureDotNetCoreGlobalToolConfiguration"
$Command = "dotnet.exe"
$Arguments = "tool $Action -g " + $PackageId
$TaskAction = New-ScheduledTaskAction -Execute $Command -Argument $Arguments
Write-Host "Setting up scheduled task to run" $Command $Arguments
Register-ScheduledTask -TaskName $TaskName -User $User -Action $TaskAction
Start-ScheduledTask -TaskName $TaskName
Write-Host ""
Write-Host "Waiting on scheduled task to complete."
while ((Get-ScheduledTask -TaskName $TaskName).State -ne 'Ready')
{
# keep waiting
}
Write-Host ""
If((Get-ScheduledTask $TaskName | Get-ScheduledTaskInfo).LastTaskResult -eq 0)
{
Write-Host $PackageId $Action "completed successfully"
}
else
{
If ($Action -eq "install")
{
Write-Host $PackageId "failed to $Action. Ensure the proper dependencies have been installed or that it isn't already installed."
}
Else {
Write-Host $PackageId "failed to $Action. It may not currently be installed."
}
}
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
}
InstallDotNetCoreGlobalTool "Amazon.Lambda.Tools" "uninstall"