Executing cmd files in terraforms - windows

I am provisioning a Windows Server 2012R2 with terraforms on Vsphere. I have the machine up and running. Now I want to run some .cmd files on the machine via remote_exec of terraforms.
The user is not the Administrator, but in the Administrator group. UAC disabled for the purpose of executing scripts via CLI or powershell.
I have written a runAsAdmin.ps1 which would call my install_software.ps1 which will have all the necessary commands to execute the .cmd files.
runAsAdmin.ps1
powershell -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -file C:\scripts\install_software.ps1' -verb RunAs}"
install_software.ps1
cd C:\\gitrepo\\lip-core-devops\\terraform\\system-config\\ims\\scripts
echo "Installing IMS Base from powerscript"
Invoke-Item .\Install_IMS_Base.cmd
I can run execute the runAsAsAdmin.ps1 on a powershell directly on the machine without admin elevation and everything works as expected.
But when I am executing the runAsAdmin.ps1 from the remote-exec of terraforms, the execution is successful, but the contents of the install_software file are not executed. I tried creating a directory before executing the cmd file.
Terraform part
provisioner "remote-exec" {
inline = [
"powershell -File C:\\scripts\\runAsAdmin.ps1"
}
the connection is all set and successful. I get success at the end of the script execution.
What I am I missing in my scripts that it is not executed via terraforms but works on the machine.

This could be caused by powershell execution policy?, try running it using the -ExecutionPolicy setting. I have to do this when using VM extensions in Azure.
start powershell -ExecutionPolicy Unrestricted -File runAsAdmin.ps1

i create server with winrm, than i put some command in powershell
like
provisioner "remote-exec" {
inline = [
"powershell.exe sleep 3",

Related

Powershell on ansible-playbook remote host

I have a PowerShell script ex1.ps1 which takes user inputs and ex1.ps1 has commands to open a new PowerShell to execute an exe file:
Start-Process -FilePath "$PSHOME\powershell.exe" -ArgumentList "-command C:\APPLICATION1.exe`
I want to execute ex1.ps1 on a remote host. I am trying to call ex1.ps1 using Ansible-playbook as:
# ansible-playbook script
- name: Run basic PowerShell script
win_powershell:
script: |
powershell.exe -ExecutionPolicy ByPass -File C:/Users/ex1.ps1
It is executing fine but in remote host there is no PowerShell prompt open to get the inputs.
You shouldn't be expecting manual input when deploying with a tool like Ansible. I don't know the actual program you are trying to run but the best solution here is to figure out the required parameters for the program to install/start/run without user interaction.
If you are able to provide the name of the program (and it's not something internal to your organization) a more complete answer may be able to be provided.
Unrelated to your question, unless you've over-generalized your code for this question there isn't a reason to call powershell.exe from within PowerShell just to run an executable. You can either use Start-Process or the call operator & directly with the exe path in question.
I have an answer here that goes over Start-Process and the usage of & in a bit more detail.

Is there a way to open multiple instances of CMD's with Azure-Pipelines?

I'm using Azure-Pipelines for my CI. In my pipeline, I need to use multiple instances of a CMD (Windows). For example, one CMD needs to start and continuously run a server, while the other needs to then deploy an app while the server is still running.
When using the CMD task, it only uses one instance of the CMD, so when I run the server, it never finishes and never gets to running the app.
Is there a way to run multiple instances of a CMD with Azure-Pipelines?
You can start cmd.exe on the agent machine from a powershell task using Start-Process command.
So you can add multiple powershell tasks to start multiple CMD instances on the agent machine. Or you can start multiple CMD instances in one powershell task. Se below example:
steps:
- powershell: |
'Start-Process -FilePath "C:\Windows\System32\cmd.exe" -verb runas -ArgumentList {/k echo "hello"}'
- powershell: |
'Start-Process -FilePath "C:\Windows\System32\cmd.exe" -verb runas -ArgumentList {/k echo "world"}'

How to sudo on powershell on Windows

Whenever I need to run a powershell script it complains of security, if I add powershell.exe -nologo -executionpolicy bypass -File .\install.ps1 I still get permission denied unauthorizedAccessException. I just want to run this install script, what is the sudo equivalent to type on the powershell on windows?
If you are using Chocolatey (a package manager), you can install a package named sudo.
Then you can use sudo like Linux 😋
Note: If you're looking to add general-purpose, prepackaged sudo-like functionality to PowerShell, consider the
Enter-AdminPSSession (psa) function from this Gist, discussed in the bottom section of this answer.
If you are running from PowerShell already, then use Start-Process -Verb RunAs as follows:
Start-Process -Verb RunAs powershell.exe -Args "-executionpolicy bypass -command Set-Location \`"$PWD\`"; .\install.ps1"
Note:
The script invariably runs in a new window.
Since the new window's working directory is invariably $env:windir\System32, a Set-Location call that switches to the caller's working directory ($PWD) is prepended.
Note that in PowerShell (Core) 7+ (pwsh.exe) this is no longer necessary, because the caller's current location is inherited.
Executing Set-Location necessitates the use of -Command instead of -File.
A general caveat is that -Command can change the way arguments passed to your script are interpreted (there are none in your case), because they are interpreted the same way they would be if you passed the arguments from within PowerShell, whereas -File treats them as literals.
If you're calling from outside of PowerShell, typically from cmd.exe/ a batch file, you need to wrap the above in an outer call to powershell.exe, which complicates things in terms of quoting, unfortunately:
powershell.exe -command "Start-Process -Verb RunAs powershell.exe -Args '-executionpolicy bypass -command', \"Set-Location `\"$PWD`\"; .\install.ps1\""
Interactively, of course, you can:
Right-click the PowerShell shortcut (in your taskbar or Start Menu, or on your Desktop), select Run as Administrator to open a PowerShell window that runs with admin privileges, and run .\install.ps1 from there.
Alternatively, from an existing PowerShell window, you can open a run-as-admin window with Start-Process -Verb RunAs powershell.exe, as in AdminOfThings' answer.
You can utilize the Start-Process command and then use parameter -Verb runas to elevate. This works great for starting an elevated process.
I created a sudo function like this and added it to my powershell profile:
function sudo {
Start-Process #args -verb runas
}
Example: Open notepad as Admin to edit hosts file
sudo notepad C:\Windows\System32\drivers\etc\hosts
If you want to elevate a Powershell command, you can create a simple function like this:
function Start-ElevatedPS {
param([ScriptBlock]$code)
Start-Process -FilePath powershell.exe -Verb RunAs -ArgumentList $code
}
Then, call the function and pass command wrapped in {} (script block)
Example: Elevate to create a symbolic link
Start-ElevatedPS { New-Item -ItemType SymbolicLink -Name mySymlink.ps1 -Target C:\myTarget.ps1 }
You can start PowerShell with the Run as Administrator option:
Start-Process powershell -Verb runAs
As of today (October 2021), winget install gerardog.gsudo did the trick (on windows 10 home edition). Edit: Tested on Windows 11 as well (April 2022)
after that, you can do this:
gsudo notepad C:\windows\system32\something-editable-by-admin-only.txt
To test if it's working, or in your case:
gsudo powershell.exe install.ps1
You will be prompted by windows` UAC to elevate your priveleges by gsudo, and you can read the source code here: https://github.com/gerardog/gsudo
If you have a corporate policy that blocks scripts execution, then yes. ByPass does not change your profile (user context) state. That is not the design (use case) for any of those switches regarding Execution Policies.
There is not a direct comparison of sudo in Windows, this has nothing to do with PowerShell. You are either admin in a session / app or you are not. If you are installing software, that means you must be admin. If you are doing global system-wide changes, that means you must be admin.
There are folks who have strived to implement scripts, wrapper functions and or modules to mimic sudo …
Module from the MS PowerShell gallery.
Sudo 0.9.3
Use functionality similar to sudo in PowerShell
From GitHub
Sudo for PowerShell
Sudo for PowerShell Installation From PowerShell, create a $profile if
you don't have one:
if (!(test-path $profile)) { new-item -path $profile -itemtype file -force }
Open the profile in notepad:
notepad.exe $profile
Add the following line and save the file:
. /path/to/sudo.ps1
sudo will be available in all new PowerShell windows Usage
sudo application [arguments ...]
...but that does not change what Windows expects when dealing with security boundaries.
See also this Q&A
Sudo !! equivalent in PowerShell
$^ is a variable that expands to the last executed Powershell command.
You can run a command as another user using runas, so the following
works:
runas /user:domain\administrator $^
To shorten that up a bit, you can do some magic with aliases. Take a
look at this Technet article for more info.
EDIT: One caveat - $^ only executes the first command in a pipeline or
multi-command line. If you need to redo an entire command that is
peppered with pipes or semicolons, use Invoke-History instead (which
defaults to the last full command in its entirety).

windows run script with local user account from administrator powershell

I have written a script which will do some stuffs on my application and that application running as local user app1user. So I need to run that script from Administrator account and call that script with runas /user:app1user, but it prompts for the user app1user password.
Is there anyway that we can overcome this and run that script as app1user without using password through powershell.
Also am tried to calling that script from Evlevated powershell window only.
In powershell you can use -Verb RunAs. Now you can use from cmd also and you can directly use it from Powershell also.
CMD:
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\Script.ps1\`\"`\"\" -Verb RunAs"
Powershell with new session (you can pass NoNewWindow also):
Start-Process powershell "-ExecutionPolicy Bypass -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\Script.ps1\`"`"" -Verb RunAs
Next Alternative is using Dot Net :
# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);
# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;
# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole)){"Its in elevated mode"}
Hope this helps...!!!

PowerShell .ps1 file on Visual Studio post build event

I am trying to execute the following post build event code but I am getting an non-useful error :
"c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file "$(SolutionDir)tools\nuget_pack.ps1"
I have run the following PS script before I try :
Set-ExecutionPolicy unrestricted
What am I missing?
UPDATE
This is strange, I am not getting an error on VS now. but the script is not working. When I run it with powershell console I get the following error :
Visual Studio writes the post-build event script to a .BAT file and executes that using cmd.exe. So using & "<path-to-powershell>" won't work. Just execute:
Powershell.exe -file "$(SolutionDir)tools\nuget_pack.ps1"
And if you think you're likely to run into execution policy issues on other machines that build the solution, consider going this route:
Powershell.exe -ExecutionPolicy Unrestricted -file "$(SolutionDir)tools\nuget_pack.ps1"
You can reproduce the error in Powershell as follows:
"this is a string" -file "my.ps1"
It is taking the first as a string, the -file as the -f format flag and saying it doesn't have a value expression on the right for the format substitution.
Try like this:
& "c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file "$(SolutionDir)tools\nuget_pack.ps1"
(as Keith notes, this will not work as this is run from a bat file than Powershell.)
Or just:
powershell.exe -file "$(SolutionDir)tools\nuget_pack.ps1"
Before calling power-shell script from visual studio, set the ExecutionPolicy to unrestricted from power-shell window like this...
Set-ExecutionPolicy -Scope CurrentUser;
ExecutionPolicy: unrestricted;
the call power-shell script in the following manner...
powershell.exe $(SolutionDir)Setup.ps1 -SolutionDir $(SolutionDir) -ProjectPath $(ProjectPath)
then in the script, you can always read the parameter like this...
param([string]$SolutionDir,
[string]$ProjectPath);
#Write-Host ($SolutionDir +" Call this script with following aruments");
#Write-Host ($ProjectPath +" Call this script with following aruments");

Resources