Execute PowerShell script from network folder - powershell

I'm developing a quite large automatic build in TFS2017 with a local VSTS build machine. My custom tasks will be mostly in PowerShell.
The inline PowerShell task handles only 500 or so characters and is too small to use for most tasks. Right now I'm editing my Powershell script, check it in, test run, read log for errors, correct, check in again and so on.
This is a bit tedious and I wonder if there are any options. I would like to avoid checking in each change in the script. Are there any options like executing my Powershell tasks from a network location during development of the build process?

You can specify UNC file path in PowerShell task.
You also can store the script files in a server (e.g. FTP), then download the file to working directory during build through PowerShell or others task.
On the other hand, there is PowerShell on Target machines task that can execute PowerShell scripts on remote machines.

You can use dot sourcing with your UNC path:
PS> . \\server\path\to\your\scriptmcscript.ps1
or use the invocation operator:
& \\server\path\to\your\scriptmcscript.ps1

You can use UNC path for the file with Powershell Task.
Or you could use the Powershell on target machine to run it.
But be careful about your choice. You have to keep in mind that who is running your script is the build/deployment agent. So while you are running it in your corporate network everything will be fine, because your agent can see your UNC path.
The moment you use that agent on a machine outside your network you will have to think about another solution, which may include saving your powershell file to a repo like Git or TFVC and then download the file to the local computer where you are running the agent.

This is the only way that works for me, call PowerShell from a .batch script with execution policy set to bypass (scope - process only)
-NonInteractive = do not prompt for confirm
-NoProfile = run under system context
powershell.exe -NoProfile -ExecutionPolicy Bypass -NonInteractive -Command C:\Users\User\Script.ps1

Related

PowerShell execution policy subverted by a powershell.exe parameter

In PowerShell, is there an advantage to a restrictive execution policy besides trying to control which script files can run?
By default, PowerShell scripts are not allowed to run, but it seems like if a malicious party wants to run PowerShell script they can just bootstrap into it using a BAT file that calls PowerShell with the -ExecutionPolicy parameter set to "bypass".
Am I missing something, or does this defeat the execution policy mechanism? Why sign scripts (which looks like quite a hassle) when you can just make the execution policy less restrictive?
Below is a BAT script I wrote that creates an unsigned .ps1 file and runs it. It works on a machine with the execution policy of Restricted, which should disallow scripts. UAC is on and no elevation prompt is shown. It even dials out to the Internet and gets the latest headline of the "Hey, Scripting Guy!" blog.
echo write-host "`r`nPowershell code running on $(hostname).`r`n`r`nHere's the latest headline from the 'Hey, Scripting Guy!' blog: '$(([xml](New-Object Net.WebClient).DownloadString("http://blogs.technet.com/b/heyscriptingguy/atom.aspx")).feed.entry[0].title)'.`r`n`r`nPress Enter to close.`r`n"; read-host > script.ps1
powershell -ExecutionPolicy bypass -Command .\script.ps1
The execution policy will prevent someone from modifying an existing script that's being run by someone else, or as an automated process (e.g. a scheduled task). From a security standpoint, using that .bat file is no different that compiling code to do the same thing into an .exe.
Also, the -ExecutionPolicy parameter doesn't work when the execution policy is set via local/group policy on the machine (per Ansgar's comment on the question).
The default PowerShell execution policy of disallowing scripts is useful for little more than preventing accidental invocations of the script. It can be trivially violated, even on earlier versions of powershell which didn't have the per instance parameter, by doing the following
Open any script you want to run in notepad
Copy the contents to the clipboard
Paste the clipboard to an instance of powershell
Anyone who really wants to run a script can do so using this or a variety of other mechanisms. It's only really useful for preventing unintentional execution of scripts

Unsigned Powershell scripts from HTA

I have created the below batch file and it works flawlessly as long as I run it manually.
However, if I run the .bat file from a HTA application, PowerShell says that he can't run the script because it is not signed/not trusted: "File cannot be loaded because the execution of scripts is disabled on this system".
Is there any fix/workaround for this without having to actually sign the script?
Batch file:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". '%cd%\temp_oooscript\wrapper.ps1'"
Thank you.
This problem is caused by Windows Execution-policy setting.
To check what policy is running type this command:
Get-ExecutionPolicy
You policy should be one of these 4:
Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
AllSigned - Only scripts signed by a trusted publisher can be run.
RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
Unrestricted - No restrictions; all Windows PowerShell scripts can be run.
Not sure you are running remotely or locally.
If locally then your policy might be "all signed".
If remotely then your policy might be "RemoteSigned" or "all signed".
To fix the problem, 2 ways:
Adjust the policy setting. Don't make it too loose like unrestricted (I assume it is a medium to large production environment). The same reason if this is true I don't pro the bypass way by Graimer.
If this is a lab or small and trusted env then "unrestricted" can be an option. Or the bypass method proposed by Graimer.
Get the script signed.You need to run some "makecert" stuff to generate the signature and then copy it to the machine. The following link might help:
http://www.hanselman.com/blog/SigningPowerShellScripts.aspx
Try setting the exeuctionpolicy for powershell to bypass when executing it. Like this:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -executionpolicy bypass -command ". '%cd%\temp_oooscript\wrapper.ps1'"
The reason you're seing this is most likely because the HTA application is run as a 32 bit software, while your os is 64bit. Because the HTA app is running as 32 bit, it uses the powershell in C:\windows\syswow64\windowspowershell... (even though you specified system32 in your code). The execution policy there has is it's own setting, seperate from what you have in your normal 64-bit powershell.
The best way to fix it would be to sign the script using the PKI infrastructure in your enviroment. As a workaround you can use the code I provided above. The advantage for the workaround above is that the executionpolicy is only set to bypass ("disabled") for the PROCESS, and not as a default setting that could compromise security.
YES!! Found the bloody solution!! the HTA file needs to be run from through the mshta.exe from system32 instead of SysWOW64. Woohoo!!!

Run a remote powershell script from a batch file

I want to have my batch file run a remote powerhell script.
I have Powershell \ip\Myscript.ps1
But it asks me for do i want to run this remote script.
I want to bypass this. with a -confirm:$false
How can i use that in a batch.
You got a few options here.
Copy the .ps1 file to a local directory and then call it via
Powershell. An ugly hack, but sometimes necessary if Execution Policy must not be changed.
Sign the .ps1 file. A huge pain in the backside.
Tell Powershell not to worry about Execytion Policy. The easy and dangerous way: powershell -executionpolicy unrestricted \\server\share\someScript.ps1.

Powershell script works when remoted in, but not as Azure startup task

I have an powershell script saved in a .cmd file that downloads a file from the web and then unzips it. My azure web role executes it upon startup. This is the script:
powershell -ExecutionPolicy Bypass -c $(New-Object Net.WebClient).DownloadFile('URL.zip', 'FILE.zip') ;
(New-Object -com shell.application).namespace('c:\FOLDER').Copyhere((New-Object -com shell.application).namespace('FILE.zip').items())
When I run the script via Azure startup tasks:
The first part of the script works. The file is downloaded. The second part of the script which unzips does not run.
When I run the script via the command line when remoted into the VM:
The entire script runs.
I therefore know this is not a syntax error. The only difference I can think of between the two cases above is a permissions issue. But, I am running powershell with -ExecutionPolicy set to Bypass, which is the highest permission level. Anybody have any ideas? Thanks!
Change the command so that the output of the command is dumped into a file. Something like this should work
<YOUR_COMMAND> > out.log 2> err.log
Run the task again and checkout the output in the logs.
Also, you are using relative paths rather than absolute ones. The scheduled task probably run with the windows system folder as its working directory, so you may be getting a permissions error from that. Try using an absolute path to a directory you created.

How to get Hudson CI to execute a Powershell script?

I'm using Hudson version 1.324 for CI and have a couple of issues:
Environment:
Windows Server 2008
Powershell v1.0
Hudson 1.324 running as a service
Hudson Powershell Plugin installed
Psake (aka. "Powershell Make/Rake" available from Github) 0.23
(All current/latest versions as of this initial post)
I have a Powershell (PS) script that works to compile, run NUnit tests, and if successful, create a 7z file of the output. The PS script works from the command line, on both my local development box as well as the CI server where Hudson is installed.
1) Execution Policy with Powershell.
I initially ran a PS console on the server, ran Set-ExecutionPolicy Unrestricted, which allows any script to be run. (Yes, I realize the security concerns here, I'm trying to get something to work and Unrestricted should remove the security issues so I can focus on other problems.)
[This worked, and allowed me to fire off the PS build script from Hudson yesterday. I then encountered another problem, but we'll discuss that more in item #2.]
Once Hudson could fire off a PS script, it complained with the following error:
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell "&
'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'" The term
'OzSystems.Tools\psake\psake.ps1' is not recognized as a cmdlet, funct
ion, operable program, or script file. Verify the term and try again.
At line:1 char:2
+ & <<<< 'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'"
Using the same command line, I am able to successfully execute the PS script from the command line manually. However Hudson is unable to get PS to do the same. After looking at additional PS documentation I also tried this:
"& 'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'"
and got a similar error. There does not appear to be any documentation for the Powershell plugin for Hudson. I've gone through all the Powershell plugin files and don't see anything that's configurable. I can't find a log file for Hudson to get additional information.
Can anyone help me past this?
2) I spent yesterday wrestling with #1. I came in this AM and tried to dig in again, after restarting the Hudson server/service, and now it appears that the ExecutionPolicy has been reset to Restricted. I did what worked yesterday, opened a PS console and Set-ExecutionPolicy to Unrestricted. It shows Unrestricted in the PS console, but Hudson says that it doesn't have rights to execution PS scripts. I reopened a new PS console and confirmed that the ExecutionPolicy is still Unrestriced -- it is. But Hudson evidently is not aware of this change. Restarting Hudson service again does not change Hudson's view of the policy.
Does anyone know what's going on here?
Thanks, Derek
I just ran into the problem of running powershell scripts in hudson. The thing is that you are running a 32-bit process of Java, and you've configured Hudson for 64-bit but not for 32-bit. See the following thread we created at microsoft.
http://social.technet.microsoft.com/Forums/en/winserverpowershell/thread/a9c08f7e-c557-46eb-b8a6-a19ba457e26d
If your lazy.
1. Start powershell (x86) from the start menu as administrator
2. Set the execution policy to remotesigned
Run this once and your homefree.
When Running PowerShell from a scheduled task or Hudson you want to:
Specify the -ExecutionPolicy parameter (in your case: -Ex Unrestricted)
Specify that command using either -Command { ... } or -File NOT BOTH and not without specifying which you mean.
Try this (except that I don't recommend using relative paths):
PowerShell.exe -Ex Unrestricted -Command "C:\Path\To\OzSystems.Tools\psake\psake.ps1" ".\oz-build.ps1"
To be clear, this will work too:
PowerShell.exe -Ex Unrestricted -Command "&{&'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'}"
The first string after -Command is interpreted as THE NAME OF A COMMAND, and every parameter after that is just passed to that command as a parameter. The string is NOT a script, it's the name of a command (in this case, a script file)... you cannot put "&'OzSystems.Tools\psake\psake.ps1'" but you can put "OzSystems.Tools\psake\psake.ps1" even if it has spaces.
To quote from the help (run PowerShell -?) emphasis mine:
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned
to the parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
I have been having the same problems as you (as you've seen from my comments). I have given up on the powershell launcher and moved to running things using the batch file launcher. Even though I had set the system to unrestricted that setting didn't seem to matter to hudson's launcher. I don't know if it runs in some other context or something, even adding things to the global profile.ps1 didn't seem to help. What I ended up doing was running
powershell " set-executionpolicy Unrestricted; & 'somefile.ps1'"
which does what I need, although it isn't ideal. I've e-mailed the plugin author about this and will update.
For question #1, try this (assuming you are using PowerShell 2.0):
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell -executionPolicy Unrestricted -file OzSystems.Tools\psake\psake.ps1 C:\{path}\oz-build.ps1"
You are using "." for the path to oz-build.ps1. I suspect you will need to provide the full path to your oz-build.ps1 file to make this work. Unless the infrastructure that executes the command above happens to have the current dir set correctly. And even if it is set correctly for the "process", that only matters to .NET/Win32 API calls and not to PowerShell cmdlets. Current dir in PowerShell is tracked differently than the process's current dir because PowerShell can have multiple runspaces running simultaneously. That sort of global, mutable value doesn't work in this concurrent scenario.
As for question #2, what account does the Hudson service run under? Make sure that account has executed Set-ExecutionPolicy RemoteSigned (or unrestricted).
I just got through this exact problem. What a pain!
If you are running a 32-bit JVM on a 64-bit Windows, make sure that you set the execution policy for the 32-bit Powershell interface. I found my 32 bit executable here:
C:\Windows\syswow64\Windowspowershell\v1.0\powerhsell.exe
The 32- and 64-bit Powershell environments are completely distinct so setting the execution policy in one has no effect on the other.