【问题标题】:Add powershell script to c# code将 powershell 脚本添加到 c# 代码
【发布时间】:2015-04-03 02:30:11
【问题描述】:

我想从 C# 代码执行一个 powershell 脚本。我不想将我的 powershell 脚本存储在任何文件夹中。脚本有点大,它有一个参数“列表”和“字符串”,如何做到这一点。

    $ComputerName = "win12"
    $username="administrator"
    $password="passw0rd@12"

   $secstr = New-Object -TypeName System.Security.SecureString
   $password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
   $fname="v.exe"
   $fname="C:\"+$fname

     $cr = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
      $Session = New-PSSession -ComputerName $ComputerName -Credential $cr
       Invoke-Command -Session $Session -ScriptBlock {
  Start-Process -FilePath $($args[0]) -ArgumentList '/a' -Verb runas -WindowStyle Normal
  $process=[io.path]::GetFileNameWithoutExtension( $($args[0]));
 $a = (Get-Process -Name $process)
 $a.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::RealTime
  } -ArgumentList $fname

这是我的 powershell 脚本。

【问题讨论】:

  • 你看过PowerShell.Invoke吗? Google 和 StackOverflow 搜索没有发现任何有价值的东西吗?

标签: .net powershell c#-4.0 c#-3.0 powershell-2.0


【解决方案1】:

将 PowerShell 脚本作为嵌入资源存储在程序集中,然后在运行时提取脚本并将其提供给 PowerShell.AddScript(string script) 方法。调用PowerShell.Invoke()方法执行脚本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多