I have been running my code for past few months by doing this -
Set-ExecutionPolicy Unrestricted
But, something weird is happening and I am getting this error always -
Windows PowerShell updated your execution policy successfully, but the
setting is overridden by a policy defined at a more specific scope.
Due to the override, your shell will retain its current effective
execution policy of "Unrestricted". Type "Get-ExecutionPolicy -List"
to view your execution policy settings. For more information, please
see "Get-Help Set-ExecutionPolicy."
I have referred these links but no luck -
http://blogs.msdn.com/b/pasen/archive/2011/12/07/set-executionpolicy-windows-powershell-updated-your-execution-policy-successfully-but-the-setting-is-overridden-by-a-policy-defined-at-a-more-specific-scope.aspx
http://blog.whatsupduck.net/2010/09/issues-with-configuring-powershell.html
http://www.howtogeek.com/106273/how-to-allow-the-execution-of-powershell-scripts-on-windows-7/
I am loading the Powershell using C# on a 64-bit Windows 7 via a 32-Bit Winforms Application using .Net 4.0
What is the exact setting which I need to do such that I do not get this error on any system ? [Everything was working fine]. What should these values be on any system such that I am able to call Powershell from C# seamlessly -
Get-ExecutionPolicy -List
MachinePolicy
UserPolicy
Process
CurrentUser
LocalMachine
You should see output like this from Get-ExecutionPolicy -List:
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine RemoteSigned
Once you see the scope that has the undesired setting, you can reset it like so:
Set-ExecutionPolicy Undefined -Scope <scope-name>
That is assuming you have permission to do so.
Related
I have a question regarding Execution Policies on Windows Server 2022.
I have a new "just out of the box" Windows Server 2022 box.
If I run in Visual Studio Code:
Get-ExecutionPolicy -List
I get the following results:
Scope ExecutionPolicy
MachinePolicy Undefined
UserPolicy Undefined
Process RemoteSigned
CurrentUser Undefined
LocalMachine Restricted
If I run the same command through a .NetCore console app via:
var psInstance = PowerShell.Create();
psInstance.AddScript("Get-ExecutionPolicy -List");
var output = psInstance.Invoke();
I get the following results:
Scope ExecutionPolicy
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine Undefined
Why are the Execution Policies different between the 2?
Are there inherent differences between the 2 flavours of Powershell that I am unaware of?
I'm trying to run a basic powershell script in a c# application, but I can't seem to get it to run. I've tried this code with and without the added execution policy code in the pipeline creation and have gotten the same results.
static void Main(string[] args)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned");
pipeline.Commands.Add(#"C:\Users\Bob\Desktop\testScript.ps1");
// Execute PowerShell script
var results = pipeline.Invoke();
}
The error I receive is this:
System.Management.Automation.PSSecurityException: 'File C:\Users\Bob\Desktop\testScript.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.'
When I run "get-executionpolicy -list", my execution policy seems to be fine.
Normally, the persistently configured script execution policy applies to PowerShell SDK-based projects such as yours, too.
While your Get-ExecutionPolicy -List output implies that RemoteSigned is the effective policy (as reported when you omit -List), the color of your screenshots suggest that you were asking for Windows PowerShell's policy, which is separate from the execution policy for the cross-platform, install-on demand PowerShell (Core) v6+ edition.
Therefore, your inability to execute a local script - which RemoteSigned should allow - can have one of two causes:
If you project is based on the SDK for PowerShell (Core) v6+ (via the Microsoft.PowerShell.SDK NuGet package), you'd have to consult - and possibly modify - its effective execution policy (run pwsh -c Get-ExecutionPolicy to see the policy in effect)
If you don't actually have PowerShell (Core) 6+ itself installed (i.e if you're only using its SDK), use the solution in the bottom section - which may be preferable anyway.
As Mathias points out in a comment, another possible reason is that your local script may have been downloaded from the web, via a web browser, in which case it is considered a remote file for the purpose of the execution policy. Passing its file path to Unblock-File as a one-time action should fix the problem.
Taking a step back:
If you trust the local script to invoke, you can bypass the execution policy for your application only, by configuring your PowerShell SDK session accordingly - see this answer.
I have a C# testing project that uses the Microsoft.PowerShell.SDK NuGet package. I use it to run a cURL command that I can't seem to get to work with an HttpClient (details on that here if you are interested).
It works great, except when I run as a weak user using RunImpersonated. Then I get the following exception:
System.TypeInitializationException : The type initializer for 'Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry' threw an exception.
With an inner exception of:
System.UnauthorizedAccessException : Access to the path 'CreateUniqueUserId' is denied.
I am not sure why my cURL powershell command needs to use Application Insights and I would like to turn it off if possible.
Is it possible to turn off Application Insights with the Powershell NuGet?
From the about_Telemetry help file:
To opt-out of this telemetry, set the environment variable POWERSHELL_TELEMETRY_OPTOUT to true, yes, or 1.
So running this when your application starts should do the trick:
Environment.SetEnvironmentVariable("POWERSHELL_TELEMETRY_OPTOUT", "1");
When I try to load a COM visible C#.net assembly from a Delphi application, "The class is not configured to support Elevated activation" error pops up on windows server 2012.
Is there a way to configure it to support elevated activation programmatically ?
Currently to avoid, privilege level is set to "Run as administrator".
That's the CO_E_ELEVATION_DISABLED error. It may happen if the class is not properly registered for elevation in the registry. You can find how to register it in MSDN:
The COM Elevation Moniker
The COM class must also be annotated as LUA-Enabled. This requires the following registry entry:
HKEY_LOCAL_MACHINE\Software\Classes\CLSID
{CLSID}
Elevation
Enabled = 1
If this entry is missing, then the activation returns the error CO_E_ELEVATION_DISABLED.
Note that these entries must exist in the HKEY_LOCAL_MACHINE hive, not the HKEY_CURRENT_USER or HKEY_USERS hive. This prevents users from elevating COM classes that they did not also have the privileges to register.
More info is in this blog post:
Local elevation points in Windows and Delphi
The scenario:
I have a Java based installer.
The Java based installer calls a C# program, whose job is to create a shortcut.
The shortcut location depends on if the installer is running as administrator or as a regular user. When running as admin, I'm trying to create a shortcut to "%ALLUSERSPROFILE%\Desktop", else I write to "%USERPROFILE%\Desktop".
My impression is that the issue seems to be a loss of administrative privilege when my Java program calls my C# shortcut maker program.
Notes:
I run my Java based installer as administrator (right click, run as administrator).
I'm able to verify the installer is running with administrator privileged because I can read registry keys that require administrative privilege.
I'm calling my C# program via 'Process process = Runtime.getRuntime().exec(command);'
When running the command manually through an administrative command prompt, the command works fine. (When outputting to "%ALLUSERSPROFILE%\Desktop")
When running the the same command manually, from a normal command prompt, I get System.UnauthorizedAccessException. (Which is to be expected). The program crashes in a similar was that it does when run from the installer.
The Exception:
Unhandled Exception: System.UnauthorizedAccessException: Access is
denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) at
IWshRuntimeLibrary.IWshShortcut.Save()
Any thoughts on what I'm missing? The installer needs to be flexible to run as both a normal user and as an administrator. How can I ensure this behavior?
Update 1
I attached a debugger to the C# program at runtime. It is throwing a:
DirectoryNoFoundException was unhandled
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)
I added "mkdir" commands before my shortcutmaker commands. The mkdir commands, just ensure that the directories exist before trying to write to them.
Rebuilt the installer, ran it and when trying to mkdir "%ALLUSERSPROFILE%\Desktop", java throws an exception of
java.io.IOException: Cannot run program "mkdir": CreateProcess error=2, The system cannot find the file specified
java.io.IOException: Cannot run program "mkdir": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
At this point, it looks like my process isn't getting admin access
Process process = Runtime.getRuntime().exec(command);
I'm going to see if I can find anything else.
Update 2
The following gave me some info that I tried: Enterprise Logging not translating environment variables in XML Trace Listener fileName specification
It suggested that %ALLUSERSPROFILE% was not getting translated.
Instead of %ALLUSERSPROFILE%, I got the environment variable values via:
String allUsersProfile = System.getenv("ALLUSERSPROFILE");
String userProfile = System.getenv("USERPROFILE");
I was then able to supply the actual values to the C# program. But I'm still having issues.
From a admin console I can navigate to "c:\ProgramData\Start Menu", but if I run "explorer" with administrative priviledges, I can navigate to "c:\ProgramData" but not see anything past that... Through some looking, I found out that "c:\ProgramData\Start Menu" is a protected operating system file. So I turned on the setting to see it. So now I can see it, but not go into it.
Using system internals, I elevated an explorer.exe to "system" access and still can't go into the folder (System internal elevation reference: http://verbalprocessor.com/2007/12/05/running-a-cmd-prompt-as-local-system/)
I right clicked on the folder and checked out the security tab. It looks like even my "System" user has limited access. I find this a bit baffling, that I can run the command from an admin command prompt that will write the shortcut to the desktop, but going through this other process I cannot... I also find the access to be a bit inconsistent.