
- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on ‎03-24-2020 11:56 AM
In this article, i will explain how you can call a powershell script from the ServiceNow instance.
Here is a sample powershell script which will print the name of the person that is selected in the RITM. A very basic example.
Powershell Script
#Variables
$name = $args[0]
$ritm = $args[1]
#when passing the argument, we are replacing spaces with -. So replace hyphen(-) with spaces back.
$DisplayName = $name -replace "-"," "
Write-Host $ritm"-"
Write-host "Mentioned name is" $DisplayName
Now store this powershell script into the midserver folder in this path.
powershell scripts\\PowerShell\\myService.ps1
The script is created and stored, now we need to call this from ServiceNow.
Let us create 1 sample RITM where you mention the name that need to be printed in the powershell. The user will mention the Name in the input field and submit. Then SN shall take that name and pass it to the powershell script.
Write a Business Rule after insert on RITM table and call the powershell script.
Business Rule - Creates ECC Queue output entry
(function executeRule(current, previous /*null when async*/ ) {
var ritm = current.number;
var name = current.u_name;
name = name.replaceAll(" ","-"); //replace spaces with hyphen(-)
var ecc = new GlideRecord("ecc_queue");
ecc.initialize();//to create record
ecc.agent = "mid.server.YOUR_MIDSERVER_NAME";
ecc.topic = "Command";
var value = "powershell scripts\\PowerShell\\myService.ps1 "+name+ " " +ritm;
ecc.payload = '<?xml version="1.0" encoding="UTF-8"?><parameters><parameter name="name"
value="'+value+'"/><parameter name="skip_sensor" value="true"/></parameters>';
ecc.queue = "output";
ecc.state = "ready";
ecc.insert();
})(current, previous);
Once the RITM is created, the BR executes and trigger an entry in ECC Queue with the queue output and state Ready.
The output entry in ECC Queue means an communication from instance to Mid Server. When the Mid server process that entry, it changes the output entry state to processed and it creates another entry in the ECC Queue with queue as input and the output of the powershell script is stored in the payload field of the ECC Queue input entry.
Business Rule - Parse ECC Queue Input Entry
Create a BR on the ecc queue table after insert with conditions
Queue: Input
Name contains myService.ps1
state: Ready
and in the script, add this code.
(function executeRule(current, previous /*null when async*/ ) {
// Add your code here. Fetch the ritm number from the powershell script output and update the status to closed complete.
var name = gs.getXMLText(current.payload, "//stdout");
data = name.split("-");
var ritmNo = data[0].trim();
var PS_output = data[1].trim();
var ritm = new GlideRecord("sc_req_item");
ritm.addQuery("number", ritmNo);
ritm.query();
if (ritm.next()) {
//update request item to closed complete
ritm.state = 3; //closed complete
ritm.comments.setJournalEntry(PS_output); //store PS output here.
ritm.update()
}
})(current, previous);
Let me know if you have any questions in the comments.
Mark the article as helpful and bookmark if you found it useful.
- 46,329 Views
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hello,
This is not the preferred way.
Flow designer and integration hub is the way to go. There is already a Powershell step once you enabled IntegrationHub. You can use the powershell step to create you own custom activity.
TA

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi,
Thanks for bringing that. I totally agree that Flowdesigner and Integration hub is the best way to go.
This articles will help people who are NOT using flow designer and still need to execute PS script.

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi
How do i use this code to call powershell script which has function and this function accepts parameter?
I am in middle to completing integration between ServiceNow and ASP.Net Web Service.
I already have powershell script which calls this ASP.net web service and returns the response based on parameters.
This powershell script has just 1 function which returns array of values based on input function parameter.
I want to call this powershell script from servicenow server scripts so that i can pase response from powershell script in servicenow.
How to call Powershell script in servicenow by passing function name and function parameters?
I tried below code to call this powershell script via ECC queue.But, this is not working.I am getting error response in ECC queue input payload after calling PS script using below code.
If you see below code, the PS script name is getData.ps1 and function in this PS script i want to call is Get-DiscountData.
Also, i need to pass parameter while calling function in this PS Script.
var employeeID = 'xxdd';
var ecc = new GlideRecord("ecc_queue");
ecc.initialize();//to create record
ecc.agent = "mid.server.xxxx";
ecc.source = gs.getUserName();
ecc.topic = "Command";
var value = "powershell scripts\\PowerShell\\getData.ps1; Get-DiscountData -Param1 " + employeeID;
ecc.payload = '<?xml version="1.0" encoding="UTF-8"?><parameters><parameter name="name" value="'+value+'"/><parameter name="skip_sensor" value="true"/></parameters>';
ecc.queue = "output";
ecc.state = "ready";
ecc.insert();
Please let me know way to call Powershell script with function and parameter from servicenow server scripting.
Regards,
Sachin

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hello Sachin,
I am not sure if you can call a function directly from ecc queue. But you can call the PS script and in the argument pass a function name along with any other values that you want to pass it.
Then in your PS you can check like this
#write-host "hello world"
function testing($str) {
Write-Host "The name is "$str
}
$str = $args[0];
if($str -eq "discount_data") {
testing($args[1])
}
powershell scripts\\PowerShell\\getData.ps1 "discount_data" employeeID;
Mark the comment as helpful once worked.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
This was really very helpful. But I need to know few things. After the powershell script is hit, there are two XML files generated XXXXstatus.xml and XXXXlog.xml. Where XXXX is the ServiceNowTicketId.
Now how to read these files as these files are still in Mid Server in the same folder where my powershell script is stored.
Please help with your inputs.

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi,
You need to have a ps script which you invoke through eccqueue. The PS script should read the files, parse the xml and then share the output back.
Ref: https://adamtheautomator.com/powershell-parse-xml/
https://devblogs.microsoft.com/scripting/use-powershell-to-parse-an-xml-file-and-sort-the-data/
Kindly mark the article as helpful if it helps.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
you shouldn't store files directly on the MID, but use the instance (in "MID Server Script Files"). This ensures it always syncs to all MID servers, and will not require access to the MID server itself.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi
Thank You for the article. It is very helpful. Just want to mention that we can also execute PowerShell scripts using Integration Hub.
https://community.servicenow.com/community?id=community_article&sys_id=66d9e0111b7ee8101e579979b04bcbe2
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
I have tried with the above idea but not getting success. Please help me with this.
Folder structure Image:
Fix script:
var ecc = new GlideRecord("ecc_queue");
ecc.initialize();
ecc.agent = "mid.server.Srv Mid Server";
ecc.topic = "Command";
ecc.name = 'AutomateLogin';
//var value = "C:\\Mid_server_PD\\Automate_login.ps1";
ecc.payload = '<?xml version="1.0" encoding="UTF-8"?><parameters><parameter name="name" value ="C:\\Mid_Server\\Automate_login.ps1"/><parameter name = "skip_sensor" value = "true"/></parameters>';
ecc.queue = "output";
ecc.state = "ready";
if (ecc.insert()) {
gs.info('Record inserted ' + ecc.sys_id + ' Payload:- ' + ecc.payload);
} else {
gs.info('Not able to create record');
}
This record is getting created in the ECC Queue table but not getting any input. Please help me.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
@Rahman, hello.
Please provide proper detailed example on how to call PS script from ServiceNow with few parameters and how those variable can be interpreted.
thank you,
George
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Can it be called in a workflow

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
yes you can create a entry in ecc_queue form anywhere. Its a server side script.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Does any one knows , how to invoke the powershell with adminstrator privileges,
The service account has admin rights but the script inside powershell still requires elevation to administrator in order to execute the content of script.
can some one please advise
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hello BhupeshG
Were you able to figure the admin rights issue? I am running into the same problem.
Thanks.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi @asifnoor
I've tried replicating this however the output record in the ECC queue gets 'stuck' at processing. I can see from the logs that the MID Server is receiving the command but nothing is being run ...
01/09/23 15:38:43 (729) Worker-Standard:Command-bad3d4a587d8615819bcec6e8bbb35e2 Worker starting: Command
Any ideas? I've tried it with scripts passing parameters and without in case I had issue with the parameters being passed but no luck. I've also confirmed that the PS scripts work when I run them directly through the PS ISE.
Steven
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
If the Powershell is not runningt then there could be multiple reasons.
- It could be the ExecutionPolicy. SetExecutionPolicy. But if you are successfully ruinning the code using ISE the this is unlikely.
- It could be the account that is excecuting the MID Server Service. The Run As tab on the Windows Service. If you are using local Administrator then this is priobably not the factor.
- It could be that the MID Server can't find/locatre the Powershell. The contents of the scriprts/Powershell folder is controlled by the Agent. Agent script files are downloaded by the Agent in Startup.
- It could be the PSExecutionPath environment variable. This should be being set and /scripts/powershell should be included automatically by the MID Server Windows Service.
I have used John Anderson's Powershell Probe. Check it out. Its pretty good. Although I did have to fax an issue because he had not updated it in a while.
But overall, I would use a Flow Action and then call the Flow action using the Flow API in Javascript. This is much the best way and is the recommended way by ServiceNow. Let ServiceNow handle the ECC Queue automatically. What you are tying to do is unneccessary.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Thanks for the response Doug.
I managed to work out why the PS wasn't running and got it to work. Although the script file was being read by the MID server PS was never being invoked to run the script so I added the following to the command:
C:\\windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe [file path for the file]
Regarding your comments on Flow. Completely agree and we are currently putting together a requirements doc for our management team to purchase IH Professional which we have tested in a non-prod environment. Unfortunately we have a requirement which needs to be meet within the next week so need to put in an interim solution.
Steven

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
For those saying to use Flow Designer, yes, that is probably the easiest way. However, I just want to point out that ServiceNow has an official KB describing the same process as that listed in the article: KB0858504. The KB article doesn't explicitly discourage the use of this method, although it is quite bare and IMO incomplete.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hello, I am currently struggling trying to run a powershell script as well. I thought there was a module in servicenow where I can paste my code or at least call my ps file from somewhere. The only thing that my code does is generating a CSV file, then we have to populate data into the CMDB table using this CSV file and also, we have to do this weekly. I will appreciate any ideas on this.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Might not be exactly what you're looking for but what I ended up doing was:
1 - Place the PS script in a folder on a MID server
2 - In my workflow run a script action which creates an output record in the ecc queue
3 - Create an additional script action in the workflow that takes the payload from the MID server, via an input record in the ecc queue. The make a decision on what action to take based on the input
The command to run the PowerShell script is:
var powerShellScript = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe D:\\ServiceNow\\PS_SCRIPTS\\DanaherSharedFolderV2.ps1 " + name + " " + ritm + " " + "'" + danaherGroupName + "'";
name, ritm and danaherGroupName are all variables being passed to the PowerShell script.
Steven
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
@asifnoor I am able to execute PowerShell script using your steps. However whenever there is an error in the input entry the queue gets stuck processing the same again and again. Until I delete those entries my other output entries are not getting processed. Do you have a better solution to handle error records so that the queue does not get stuck?
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
As a developer that hates Flow and the Integration Hub i really like this.
What you can also do is find an old instance of ServiceNow that has the PowerShell activity for Workflow and copy that over to your instance. Set the activity to active and you will be able to do it directly from workflow. If your SN department is big on having to use flow, there is a built in action to call a workflow from Flow.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Whatever happened to the native "run powershell" action or the powershell item in workflow editor?
Why are these gone and why can't we use these instead of doing all this rigamaroo to write to the ecc queue which is problematic - instead of having an out of the box easy pick this and choose your script file method?
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
They were taken out so they could sell you spokes.
The SSH activity also. The only way to use these again is to pull them off an old instance and impost them. The core functions still exist within, the actives were just deprecated and removed.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
ciao ragazzi questo è il comando che uso
e non funziona. Qualcuno può aiutarmi?
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
have you ever succeeded in doing this with passing a credential alias along and being able to access the $cred variable on the PS side successfully?