PowerShell脚本如何以指定凭据重启自身并保留输入参数
问题解决方法
错误原因分析
- Invoke-Command的
-FilePath参数属于远程执行参数集,必须搭配-ComputerName(本地执行填localhost)才能明确参数集,否则会触发参数歧义错误。 -ArgumentList需要接收参数数组,而非拼接好的字符串(比如'-order', '66', '-location', 'UAT'),直接传字符串会被当作单个参数处理。
修正后的Invoke-Command方案
$user = "目标账户名" $script = "C:\path\to\script.ps1" # 将参数拆分为数组,避免使用拼接字符串 $arguments = '-order', '66', '-location', 'UAT' if(-not ([System.Environment]::UserName -eq $user)){ $Credential = Get-Credential -Credential "INTRANET\$user" # 必须添加-ComputerName localhost明确参数集 Invoke-Command -FilePath $script -Credential $Credential -ComputerName localhost -ArgumentList $arguments }
更适合本地重启的Start-Process方案
Invoke-Command本质是远程执行框架,本地场景用Start-Process更直接,还能规避远程执行的环境差异问题:
$user = "目标账户名" $script = "C:\path\to\script.ps1" $arguments = '-order', '66', '-location', 'UAT' if(-not ([System.Environment]::UserName -eq $user)){ $Credential = Get-Credential -Credential "INTRANET\$user" # 拼接脚本路径与参数为完整命令行,传递给PowerShell.exe $fullCommand = "& '$script' $($arguments -join ' ')" Start-Process powershell.exe -Credential $Credential -ArgumentList "-NoProfile", "-Command", $fullCommand }
关键注意事项
- 若脚本路径包含空格,必须用单引号包裹,避免解析错误。
-NoProfile参数可跳过加载当前用户的PowerShell配置,保证执行环境纯净。- 如需保留输出,可添加
-Wait参数等待脚本执行完成,或用-RedirectStandardOutput/-RedirectStandardError重定向输出内容。
内容的提问来源于stack exchange,提问作者erewien
相关产品推荐
相关产品推荐

