SaltStack executing unsigned powershell scripts on windows - windows

Is there a way to pass switch operators to the powershell prompt that is created to execute scripts. Essentially I have a state file which executes a powershell script:
function1:
cmd.script:
- source: salt://utils/scripts/function1.ps1
- shell: "powershell"
- env: "-ExecutionPolicy bypass"
But this doesn't work.
Because a dirty solution is to run the script via cmd:
%windir%\System32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -executionpolicy Bypass -File
Any way to set the executionpolicy flag in the state file itself?
Thanks!

try using a file.managed to deploy the sls that holds the .exe and then use and cmd.run instead of cmd.script for the execution

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.

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).

Executing cmd files in terraforms

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",

Unable to execute PowerShell Script

How can I get my PowerShell script to execute?
When I run my script I get the error:
File cannot be loaded because the execution of scripts is disabled on this system
Can you help me to get my script to run?
set-executionpolicy unrestricted
#Set-ExecutionPolicy RemoteSigned
$target=[IO.File]::ReadAllText(".\usermenuTest1.4d")
$output=[IO.File]::ReadAllText(".\usermenuTest2.4d")
($output -replace $target) | Set-Content "usermenuTest2.4d.new"
Start-Sleep -s 10
This Technet article suggests trying Get-ExecutionPolicy to check your script execution policy, and then set it to AllSigned or Unrestricted. Also, make sure you run the script like this ".\scriptname.ps1"

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