我想在c#中执行以下命令:
@echo off
PowerShell "ForEach($v in (Get-Command -Name "Set-ProcessMitigation").Parameters["Disable"].Attributes.ValidValues){Set-ProcessMitigation -System -Disable $v.ToString() -ErrorAction SilentlyContinue}"
pause
我把它放在CMD文件中,并运行它:
Process.Start(CMDFilePath);
但是出现错误:
C:UsersNew-hwidDesktopDebug2>PowerShell "ForEach($v in (Get-Command -Name "Set-ProcessMitigation").Parameters["Disable"].Attributes.ValidValues){Set-ProcessMitigation -System -Disable $v.ToString() -ErrorAction SilentlyContinue}"
Get-Command : The term 'Set-ProcessMitigation' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:16
+ ForEach($v in (Get-Command -Name "Set-ProcessMitigation").Parameters[ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Set-ProcessMitigation:String) [Get-Command], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand
Cannot index into a null array.
At line:1 char:15
+ ... rEach($v in (Get-Command -Name "Set-ProcessMitigation").Parameters["D ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
当我打开cmd文件正常工作,但当我运行它通过Process.Start(…)这个错误发生,我的操作系统是windows 10 64位,如何运行cmd文件没有错误?由于
,您看到的问题是由于文件系统重定向,这是因为您在64位操作系统上以32位运行程序。因此,您正在执行%windir%SysWOW64SystemPropertiesProtection.exe(例如:C:WindowsSysWOW64SystemPropertiesProtection.exe)。所以我添加In app.manifest,并替换
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
并修改代码以使用powershell:
public static void OpenPowerShell(string Command)
{
try
{
string filename = System.IO.Path.Combine(Environment.GetEnvironmentVariable("windir"), "System32", "WindowsPowerShell","v1.0","powershell.exe");
//environment variable windir has the same value as SystemRoot
//use 'Sysnative' to access 64-bit files (in System32) if program is running as 32-bit process
//use 'SysWow64' to access 32-bit files on 64-bit OS
if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess)
{
//filename = System.IO.Path.Combine(Environment.GetEnvironmentVariable("windir"), "SysNative", "PowerShell.exe");
filename =System.IO.Path.Combine(Environment.GetEnvironmentVariable("windir"), "SysNative", "WindowsPowerShell", "v1.0", "powershell.exe");
}
ProcessStartInfo startInfo = new ProcessStartInfo(filename);
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(filename);
startInfo.Arguments = "-NoExit "+Command ;
Process.Start(startInfo);
}
catch (Exception ex)
{
FRM_MSG f = new FRM_MSG();
f.ShowDLG(" ",
ex.Message + "n" + ex.StackTrace.ToString(),
FRM_MSG.MSGIcon.Error,
FRM_MSG.BTNS.One,
new string[] { "Ok" });
throw ex;
}
}