如何在同一个脚本中生成新进程

时间:2013-10-07 17:30:28

标签: powershell process elevated-privileges

我了解您无法提升现有流程,但您可以使用提升的权限创建新流程。

目前我有两个脚本,其中一个脚本创建提升的权限并调用另一个脚本。

# script1.ps1

$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL
$userId = $NULL

$password = get-content C:\cred.txt | convertto-securestring    

$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = "C:\script2.ps1 " + $abc

$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$startInfo.Username = "username"
$startInfo.Domain = "DOMAIN"
$startInfo.Password = $password 

$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$userId = $process.StandardOutput.ReadToEnd() 
$process.WaitForExit()

return $userId

首先,我考虑在script1.ps1中创建一个函数New_Function,并通过$ startInfo.Arguments启动,即$ startInfo.Arguments = New_Function

$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL
$userId = $NULL

Function New_Function(){  
    $foo = "Hello World"
    return $foo
}


$password = get-content C:\cred.txt | convertto-securestring    

$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = New_Function

$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$startInfo.Username = "username"
$startInfo.Domain = "DOMAIN"
$startInfo.Password = $password 

$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$userId = $process.StandardOutput.ReadToEnd() 
$process.WaitForExit()    

return $userId

我没有将“Hello World”打印到屏幕上,而是出现以下错误,

The term 'Hello' is not recognized as the name of a cmdlet, function, script fi
le, or operable program. Check the spelling of the name, or if a path was inclu
ded, verify that the path is correct and try again.
At line:1 char:6
+ Hello <<<<  World
    + CategoryInfo          : ObjectNotFound: (Hello:String) [], CommandNotFou 
   ndException
    + FullyQualifiedErrorId : CommandNotFoundException

任何想法???

1 个答案:

答案 0 :(得分:1)

这一行:

 $startInfo.Arguments = New_Function

调用New_Function,返回“Hello World”并将其分配给$ startInfo.Arguments。因此,当您运行启动过程时,命令行如下所示:

C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe hello world

错误消息告诉您PowerShell找不到名为hello的命令(或应用程序)。我不太清楚你要做什么。正如提交中所提到的,新的Powershell.exe进程中的函数New_Function将不可用,除非您将其副本放在脚本中并从那里调用它,然后将该脚本的路径传递给Powershell.exe。

相关问题