简体   繁体   中英

Run elevated Powershell Script and import system modules

I'm trying to call a .PS1 using a batch file to produce a csv file with just the User Name and Other Telephone number details. I have the script to produce the csv file.

Get-ADUser -Filter * -Properties otherTelephone | 
    select name, @{L='otherTelephone'; E={$_.otherTelephone[0]}} | sort-object otherTelephone | select-object -last 1000 | 
    Export-Csv C:\Test.csv -NoTypeInformation

and I have the batch file to elevate the PowerShell

powershell -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -file C:\Test.ps1' -verb RunAs}"

The problem is when I try to import the system modules by adding

powershell.exe -ImportSystemModules

to the front of the powershell script, the CSV only returns the header information eg name and otherTelephone. The script works if I import the modules manually ie right click import system modules, but not when I try to load modules before running the script.

Basically I need to run the PS script as admin, import the system modules and have the code output my data.

Any help as to where I am going wrong is appreciated.

powershell.exe -ImportSystemModules Get-ADUser -Filter * -Properties otherTelephone | 
    select name, @{L='otherTelephone'; E={$_.otherTelephone[0]}} | sort-object otherTelephone | select-object -last 10 | 
    Export-Csv C:\Test.csv -NoTypeInformation

If you need to load the modules inside your script use the following code:

Get-Module -ListAvailable | Where-Object {$_.Path -like "$PSHOME*"} | Import-Module

The -ImportSystemModules switch is a flag for powershell.exe . If you call powershell.exe -ImportSystemModules inside of your script it will start another powershell instance and load the modules inside of it.

You could also add the -ImportSystemModules to your powershell call inside the batch file. That should work too

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM