xxxxxxxxxx
// Install the NuGet package "System.Management.Automation" for PowerShell integration
using System.Management.Automation;
public void RunPowerShellScript(string scriptPath)
{
// Create an instance of the PowerShell engine
var powerShell = PowerShell.Create();
// Add the script path to the PowerShell instance
powerShell.AddScript(scriptPath);
// Execute the script
var results = powerShell.Invoke();
// Check for any errors
if (powerShell.HadErrors)
{
// Handle or log the errors
}
// Handle the output (if required)
foreach (var result in results)
{
// Process the output
}
}
xxxxxxxxxx
powershell -ExecutionPolicy Bypass -Command "your script here"
xxxxxxxxxx
CMD>
C:> powershell -File "C:\Zabbix\hello.ps1"
PS>
cd "C:\Zabbix";
echo 'Write-host "Please enter your name:"' > hello.ps1
echo '$userName = read-host' >> hello.ps1
echo '"Hello $userName!"' >> hello.ps1
type hello.ps1
./hello.ps1
For Error: cannot be loaded because the execution of scripts is disabled on this system, Use:
PS> set-executionpolicy remotesigned
xxxxxxxxxx
./myscript.ps1 //if is in the current directory
c:/scripts/myscript.ps1 //if you want to use the full path
&"C:/my path with space/myscript.ps1" //if your path has spaces
xxxxxxxxxx
# Run PowerShell as administrator and run the following command
set-executionpolicy remotesigned
xxxxxxxxxx
# Specify the file path of the PowerShell script
$scriptFilePath = "C:\path\to\script.ps1"
# Check if the script file exists
if (Test-Path $scriptFilePath) {
# Run the PowerShell script
& $scriptFilePath
} else {
Write-Host "Script file not found."
}