PowerShell on Target Machines -TFS task, Security Warning persists after changing execution policy in remote server - powershell

I am pulling my hairs as I could not figure out what happens in powershell on target machine task (v1.0 and 2.0) in my release.
every time I run the task, it throws me the error:
AuthorizationManager check failed. ---> System.Management.Automation.PSSecurityException: AuthorizationManager check failed. ---> System.Management.Automation.Host.HostException: A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. If you trust this script, use the Unblock-File cmdlet to allow the script to run without this warning message. Do you want to run \\server\c$\Program Files\exampleps.ps1?
I understand this may relate to execution policy, so this is what I have done so far trying to solve the issue:
I went in the remote server and turned off IE enhanced security for admins, as the service account to run this script is admin
Shift+Right-click powershell to run as service account and changed execution policy from remotesigned to bypass. performed this action in both 32 and 64bit powershell. Bypass was set to local machine and current user
Added the \server\c$\Program Files\exampleps.ps1 to trusted site under internet options
I have tried to google and stackoverflow similar questions and these are what I found.
Update
After trying all 3 methods above, even when I try to run the ps script directly in console, the security warning still shows up. For some reasons, the bypass execution policy doesn't kick in. --I was able to run it in console without warnings, however, tfs task still failed
I am really frustrated and I hope anyone in the community can give me some guidance on the this.
Much appreciated.

Please try the following ways to see if they can work:
Use the "Bypass" Execution Policy Flag
PowerShell.exe -ExecutionPolicy Bypass -File \server\c$\Program Files\exampleps.ps1
Read Script from the File and Pipe to PowerShell Standard In
Get-Content \server\c$\Program Files\exampleps.ps1 | PowerShell.exe -noprofile -
Use the Invoke-Expression Command
Get-Content \server\c$\Program Files\exampleps.ps1 | Invoke-Expression
Use the "Unrestricted" Execution Policy Flag
PowerShell.exe -ExecutionPolicy UnRestricted -File \server\c$\Program Files\exampleps.ps1
There also are few other ways you can try. To view more details, you can reference to "15 Ways to Bypass the PowerShell Execution Policy".

Related

Task Scheduler - Powershell script not firing?

I've created numerous scripts in PowerShell that are working as intended if I execute them directly, however, when I try and setup a schedule to run these in Task Scheduler (to run with highest privileges) it doesn't seem to be running anything at all.
I'm running the following in my actions:
powershell.exe -ExecutionPolicy Bypass -File C:\PS\Mailboxes\CheckForwardingList.ps1
I'm getting a "Last Run Result" of 0x0 and the particular purpose of the above script is to generate a TXT file from EXO which it then mails out via SMTP and I've yet to receive any emails and I also don't see any TXT being generated in the folder where the script is located.
I do have two additional scripts setup which aren't running but once I've addressed the issue on the above this should quickly rectify the problems.
I like to test my PowerShell scripts from a command prompt first.
For example a script called C:\Tests\Test-PowerShellScriptsRunning.ps1 that only contains the following one liner helps me to test if scripts can run successfully on a machine
Write-Host -ForegroundColor Yellow "If you see this, then your script is running"
Next, I run this script from a command prompt, to get the syntax right in my scheduled task:
powershell.exe -nologo -file c:\Tests\Test-PowerShellScriptsRunning.ps1
Of course, you can add the -Executionpolicy bypass parameter, but I prefer to test the execution policy first.
However, as you are running a script that connects to ExchangeOnline, I suspect it has to do with the user you are running this task under. Does the script run if you run this task under your credentials or are the credentials stored on the system or in the script?
You might want to check this article to see how you can register an app and authenticate without storing your credentials on the machine to run the script unattended: App-only authentication for unattended scripts in the EXO V2 module

Allow Win 10 user to reset network adaptor via PS script without UAC

Firstly: I have found a number of questions answered that do everything but allow me to bypass UAC. I am IT for a small business, but it is not my primary responsibility.
I have two machines in my domain that on startup often fail to correctly connect to the domain network. Restarting the network adapter fixes the issue until the machine restarts. Unfortunately, one of the machines is used by a non-admin, and a technically illiterate one at that.
I hoped to use a powershell script to do this. Using this website, I created script and batch files to solve the issue. Since the computer only has one network adaptor, I went simple:
internet.ps1
Get-NetAdapter | Restart-NetAdapter
internet.cmd
#ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%internet.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";
Unfortunately, I don't fully understand the last command in the batch file. As such I struggle to research the command to pass some form of user credential. This environment is not very secure. But I don't want to give this user domain admin permissions generally, or provide them with some admin credentials which would end up on a sticky note. Either option is just inviting trouble from my older, technically illiterate colleagues. And going over to punch in credentials every day is time consuming.
I am looking for a script that cycles the network adaptor and provides the necessary credentials to make that change so a non-admin user can fix their domain and internet access without having admin credentials on a post-it note.
You could schedule a task using the Task Scheduler in Windows. When scheduling a task, you can specify credentials for the task to use when it runs. You can add a trigger for this task to have it run when the computer starts, or you can simply allow the user to manually start it.
If you decide to go this route, there is a check box you can check that runs the program with the highest possible privileges. The entire point of that last line is to start a new PowerShell window that runs as administrator so it actually has permission to restart the adapter. This means that you can get rid of almost your entire script, and just keep the part that actually restarts the adapter.
For example, when you go to create a new task in Task Scheduler, under the Actions tab, you can create a new action and enter the following:
Program/script:
PowerShell
Add arguments:
-Command "Get-NetAdapter | Restart-NetAdapter"
Note: I'm not sure if this is still the case, but in my past experience, sometimes it will try to run before Windows is fully loaded. If it doesn't seem to be doing anything on startup, you may need to add a delay to it. You can do this by running the Start-Sleep command. You can add it to the arguments field by doing the following:
-Command "Start-Sleep 5; Get-NetAdapter | Restart-NetAdapter"
Replace the number 5 with how many seconds you would like it to wait.

What is the potential threat if I "Unrestricted' the Execution Policy for Local Machine?

I installed oh-my-posh but the profile script for PowerShell was not working correctly. I found out PowerShell execution policy is restricted by default. I have changed the setting following Microsoft's About Execution Policy page.
What is the security threat of unrestricted execution?
The default is remotesigned now anyway. But anyone can override it by running "powershell -executionpolicy bypass". The purpose is to stop unknowingly running a PowerShell script, say from an email attachment, like the good old days of getting vbscripts in email.

Alternatives to fix PowerShell error "execution of scripts is disabled on this system"

I have a PowerShell script which is written by me. I try to run the PowerShell script as below;
PS C:\Documents and Settings\Administrator>c:\test\Test.ps1
So this is giving me an error saying:
File c:\test\Test.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
I found that setting Set-ExecutionPolicy Unrestricted will fix the error.
But my questions are;
What is this signing is about?
Can we fix this error without setting Set-ExecutionPolicy Unrestricted (doing a signing kind of a thing)? If so, how to do that?
Is there a security issue arise if I set Set-ExecutionPolicy Unrestricted in my web server?
Set-ExecutionPolicy causes a system wide change. Scripts are possible security vulnerabilities, which is why all script execution is disabled by default. One possibility is to launch the PowerShell process from the command line with an execution policy that is only in effect for that specific session. The command line would be something like:
> powershell.exe -ExecutionPolicy Unrestricted -File "c:\test\Test.ps1"
You could combine this with signing by leaving the default policy to Restricted and launching PowerShell with RemoteSigned or AllSigned policy when needed. Some additional information on the powershell.exe command line options is here.
If you did what the instructions told you to do you would have gotten a help page that would have told you exactly what you need to do.
get-help about_signing
In summary, the computer has no way to tell that whoever wrote the script was a trustworthy person, so by default it does not run any untrustworthy scripts. The two ways to fix this is either allow scripts from unknown sources (the solution you found out about by using Set-ExecutionPolicy Unrestricted) or by "signing" the script proving it came from a trustworthy source and has not been tampered with seance you got it from that source.
To sign your own code you will need a code signing certificate. Read that about_signing help and there is a section called CREATE A SELF-SIGNED CERTIFICATE that tells you how to do it.
After you have the certificate you need to sign your script. If you check that same help again there is a section called SIGN A SCRIPT that tells you how to do that too.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Since this question continues to attract responses that are either
refuted by the question body or don't address the actual problem,
please read this simple summary of what you need to know:
This is not a "Why won't my default installation of PowerShell run scripts?" question.
This is not a "Why won't my installation of PowerShell run scripts downloaded from the internet?" question.
The question is why the RemoteSigned execution policy is preventing script execution when it shouldn't.
RemoteSigned is the only execution policy I want to use. I am aware that other, less-restrictive policies are available. If
those policies were acceptable substitutes I would have just used them
instead and this question wouldn't exist.
The execution policy is already set to RemoteSigned. Changing it from RemoteSigned to RemoteSigned is not a solution.
The script file is created and stored locally.
The script file is not blocked. The script file was never blocked (see previous point).
The script file cannot be unblocked because there is nothing to unblock (see previous point).
The script file is (attempted to be) executed by an administrator.
Windows PowerShell is the only application involved. Not Windows PowerShell ISE nor Command Prompt nor any other tools or
editors are relevant.
The cause of the problem has already been identified (see accepted answer). After nearly 8 years, I think all other obvious
explanations, whether applicable or not, have been posted, too. If
you think otherwise then please read the question and existing
answers in their entirety before adding yours.
I am using Windows PowerShell 2.0 on 64-bit Windows 7 Professional. I have a script on my Desktop that causes the following error when I try to run it:
File C:\Users\UserName\Desktop\Script.ps1 cannot be loaded. The file C:\Users\UserName\Desktop\Script.ps1 is not digitally signed. The script will not execute on the system. Please see "get-help about_signing" for more details..
At line:1 char:54
+ C:\Users\UserName\Desktop\TestGetWindowsUpdateLog.ps1 <<<<
+ CategoryInfo : NotSpecified: (:) [], PSSecurityException
+ FullyQualifiedErrorId : RuntimeException
I am both a domain administrator and a local administrator, and if I run Get-ExecutionPolicy -List, I can see that the Group Policy Object I created to configure PowerShell is correctly applying the RemoteSigned execution policy at the machine level:
Scope ExecutionPolicy
----- ---------------
MachinePolicy RemoteSigned
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine Undefined
I created the script myself in Notepad, and used the Sysinternals' streams utility and the file Properties dialog to confirm that the script is not being treated as having come from the internet. If I copy the script to a network share on a domain server, then it's allowed to execute. If I run Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine then the local script is still not allowed to execute, which makes sense since the execution policy at the MachinePolicy scope will take precedence.
As documented by about_Execution_Policies(current; at time of question), the RemoteSigned policy means:
Scripts can run.
Requires a digital signature from a trusted publisher on scripts and configuration files that are downloaded from the Internet
(including e-mail and instant messaging programs).
Does not require digital signatures on scripts that you have run and that you have written on the local computer (not downloaded from
the Internet).
Risks running unsigned scripts from sources other than the Internet and signed, but malicious, scripts.
My script is not signed, but since it is both created and executed locally, it should satisfy the third bullet point above. Therefore...
Why is my script not being allowed to run?
Why does PowerShell complain that my script "is not digitally signed" when that requirement should only apply to files from the Internet?
Why does PowerShell no longer care about the script not being signed when it's run from a network share?
Some things to check:
Can you change to unrestricted?
Set-ExecutionPolicy Unrestricted
Is the group policy set?
Computer Configuration\Administrative Templates\Windows Components\Windows PowerShell
User Configuration\Administrative Templates\Windows Components\Windows PowerShell
Also, how are you calling Script.ps1?
Does this allow it to run?
powershell.exe -executionpolicy bypass -file .\Script.ps1
Is the file being blocked? I had the same issue and was able to resolve it by right clicking the .PS1 file, Properties and choosing Unblock.
When you run a .ps1 PowerShell script you might get the message saying “.ps1 is not digitally signed. The script will not execute on the system.”
To fix it you have to run the command below to run Set-ExecutionPolicy and change the Execution Policy setting.
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
I have found out when running a PS1 file for a Mapped drive to Dropbox that I'm always getting this error. When opening up properties for the PS1 there is no "Unblock".
The only thing that work for me is
powershell.exe -executionpolicy bypass -file .\Script.ps1
I finally tracked this down to .NET Code Access Security. I have some internally-developed binary modules that are stored on and executed from a network share. To get .NET 2.0/PowerShell 2.0 to load them, I had added a URL rule to the Intranet code group to trust that directory:
PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -listgroups
Microsoft (R) .NET Framework CasPol 2.0.50727.5420
Copyright (c) Microsoft Corporation. All rights reserved.
Security is ON
Execution checking is ON
Policy change prompt is ON
Level = Machine
Code Groups:
1. All code: Nothing
1.1. Zone - MyComputer: FullTrust
1.1.1. StrongName - ...: FullTrust
1.1.2. StrongName - ...: FullTrust
1.2. Zone - Intranet: LocalIntranet
1.2.1. All code: Same site Web
1.2.2. All code: Same directory FileIO - 'Read, PathDiscovery'
1.2.3. Url - file://Server/Share/Directory/WindowsPowerShell/Modules/*: FullTrust
1.3. Zone - Internet: Internet
1.3.1. All code: Same site Web
1.4. Zone - Untrusted: Nothing
1.5. Zone - Trusted: Internet
1.5.1. All code: Same site Web
Note that, depending on which versions of .NET are installed and whether it's 32- or 64-bit Windows, caspol.exe can exist in the following locations, each with their own security configuration (security.config):
$Env:SystemRoot\Microsoft.NET\Framework\v2.0.50727\
$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\
$Env:SystemRoot\Microsoft.NET\Framework\v4.0.30319\
$Env:SystemRoot\Microsoft.NET\Framework64\v4.0.30319\
After deleting group 1.2.3....
PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -remgroup 1.2.3.
Microsoft (R) .NET Framework CasPol 2.0.50727.9136
Copyright (c) Microsoft Corporation. All rights reserved.
The operation you are performing will alter security policy.
Are you sure you want to perform this operation? (yes/no)
yes
Removed code group from the Machine level.
Success
...I am left with the default CAS configuration and local scripts now work again. It's been a while since I've tinkered with CAS, and I'm not sure why my rule would seem to interfere with those granting FullTrust to MyComputer, but since CAS is deprecated as of .NET 4.0 (on which PowerShell 3.0 is based), I guess it's a moot point now.
If the file is copied from a network location, that is, another computer, Windows might have blocked that file. Right click on the file and click on the unblock button and see if it works.
What works for me was right-click on the .ps1 file and then properties. Click the "UNBLOCK" button. Works great fir me after spending hours trying to change the policies.
Select your terminal Command prompt instead of Power shell. That should work.
This is an IDE issue. Change the setting in the PowerShell GUI. Go to the Tools tab and select Options, and then Debugging options. Then check the box Turn off requirement for scripts to be signed. Done.
Please make a backup for the script.bs1 file
What works for me was deleting the script.bs1 file and running the execution command.
I was having the same issue and fixed it by changing the default program to open .ps1 files to PowerShell. It was set to Notepad.
Try running the Powershell GUI as Administrator
This occurs due to Powershell execution policy is set to restricted by default which prevents execution PowerShell scripts and protects from running malicious scripts.
You can change execution scope for specific scope by running the following command
Set-ExecutionPolicy -Scope Process
Run below 2 commands in PowerShell window
Set-ExecutionPolicy unrestricted
Unblock-File -Path D:\PowerShell\Script.ps1