gpt4 book ai didi

c - 如果从 C 程序执行,Powershell 脚本不起作用?

转载 作者:太空狗 更新时间:2023-10-29 15:33:24 25 4
gpt4 key购买 nike

我有一个 powershell 脚本,如果我从管理员 powershell 运行它,它可以正常工作。但是,如果我在 c 程序中调用 powershell 脚本,以管理员身份运行,使用 system() 函数,它的某些部分不起作用。更具体地说,复制 unattend.xml 和 sysprep.exe 命令。我已经发布了 powershell 脚本和 c 程序脚本。我怎样才能让它发挥作用?

POWERSHELL 脚本:

#Set working directory to scripts location.
$scriptpath = $MyInvocation.MyCommand.Path
$Switcheroo = Split-Path $scriptpath
Set-Location $Switcheroo
#Set error options
$Error.clear()
$ErrorActionPreference = “Inquire”

Write-Host "Running part 2."
#1
& "DISKPART" /s $Switcheroo\DskPrtRmv.txt
TIMEOUT /T 3

#2
if ($? -eq "True")
{
Copy-Item $Switcheroo\unattend.xml $env:windir\System32\Sysprep
TIMEOUT /T 3

#3
if ($? -eq "True")
{
SCHTASKS /Delete /TN "Switcheroo" /f
TIMEOUT /T 3
}
elseif ($? -ne "True")
{
Write-Host Failed to copy unattend.xml
exit (22)
}

#4
if ($? -eq "True")
{
rm log.txt
TIMEOUT /T 3
}
elseif ($? -ne "True")
{
Write-Host Failed to delete the schedued task
exit (32)
}

#5
if ($? -eq "True")
{
& "$env:windir\System32\Sysprep\sysprep.exe" /generalize /oobe /shutdown /unattend:unattend.xml
}
elseif ($? -ne "True")
{
Write-Host Failed to remove the log.txt
exit (42)
}
#6
if ($? -ne "True")
{
Write-Host Sysprep failed.
exit (52)
}
}
elseif ($? -ne "True")
{
Write-Host Failed to run DskPrtRmv
exit (12)
}

C 代码:

/* 
* File: main.c
* Author: Andrew
*
* Created on June 1, 2012, 2:39 PM
*/

#include <stdio.h>
#include <stdlib.h>

FILE *fp;

int main()
{
printf("Switcheroo in progress...\n");

if ((fp=fopen("chk.bin", "rb")) == NULL)
{
//Run powershell script Part1.ps1 and set its return value to the int i variable.
int i = system("powershell -executionpolicy unrestricted -file \"Part1.ps1\"");
if (i == 0)
{
//Set up the log file that the computer will check upon reboot.
char buffer[2] = {'0'};
fp = fopen("chk.bin", "wb");
fwrite (buffer , 1 , sizeof(buffer) , fp );
}
else if (i != 0)
{
//Print the error returned from powershell script Part1.ps1
printf("Part1 Error: %d \n", i);
system("PAUSE");
}
}
else if (fp = fopen("chk.bin", "rb"))
{
//Run powershell script Part2.ps1 and set its return value to the int j variable.
int j = system("powershell -executionpolicy unrestricted -file \"Part2.ps1\"");
if (j == 0)
{
printf("Switcheroo has finished successfully.\n");
remove("chk.bin");
}
else if (j != 0)
{
//Print the error returned from powershell script Part2.ps1
printf("Part2 Error: %d \n", j);
system("PAUSE");
}
}
}

最佳答案

您正在测试的计算机上的操作系统架构是什么?

当你编译你的 C 程序时,你的目标是 32 位还是 64 位 exe?

您的问题可以解释为您的操作系统是 64 位,而您的程序是 32 位,因此它执行 32 位版本的 PowerShell,这会产生一些问题。

如果是这样,您可以解决从 32 位 C exe 使用生成 64 位 PowerShell 的问题。

c:\windows\sysnative\WindowsPowerShell\v1.0\powershell.exe

关于c - 如果从 C 程序执行,Powershell 脚本不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10868184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com