首页 > 解决方案 > 使用其他语言激活 Powershell 脚本

问题描述

我有一个 PS 脚本,我需要在用户无需打开 powershell 的情况下运行它——我认为最简单的事情是编写一个将运行 PS 脚本的应用程序或 .bat 文件。但是我无法让脚本使用任何其他语言运行。

我试过使用 java 但它不运行脚本,C# 或批处理命令也不运行。我将附上下面的批次,因为这似乎是更简单的方法,我只是不确定为什么它不起作用 - 没有错误消息它只是不起作用。

编辑** Powershell 脚本如下,可以运行。我需要一个将运行脚本的第三方应用程序。

$wshell = New-Object -ComObject Wscript.Shell
$Output = $wshell.Popup("Select a Folder that you want to Analyze
Please be aware the larger the folder size the Longer it will take to Generate")
@echo off
 
powershell.exe -ExecutionPolicy Unrestricted -Command "'I:\TestScript\FolderInformation.ps1'"
 
TIMEOUT /T 10

对于不知道使用 ISE 或任何其他 PS 应用程序的用户,我只需要能够通过启动单个应用程序来运行脚本。

到目前为止,我使用的任何应用程序或脚本都不起作用,除了使用 ISE 来运行它。

***** Java 代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PowerShellJavaDemo {

    public static void main(String[] args) throws IOException {

        String line;

        String command = "powershell.exe & \"I:\\testingscript\"";

        Process powerShellProcess = Runtime.getRuntime().exec(command);

        powerShellProcess.getOutputStream().close();

        BufferedReader stdout = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream()));
        while ((line = stdout.readLine()) != null) {
            System.out.println("Output: " + line);

        }

        stdout.close();

        BufferedReader stderr = new BufferedReader(new InputStreamReader(powerShellProcess.getErrorStream()));
        while ((line = stderr.readLine()) != null) {
            System.out.println("Output: " + line);
        }
        stderr.close();

    }

}
    

标签: javapowershellbatch-file

解决方案


如下所示的两件事可能会有所帮助。

  1. 删除路径\文件前后的 '。如果这没有帮助,那么:
  2. 尝试使用“绕过”而不是“不受限制”

@echo off

powershell.exe -ExecutionPolicy Bypass -Command "I:\TestScript\FolderInformation.ps1"

TIMEOUT /T 10

我一直使用它来与我们的服务器通信并运行更新或其他重要信息。

注意:您的组策略可能会限制这一点。如果以上都不起作用。

我可能有一个解决方案,您可以使用 ISE。

start powershell_ise.exe "I:\TestScript\FolderInformation.ps1"

timeout /t 5

ECHO Set obkey = CreateObject("WScript.Shell") > temp.vbs

ECHO obkey.SendKeys "{F5}" >> temp.vbs

cscript temp.vbs

DEL temp.vbs

timeout /t 5

taskkill /im powershell_ise.exe

pause


推荐阅读