У меня есть один скрипт powershell, который имеет несколько функций, и одна функция вызывает другую функцию. Я хочу выполнить эту функцию с некоторым аргументом, используя node js. Я использую node-powershell npm, но он выполняет только команду powershell, а не функцию. Я сделал это с C#, но в node js я не могу это сделать.
C# код для запуска функции powershell:
using (var runspace = RunspaceFactory.CreateRunspace())
{
try
{
log.Info(domain+"," + devicetype + "," + fullpath + "," + computername + "," + description );
var script = File.ReadAllText(HttpContext.Current.Server.MapPath(@"~\Scripts\ComputerOperation.ps1"));
runspace.Open();
var ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddScript(script);
ps.Invoke("Set-ExecutionPolicy Unrestricted");
ps.AddCommand("createComputer").AddParameters(
new Dictionary<string, string>
{
{ "domaincontroller" ,domain},
{"sitecode",sitecode },
{ "devicetype",devicetype},
{ "organizationUnit",fullpath},
{ "computername",computername},
{ "description",description},
{ "source",UserLoginController.version},
{ "ipAddress" , ipaddress},
{ "username",username}
});
foreach (PSObject result in ps.Invoke("Set-ExecutionPolicy Unrestricted"))
{
if (result != null)
{
log.Info("result=" + result.ToString());
return result.ToString();
}
}
}
catch (Exception ex)
{
log.Error(ex.Message);
return ex.Message;
}
}
Node JS Код для запуска команды powershell:
let cmd = './Scripts/ComputerOperation.ps1';
return new Promise((resolve, reject) => {
ps.addCommand(cmd)
ps.addParameters([{ domainController: computer.domain },{ sitecode: computer.siteCode },{ organizationUnit: 'OU=Legacy,OU=ARBUE,OU=AMER' },{ computername: computer.computerName },{ description: computer.description },{ devicetype: computer.deviceType }])
ps.invoke()
.then(response => {
resolve(JSON.parse(JSON.stringify({ message: response })));
})
.catch(err => {
reject(err);
ps.dispose();
});
});
Сценарий Powershell:
$Logfile = "C:\inetpub\wwwroot\UmgAcra\Scripts\log.log"
Function LogWrite{
Param ([string]$logstring)
try{
$timestamp = Get-Date
$logstring = $timestamp.ToString() +" - "+ $logstring
Add-content $Logfile -value $logstring
}
catch{
}
}
function getDirectoryEntryObject {
param([string]$path)
$Error.Clear();
try {
$directoryEntry = New-Object System.DirectoryServices.DirectoryEntry $path;
}
catch{
$er = $Error;
Logwrite("Error occured in $($MyInvocation.MyCommand.Name) $($Error)")
}
return $directoryEntry;
}
function createComputer {
param([string]$domainController,[string]$sitecode, [string]$organizationUnit, [string]$computername,[string]$description,[string]$devicetype,[string] $source ,[string] $ipAddress,[string] $username)
try{
LogWrite ("DomainController= "+$domainController+" OU= "+$organizationUnit+" computername= "+ $computername)
try{
$rootEntry = getDirectoryEntryObject -path "LDAP://$domainController"
$parentPath = $rootEntry.Path + "/" + $organizationUnit + "," + $rootEntry.Properties["distinguishedName"];
$objectPath=$rootEntry.Path + "/" +"OU="+$devicetype+","+$organizationUnit + "," + $rootEntry.Properties["distinguishedName"];
$parent = getDirectoryEntryObject -path $objectPath -credential $Cred;
if ($parent -eq $null -or $parent.Children -eq $null) {
#throw New-Object System.ArgumentException("$parentPath could not be found");
return "Path doesn't exist in AD. Please contact the support team for Organization Unit creation : "+" OU="+$devicetype+","+$organizationUnit
# please contact the support team for Organization Unit Creation
}
}
catch{
return " Error occured in createComputer An Active Directory Domain Controller for the domain ($domaincontroller) could not be contacted."
}
$adObject = $parent.Children.Add("CN=" + $computername, "computer");
if ($adObject -eq $null) {
throw New-Object System.ArgumentException("Unable to add new object (check AD permissions)");
}
$adObject.Properties["sAMAccountName"].Value = $computername.ToUpper() + "$";
$adObject.Properties["userAccountControl"].Value = 0x1020;
if($description -ne $null -and $description -ne "")
{
$adObject.Properties["description"].Value = $description;
}
if($sitecode -ne $null -and $sitecode -ne "")
{
$adObject.Properties["extensionAttribute3"].Value=$sitecode
}
$adObject.CommitChanges();
$result ="Computer "+$computername +" successfully created.";
return $result;
}
catch
{
$er = $Error;
Logwrite("Error occured in $($MyInvocation.MyCommand.Name) $($Error)");
return "Failed : " +$Error;
}
}
этот сценарий не работает и ничего не возвращается из скрипта, но когда я обновил тот же скрипт, удалив имя функции 'createComputer', а также удалив вызовы функций 'LogWrite' и 'getDirectoryEntryObject' из функции createComputer, он работает нормально.
Мой обновленный сценарий:
param([string]$domainController,[string]$sitecode, [string]$organizationUnit, [string]$computername,[string]$description,[string]$devicetype)
try{
#LogWrite ("DomainController= "+$domainController+" OU= "+$organizationUnit+" computername= "+ $computername)
try{
$Logfile = "C:\Users\Asif\UMGv2\Node JS Backend\Scripts\log.log"
$timestamp = Get-Date -Format g
$logstring = "DomainController= "+$domainController+" SiteCode="+$sitecode+" OrganizationUnit= "+$organizationUnit+" computername= "+ $computername+" Description="+$description+" DeviceType="+$devicetype
$logstring = $timestamp.ToString() +" - "+ $logstring
Add-content $Logfile -value $logstring
}catch
{
}
try{
$organizationUnit = $organizationUnit.Replace(" ",",");
Add-content $Logfile -value $organizationUnit
$rootEntry = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$domainController"
$parentPath = $rootEntry.Path + "/" + $organizationUnit + "," + $rootEntry.Properties["distinguishedName"];
$objectPath=$rootEntry.Path + "/" +"OU="+$devicetype+","+$organizationUnit + "," + $rootEntry.Properties["distinguishedName"];
$parent = New-Object System.DirectoryServices.DirectoryEntry $objectPath
if ($parent -eq $null -or $parent.Children -eq $null) {
#throw New-Object System.ArgumentException("$parentPath could not be found");
return "Error;Path doesn't exist in AD. Please contact the support team for Organization Unit creation : "+" OU="+$devicetype+","+$organizationUnit
# please contact the support team for Organization Unit Creation
}
}
catch{
return "Error;Error occured in createComputer An Active Directory Domain Controller for the domain ($domaincontroller) could not be contacted."
}
$adObject = $parent.Children.Add("CN=" + $computername, "computer");
if ($adObject -eq $null) {
throw New-Object System.ArgumentException("Error;Unable to add new object (check AD permissions)");
}
$adObject.Properties["sAMAccountName"].Value = $computername.ToUpper() + "$";
$adObject.Properties["userAccountControl"].Value = 0x1020;
if($description -ne $null -and $description -ne "" -and $description -ne 'none')
{
$adObject.Properties["description"].Value = $description;
}
if($sitecode -ne $null -and $sitecode -ne "")
{
$adObject.Properties["extensionAttribute3"].Value=$sitecode
}
$Error.Clear()
$adObject.CommitChanges();
return "Success;Computer "+$computername +" successfully created.";
}
catch
{
$er = $Error;
Add-content $Logfile -value "Error occured in $($MyInvocation.MyCommand.Name) $($Error)"
#Logwrite("Error occured in $($MyInvocation.MyCommand.Name) $($Error)");
return "Error;"+$Error;
}
Я думаю, что через node-powershell мы можем выполнять только команду powershell, и я хочу вызвать функцию powershell, тогда как это сделать с помощью Node.js? На самом деле я нахожу некоторую альтернативу для вызова функции powershell вместо команды powershell через Node.js