Run BAT file as a Local User Account - powershell

I pulled this from another question, but I cannot seem to make this work.
I need to run this .bat file as a local admin account. I want users to be able to run and install this without having local admin rights.
I'm not sure what's wrong though.
$username = 'localadmin'
$password = 'passwordforlocaladmin'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process -Filepath "p:\kaceInstaller\kaceinstall3.bat" -Credential $credential
The error I'm getting back is:
Start-Process : This command cannot be executed due to the error: The directory
name is invalid.
At P:\kaceInstaller\misc\kaceSetup.ps1:7 char:14
+ Start-Process <<<< cmd -Credential $credential
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommandy

If you want to allow users to run something as a local administrator account without effectively giving them the password to the local admin account, I would suggest to create a scheduled task running as a local admin. Users can manually trigger that task, which will then be executed under the local admin account. Creating the task withoug saving the credentials should work, but even if you have to save the credentials they won't be accessible to your users.
For access to network shares you may need to connect/disconnect the share with explicit credentials from within the script that the scheduled task runs, though, because the local account usually doesn't have permission to access the network drives mapped by your domain user.
net use X: \\server\share\kaceInstaller password /user:DOMAIN\user
call X:\kaceinstall3.bat
net use X: /d
Make DOMAIN\user a dedicated account that has access only to \\server\share and nothing else to minimize risk.
Note that you must make sure that the script run by the task is not writable by regular users, otherwise they will be able to run arbitrary commands with admin privileges by simply modifying the script.

Related

Start-Job Using Credentials Fails With Error Username/Password Incorrect

I am working on a PowerShell script that needs to run a job as a different user due to different types of permissions used at my organization. When testing my script, I keep getting the error that the username or password is incorrect, even though I am certain the credentials I am using are correct.
My script right now gets the users credentials, and starts the job which just calls a second PS script. The second script is located in the same folder as the parent script. My code right now:
$PSScriptRoot
$scriptPath = $PSScriptRoot + "\sample2.ps1"
$cred = Get-Credential -Message "Please enter your non-admin account information"
$myJob = Start-Job -FilePath $scriptPath -Credential $cred
$myJob | Receive-Job -Keep
$myJob #Output the job
I even tried the following which I found online, and using this format did not work either.
$username = Username
$password = Password
$cred = New-Object -TypeName System.Management.Automation.PSCredential ($username, $password)
$Credentials = Get-Credential $cred
I am hoping that this process will allow the second script to be run off of the first script, since to complete the objective of my script, I must run the parent script as an admin account and the child script as a normal account, due to organizational differences in permissions. Instead, I continue to get the following error:
[localhost] An error occurred while starting the background process. Error reported: The user name or password is incorrect.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : -2147467259,PSSessionStateBroken
And get the following output from the job:
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
7 Job7 BackgroundJob Failed False localhost Write-Host "Hello Worl...
Any help with figuring out this credentials issue is much appreciated.
EDIT: My issue was that I was not using the domain\username format when entering my username in the credentials dialog. I also had to move the scripts to a drive that was accessible by both the non-admin and admin accounts, since they cannot access each other's C:\.

getting error while copying file to remote location using powershell scripts in gitlab runner

I am setting up a GitLab CI/CD pipeline to copy the war file using PowerShell copy-item function. I am getting below error in the pipeline. the user is already an administrator on the gitlab runner computer.
[servername] Connecting to remote server name failed with the
following error message: Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (servername:String) [], PSRemotingT ransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken ERROR: Job failed: exit status 1
Here is my script in .yml file.
GitLab Runner registered in windows server.
Here is my script in .yml file.
envvariable_username - Environment variable configured in gitlab CI/CD settings page
$envvariable_password - Environment variable configured in gitlab CI/CD settings page
- powershell Invoke-Command -ComputerName computer_name -argumentlist $envvariable_username,$envvariable_password -ScriptBlock {
$password = convertto-securestring -String $envvariable_password -AsPlainText -Force
$mycred = new-object -typename System.Management.Automation.PSCredential $envvariable_username, $password
New-PSDrive -Name "s" -PSProvider FileSystem -root "\\\\computer_name\\share" -Credential $mycred
New-PSDrive -Name "z" -PSProvider FileSystem -root "\\\\computer_name\\backup" -Credential $mycred
Copy-Item -Path "s:\\sample.war" -Destination "z:\\sample.war"
}
expected to copy .war file from one server location to another server location
Looking at your script, you try to execute a script block on a remote server without specifying credentials. That means that either the server has no restrictions or you assume that both servers belong to the same domain, so kerberos will be utilized.
In my experience, when the second is the case, most people forget to evaluate on who's behalf is the script executing. Keep in mind that a process inherits the user context of the parent process unless otherwise specified.
That would mean that the user running your script doesn't have the necessary access to the remote server. You can always evaluate this by first doing this $env:USERDOMAIN + "\" + $env:USERNAME
For example a line in your yaml
- powershell $env:USERDOMAIN + "\" + $env:USERNAME
So when you debug something from a console that you launched with your user, then you don't have 100% replication of the conditions as you are forgetting the most important aspect of any process, that is the logon user.
Then, if this works, I've noticed that from the remote server you are trying to access another remote location. I notice that you are specifying credentials for this part if please do note that if from within a remote session, you try to access any remote resource, then you need to be aware of some caveats. Please read more about them hereand especially the one specific to the double hop.
As a word of advice, best way to troubleshoot scripts that utilize remote execution, is to logon on the server with the same user as with the services that runs your scripts, thus replication the conditions 100%. It is also possible to launch only the console with the credentials of another user.

Azure Provisioning - Without manual login

I have a Powershell script which runs to set up Azure web apps, databases, etc. but before running the script, I have to do the following:
PS C:/> Login-AzureRmAccount
This pops up a GUI in which I have to manually add in my user, password, and my 2-factor authentication code. I eventually want to use that script as a part of a part of a build/deployment automation script.
I gleaned the following from a few articles about using a "service principal".
First I do:
PS C:\> Add-AzureRmAccount
In this call I have to put in my user, password, and authentication code
After that I have to do the following (even though I don't fully understand).
$app = New-AzureRmADApplication -DisplayName "GGReal" -HomePage "https://www.example.org/ggreal" -IdentifierUris "https://www.example.org/ggreal" -Password "mysecretpass"
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
This seems to work:
Then I try this, and it fails.
New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName $app.ApplicationId
I got the following error:
New-AzureRmRoleAssignment : AuthorizationFailed: The client jay#myemail.com' with object id '8ee9a6ec-yyyy-xxxx-xxxx-4ac0883f2a12' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write' over scope '/subscriptions/5ba06de5-xxxx-zzzz-yyyy-27f7d2c8bba6'.
At line:1 char:1
+ New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureRmRoleAssignment], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.NewAzureRoleAssignmentCommand
What do I have to do to enable a scripted authorization without manual intervention?
According to the exception that it indicates that you don't has adequate permission to that. We can check active directory permissions following the document. Our account needs to have Microsoft.Authorization/*/Write access to assign an AD app to a role. That means our account should be assigned to the
Owner role or User Access Administrator role. If not, please ask your subscription administrator to add you to User Access Administrator role. How to add or change Azure administrator roles please refer to the document.
After that please have a try to Automate login for Azure Powershell scripts with the following code.
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "strong password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId $azureTenantId  -ServicePrincipal
I also find some related documents about creating authentication and Built-in roles:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal
https://learn.microsoft.com/en-us/azure/active-directory/role-based-access-built-in-roles#roles-in-azurel
Well, you don't have permissions to assign that role to that serviceprincipal, you need appropriate rights. And those would be: Microsoft.Authorization/roleAssignments/write and scope /subscriptions/5ba06de5-xxxx-zzzz-yyyy-27f7d2c8bba6
You could either create a new Custom Role and assign it to your account, or assign something like Subscription Admin (not sure if its the least possible approach, but you can retract it later) to your account.

How to avoid the crendetial dialog box while conecting to different system using powershell?

I am making connection to the diferent system using powershell. I want this process to be automated in a way that once user hits the powershell script he gets connected to different system without entering username and password details into the dialog box. So, currently my.PS1 script as follows:
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts CP0001256
Restart-Service WinRM
Test-WsMan CP0001256
$credential = Import-CliXml -Path "D:\$Env:USERNAME_pass.xml"
Invoke-Command -ComputerName CP0001256-ScriptBlock { Get-ChildItem D:\ }-credential $credential
Before running my.PS1 i have executed follwing script:
$credential = Get-Credential
$credential | Export-CliXml -Path "D:\$Env:USERNAME_pass.xml"
So, when i execute my.PS1 i got error as:
Invoke-Command : Cannot process argument transformation on parameter 'Credential'. username
At my.PS1:7 char 86
+ Invoke-Command -ComputerName CP0001256-ScriptBlock { Get-ChildItem D:\ } -credential <<<< $credential
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindin..mationException
+ FullyQualifiedErrorID : ParameterArgumentTransformationError,Microsoft.Powershell.Commands.InvokeCommand
So, tell me what i am doing wrong and how can i avoid getting the credential dialog box pop up appearing.
This is a question of how to store credentials in a script. Keep in mind that this always carries some risk. You can of course store them in plain text. Then anyone with access to the script has those credentials.
Another thing you can do is take advantage of the [PSCredential] object, and store the password encrypted. Consider running this code (outside of that script):
$credential = Get-Credential # dialog pops up here, enter server creds
$credential | Export-CliXml -Path "C:\Script\$Env:USERNAME_Credential.xml"
Now in your script, you can do this:
$credential = Import-CliXml -Path "C:\Script\$Env:USERNAME_Credential.xml"
Invoke-Command -ComputerName CP0001256-ScriptBlock { Get-ChildItem D:\ }-credential $credential
The password is encrypted within that XML file, and it's encrypted with a key that is specific to the user who ran the first set of commands, so only that user will be able to effectively run the script if you do this.
This is also why I use the USERNAME environment variable as part of the file name. You can have multiple employees run the first code snippet to generate a separate encrypted file for each of them. Then your script will work successfully when any of them run it.
It also works if you have an account used for a scheduled task for example; run the snippet as that user once, then the scheduled task will work.

Not able to run exe from powershell for a system user

I am trying to run an exe from powershell script on windows-7 64 bit machine. In this script I want to run exe as another user. It works when user invoking script is an actual user. But in my case, this powershell script will be executed from system user account and for system user script does not work. Here in a simple code I am using to open notepad. This code fails for system user.
$username = 'MyDomain\MyUser'
$password = 'mypswd'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process -Credential $cred "notepad.exe"
I have set execution policy to unrestricted. When I run this script for system user, then I get error as
Start-Process : This command cannot be executed due to the error: Access is den
ied.
At D:\temp\trythis.ps1:4 char:14
+ Start-Process <<<< -Credential $cred "notepad.exe"
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp
erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand
Is there any way in which I can run this script for system user?
The most likely problem here is a permissions one (The only way I could reproduce your issue was by setting a Deny entry for the account).
I would suggest the following to confirm the permissions are correct. Instructions are for Windows XP, SP3 - adjust for your version!
Right-click on "notepad.exe" and click Properties
Click the Security tab
Click the Advanced button
Click the Effective Permissions tab
Click the Select... button
Enter the account you want to check and confirm that the account has appropriate read and execute permissions.