2016-06-23 753 views
0

整个程序的要点:如何在C++中执行powershell脚本?

传入用户名和密码以提升用户的权限,以便如果他们不是允许访问受保护文件夹的用户,他们仍然可以打开并查看它。用户名在其中包含一个关键所在文件夹<map>映射,它会搜索自己的文件夹,然后使用用户名和密码通过它一起做下面的PowerShell脚本真正海拔:

param(
    [string]$username, 
    [string]$password, 
    [string]$folder 
    ) 
    Write-Host $username $password $folder 
  
    $securePassword = ConvertTo-SecureString $password -AsPlainText -Force 
    $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword 
    Start-Process T:\folders\Explorer++\Explorer++.exe \\foo\boo\fileserver\allusers\specialUsers\$folder -Credential $credential 

我传递通过使用System()将用户名,密码和文件夹放入此脚本中。

C++代码来执行脚本,并传递变量是这样的:

String^ runCommand(string folder, string username, string password) 
    { 
     string explorerpp = "\\\\foo\\boo\\examplefolder\\Explorer++\\EXPLORER++.exe"; 
     string space = " "; 
     string quote = "\""; 
     string start = "C:\\ProgramData\\Microsoft\Windows\\Start Menu\\Programs\\System Tools\\Windows Powershell"; 
     string open = "open"; 
     string domain = "domain\\"; 
     string pwShell = "S:\\foo\\boo\\locationofscript\\pwShell.ps1 "; 
     string parentFolder = """\\\\foo\\boo\\folder\\Parent_folder\\special_users \\"""; 
     string path = parentFolder + folder; 
     String^ dir = gcnew String(path.c_str()); 
     string param = quote + domain+ username + quote + space + quote + password + quote + space + quote + folder + quote; 
     string command = "start powershell.exe" + space + pwShell + param;   
     system(command.c_str()); 
     return dir; 
    } 

注:该代码看起来它的方式,由于调试的巨量,我明白,我可能使用很多不需要的变量。

当通过System()_popen运行时,它会在命令提示符下打开包含脚本或错误的.txt文件。

如果我把string command的值是什么并粘贴到命令提示符中,我会让脚本正常运行,然后打开正确的文件夹。

当命令提示符正确执行一切操作时,C++不允许脚本正确执行的问题是什么?

BIG编辑:

我得到的错误是C:\OurProj\pwShell.ps1 : File C:\OurProj\pwshell.ps1 cannot be loaded because running scripts is disabled on this system.

我也只是说说的IT人,我能够运行这个系统上的脚本,试图使一切地方,如果我通过它运行的PowerShell运行脚本。

编辑2:

我已经改变了执行政策为已建议,并不会返回RemoteSigned,但是当代码用C++执行我仍然告诉我,我已禁用脚本。

+3

凡'command'实际上初始化? – Andrew

+0

@Andrew在格式化发布堆栈溢出时意外删除了它,现在它被添加到正确的位置。它直接在'system(command.c_str())'调用之上。 – Bridger

+0

在我的系统上,.ps1文件上命令行的默认操作是在记事本中打开它。 (即:如果我在命令行上运行命令内容,它将打开记事本,而不是运行脚本)这在Windows 7上。您需要将'powershell.exe'放在命令前面。 – ebyrob

回答

0

在一个环境中,您可以执行未签名的电源shell脚本,但在另一个环境中则不能。 64位和32位每个都有一个独立的电源外壳执行策略。很可能你在64位操作系统上运行并构建一个32位C++程序(Visual Studio的默认设置)。

您可以通过以下步骤得到一个32位电源外壳:

在开始屏幕上,类型的Windows PowerShell(x86)的。以管理员身份运行。

下运行命令:

Set-ExecutionPolicy RemoteSigned 

现在,你应该能够在您的计算机上运行,​​从32位无符号的环境本地电源的脚本文件。

从开始菜单,你可以得到要么PowerShell的环境中,一定相同的执行策略是使用命令两个设置:

Get-ExecutionPolicy 
+0

我已经在PowerShell中以管理员身份运行该命令,并且在获取执行策略时返回RemoteSigned。 但是,当我试图执行我的代码时,我仍然认为此机器上的运行脚本被禁用为安全风险。当我通过C++调用它时,我获得了不同的powershell吗? – Bridger

+0

@BridgerWinter你需要为32和64位环境设置它。尝试从应用程序内部设置,如果没有其他工作。 – ebyrob