整个程序的要点:如何在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++执行我仍然告诉我,我已禁用脚本。
凡'command'实际上初始化? – Andrew
@Andrew在格式化发布堆栈溢出时意外删除了它,现在它被添加到正确的位置。它直接在'system(command.c_str())'调用之上。 – Bridger
在我的系统上,.ps1文件上命令行的默认操作是在记事本中打开它。 (即:如果我在命令行上运行命令内容,它将打开记事本,而不是运行脚本)这在Windows 7上。您需要将'powershell.exe'放在命令前面。 – ebyrob