Delphi 7 中使用 Windows PowerShell 脚本 (WPS)
WPS (Windows PowerShell Script) 是由 Microsoft 开发的一种脚本语言,用于在 Windows 中自动执行管理任务。要在 Delphi 7 中使用 WPS,您需要执行以下步骤:
-
从 Microsoft 网站下载并安装 Windows PowerShell SDK。
-
打开 Delphi 7 并创建一个新项目。
-
向项目添加一个新的单元,并将其命名为“WPSUnit”。
-
在 WPSUnit 中添加以下代码:
unit WPSUnit;
interface
uses
SysUtils, Classes, Variants, WPS_TLB;
type
TWPS = class(TObject)
private
FPowerShell: IWindowsPowerShell;
public
constructor Create;
destructor Destroy; override;
procedure ExecuteScript(const AScript: string);
end;
implementation
constructor TWPS.Create;
begin
inherited;
FPowerShell := CoWindowsPowerShell.Create;
end;
destructor TWPS.Destroy;
begin
FPowerShell := nil;
inherited;
end;
procedure TWPS.ExecuteScript(const AScript: string);
var
LCommand: ICommand;
LResults: IEnumVariant;
LResult: OleVariant;
LBuffer: string;
begin
LCommand := FPowerShell.CreateCommand;
LCommand.AddScript(AScript);
LResults := LCommand.Invoke;
while LResults.Next(1, LResult, nil) = S_OK do
begin
LBuffer := LBuffer + LResult + #13#10;
LResult := Unassigned;
end;
ShowMessage(LBuffer);
end;
end.
-
保存单元并将其添加到项目中。
-
在主窗体中,添加一个按钮并将其命名为“btnExecute”。
-
双击按钮以创建事件处理程序。
-
在事件处理程序中,添加以下代码:
procedure TForm1.btnExecuteClick(Sender: TObject);
var
LPS: TWPS;
begin
LPS := TWPS.Create;
try
LPS.ExecuteScript('Get-Process | Select-Object Name,Id');
finally
LPS.Free;
end;
end;
-
保存并运行项目。
-
点击“btnExecute”按钮执行 WPS 脚本,并在消息框中显示结果。
注意:这只是一个关于如何在 Delphi 7 中使用 WPS 的基本示例。您可以根据需要修改代码,并执行更复杂的脚本。
原文地址: https://www.cveoy.top/t/topic/k461 著作权归作者所有。请勿转载和采集!