0

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

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

# 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

有任何想法吗???

4

1 回答 1

1

这一行:

 $startInfo.Arguments = New_Function

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

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

错误消息告诉您 PowerShell 找不到名为hello. 我不完全清楚你想做什么。正如评论中提到的,函数 New_Function 在新的 Powershell.exe 进程中将不可用,除非您将它的副本放在脚本中并从那里调用它,然后将该脚本的路径传递给 Powershell.exe。

于 2013-10-07T20:52:04.403 回答