powershell如何编程C语言,如果从c程序执行,Powershell脚本不起作用?

我有一个Power

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

POWERSHELL SCRIPT:

#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

#include

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");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值