Enable-CimPSRemote.ps1 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. param(
  2. $ComputerName = 'somehostname.full.qualified.domain',
  3. [switch]
  4. $GetCredential=$false,
  5. [switch]
  6. $ForceGetCredential=$false,
  7. [System.Management.Automation.PSCredential]
  8. $Credential=$null,
  9. [switch]
  10. $ClientTrust=$false
  11. )
  12. if ($ClientTrust){
  13. if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" `"$args`"" -Verb RunAs; exit }
  14. Enable-PSRemoting -Force
  15. Set-Item WSMan:localhost\client\trustedhosts -value *
  16. Get-Item WSMan:localhost\client\trustedhosts
  17. exit
  18. }
  19. $SessionArgs = @{
  20. ComputerName = $ComputerName
  21. SessionOption = New-CimSessionOption -Protocol Dcom
  22. }
  23. if ($null -ne $Credential){
  24. $SessionArgs.Credential = $Credential
  25. }
  26. if ($ForceGetCredential -or $GetCredential){
  27. if ($ForceGetCredential -or ($null -eq $global:psremoteremotecred)) {
  28. $global:psremoteremotecred = Get-Credential
  29. }
  30. $SessionArgs.Credential = $global:psremoteremotecred
  31. }
  32. $SessionArgs | Out-Host
  33. $cmd_reg = "New-Itemproperty -name LocalAccountTokenFilterPolicy -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -propertyType DWord -value 1"
  34. $cmd_enable = "Enable-PSRemoting -Force"
  35. $Session = New-CimSession @SessionArgs
  36. if ($null -ne $Session){
  37. $MethodArgs = @{
  38. ClassName = 'Win32_Process'
  39. MethodName = 'Create'
  40. CimSession = $Session
  41. Arguments = @{
  42. CommandLine = "powershell Start-Process powershell -ArgumentList '$cmd_reg;$cmd_enable;get-netconnectionprofile'"
  43. }
  44. }
  45. Invoke-CimMethod @MethodArgs
  46. }