1

I have a PowerShell script. The way I usually execute this script in the PS console is by using:

. .\psScript.ps1

functionName

functionName is my entry function. I am attempting to run this PowerShell script and auto execute the function functionName as Administrator from a batch file. I can execute this script and function from my batch file using:

powershell -command "& { . .\psScript.ps1; functionName }"

However, this does not execute the script as administrator. So I have also tried the following:

powershell -NoProfile -ExecutionPolicy ByPass -command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy ByPass -File "". .\psScript.ps1; functionName""' -Verb RunAs}"

This still does not work, and the console disappears too quickly for me to read the error message. Could anybody please help?

2
  • I assume that cmd is not launched as admin? Commented Feb 15, 2017 at 15:38
  • Cmd is not launched as admin, no. Commented Feb 15, 2017 at 15:55

1 Answer 1

2

This works, from a non-elevated command prompt:

powershell -Command "Start-Process PowerShell –Verb RunAs -ArgumentList ""-File C:\Path\To\Script\psScript.ps1"""
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your reply. This does run the script as admin from a non-elevated cmd prompt, however, it does not auto-execute the function I need it to, I.e. functionName (shown above)
Easiest way to run the function, is to wrap dot-sourcing of the the psScript.ps1 file AND the function call into a second script. Then call that second script using my method above .
@potatopotarto you could add a call to the function at the end of the ps1 file, i.e. at the top you have function a { ... } and then after that just type a to call it.
@TechSpud How would I wrap the dot source script. Would it be something along the lines of . ". \psScript.ps1" functionName ?
@potatopotarto - Yes. Line1: . C:\path\to\script.ps1. Line2: functionName -param1 value1 -param2 value2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.