我有一个特殊的用例,需要很多我的PowerShell脚本来更改它们所运行的用户上下文。我有可靠工作的代码,但我试图将它放入函数中,而不是在每个脚本中重复它。pssession功能不起作用
单独地,这个函数中的行可以工作,但是当作为一个函数运行时,脚本不会遇到错误,但是我没有得到任何结果。
如果任何人都可以发现我在这里失踪的东西,我将不胜感激。
Function Invoke-AsUser() {
Param(
[Parameter(Mandatory=$true)]
[String]
$ScriptBlock
,
[Parameter(Mandatory=$true)]
[String]
$RunAsUser
,
[Parameter(Mandatory=$true)]
[String]
$RunAsPassword
,
[Switch]$credSSP=$false
)
#Get the execution policy and store
$ExecutionPolicy = Get-ExecutionPolicy
#Set up WSMANCredSSP
Enable-WSManCredSSP -Role Server -Force | out-null
Enable-WSManCredSSP -Role Client -DelegateComputer $env:COMPUTERNAME -Force | Out-Null
#Set WSMAN MaxMemoryPerShell
#The following Prevents "Out of memory" errors from occurring when running commands through a remote pssession.
set-item wsman:localhost\Shell\MaxMemoryPerShellMB 512
#Enable PSRemoting
try
{
enable-psremoting -force | Out-Null
}
catch
{
Write-Host "Enabling PSRemoting returned a non fatal exception."
}
#Create Credentials
$cred = new-object System.Management.Automation.PsCredential($runasuser,(ConvertTo-SecureString $RunasPassword -AsPlaintext -force))
$cred
#Create the pssession
If ($credSSP -eq $true) {
try {
write-host "Authenticating with CredSSP"
$s = new-pssession -ComputerName $ENV:COMPUTERNAME -Credential $cred -Authentication Credssp
}
Catch {
Write-Error "Creating new-pssession failed"
}
}
Else {
try {
Write-Host "Authenticating without CredSSP"
$s = new-pssession -ComputerName $ENV:COMPUTERNAME -Credential $cred
}
Catch {
Write-Error "Creating new-pssession failed"
}
}
#Invoke the command using pssession
Write-host "Running Scriptblock as $RunAsUser"
Invoke-Command -Session $s -ScriptBlock {Set-executionpolicy Bypass -Force}
Write-Host $ScriptBlock
invoke-command -Session $s -ScriptBlock { $ScriptBlock }
Write-host "Running Scripblock as $RunAsUser has finished."
#set executionpolicy back to original
$ScriptBlock = "Set-ExecutionPolicy $ExecutionPolicy -Force"
Invoke-Command -Session $s -ScriptBlock {$ScriptBlock}
#Disable psremoting
Disable-PSRemoting -force -WarningAction SilentlyContinue
}
$ErrorActionPreference = "Stop"
Invoke-AsUser -ScriptBlock "& C:\temp\test.ps1" -RunAsUser $ENV:RUNASUSER -RunAsPassword $ENV:RUNASPASSWORD -CredSSP
谢谢。我在调试时删除了out-null,但将其清理干净以便在此处发布。 – user3255401
我已经找出问题所在,但解决不了问题。 事实证明,函数参数“脚本块”没有被传递到线 \t \t \t \t调用命令-Session $ S -ScriptBlock {$脚本块} 如果我改变路线是 \t \t \t \t invoke-command -Session $ s -Filepath $文件路径 它的工作原理。然而,这限制了功能,因为我无法将参数传递给$ filepath中的脚本。 – user3255401
尝试将参数类型更改为[scriptblock],然后直接传递参数'-Scriptblock $ scriptblock'。 –