运行 提升 Powershell 脚本并导入系统模块

Run elevated Powershell Script and import system modules

我正在尝试使用批处理文件调用 .PS1 以生成仅包含用户名和其他电话号码详细信息的 csv 文件。我有生成 csv 文件的脚本。

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

我有提升 PowerShell 的批处理文件

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

问题是当我尝试通过添加

来导入系统模块时
powershell.exe -ImportSystemModules

到 powershell 脚本的前面,CSV 只有 returns header 信息,例如姓名和其他电话。如果我手动导入模块,即右键单击导入系统模块,则该脚本有效,但当我尝试在 运行 安装脚本之前加载模块时,该脚本无效。

基本上我需要以管理员身份运行 PS 脚本,导入系统模块并让代码输出我的数据。

感谢任何关于我哪里出错的帮助。

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

如果您需要在脚本中加载模块,请使用以下代码:

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

-ImportSystemModules 开关是 powershell.exe 的标志。如果您在脚本中调用 powershell.exe -ImportSystemModules,它将启动另一个 powershell 实例并在其中加载模块。

您还可以将 -ImportSystemModules 添加到批处理文件中的 powershell 调用中。这也应该有效

此致