如何使用 Node JS 使用参数执行 Powershell 脚本函数? [英] How to execute Powershell script function with arguments using Node JS?

查看:69
本文介绍了如何使用 Node JS 使用参数执行 Powershell 脚本函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多个功能的 powershell 脚本,一个函数正在调用另一个函数.我想使用 node js 用一些参数执行该函数.我正在使用 node-powershell npm,但它只执行 powershell 命令而不是函数.我已经用 C# 做到了这一点,但在节点 js 中我无法做到这一点.

I have one powershell script which has multiple function and one function is calling another function. I want to execute that function with some argument using node js. I am using node-powershell npm, but it executes only powershell command not a function. I have done this with C#, but in node js i am not able to do this.

运行powershell函数的C#代码:

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;
            }
        }

运行powershell命令的Node JS代码:

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"更新相同的脚本并从 createComputer 函数中删除函数调用LogWrite"和getDirectoryEntryObject"时,它是工作正常.

this script is not working and nothing is being returned from script but when i have updated same script by removing the function name 'createComputer' and also remove the function call 'LogWrite' and 'getDirectoryEntryObject' from the createComputer function then it is working fine.

我更新的脚本:

    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 函数而不是通过 Node.js 调用 powershell 命令

I think, through node-powershell we can only execute powershell command and i want to call powershell function then how to do this using Node.js? Actually i am finding some alternative to call powershell function instead of powershell command through Node.js

推荐答案

问题是你的 Node.js 调用没有 dot-source *.ps1脚本文件,这是调用其中定义的 createComputer 函数所必需的.

The problem is that your Node.js invocation doesn't dot-source the *.ps1 script file, which is necessary in order to call the createComputer function defined therein.

因此,请尝试以下操作:

Therefore, try the following:

// This command dot-sources the script.
let cmd = '. ./Scripts/ComputerOperation.ps1'
return new Promise((resolve, reject) => {
    ps.addCommand(cmd)
    // Now that the script is sourced, you can call the `createComputer` function.
    ps.addCommand('createComputer')
    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 })))
            // Be sure to call .dispose() after execution.
            ps.dispose()
        })
        .catch(err => {
            reject(err)
            ps.dispose()
        })
})

<小时>

附带说明 node-powershell 包装:截至 2020 年 4 月 8 日,文档中的示例命令显示 .addArgument/addParameter/addParameters 方法调用的错误使用 - 查看此 GitHub 问题.


On a side note re the node-powershell package: As of 8 Apr 2020, the sample commands in the documentation show incorrect use of the .addArgument / addParameter / addParameters method calls - see this GitHub issue.

这篇关于如何使用 Node JS 使用参数执行 Powershell 脚本函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆