question

PChoward25-1111 avatar image
0 Votes"
PChoward25-1111 asked RichMatheisen-8856 edited

Unable to Run .ps1 Remotely -invoke does not work

Hi All,
I am looking for some help. I just started with a new company, and one of my first tasks is to log into computers to run a ".ps1" script. I know this doesn't sound complicated, but it sure is tedious as the computer log that needs to be completed is well in the hundreds.

Okay, so the problem. This company has a beautiful working ".ps1" that is distributed the domain group policy. However, running the script requires logging into the computer as an administrator because remote "running the script" does not work.

Errors Received.
When Attempting to use:invoke-command
Invoke-Command -FilePath C:\AdminTools\PowerShell\RemovedCompanyData.ps1 -ComputerName RemovedCompanyData -Credential $c

RemovedCompanyData
ListOnly is False
NoDrivers is False
KB not to install is False
RemovedCompanyData: Access denied. You don't have permission to perform this task.
+ CategoryInfo : PermissionDenied: (:) [Get-WURebootStatus], Exception
+ FullyQualifiedErrorId : PSWindowsUpdate.GetWURebootStatus
+ PSComputerName : RemovedCompanyData

Press any key to continue ...
Exception calling "ReadKey" with "1" argument(s): "The method or operation is not implemented."
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : RemoteException
+ PSComputerName : RemovedCompanyData


So, i Deleted the section "#region Checks reboot status and install or list updates" from the ".ps1".
Okay, It runs. But without completing the purpose of the ".ps1".


If the ".ps1" is run as an administrator logged into the computer, the correct log will show the following:


RemovedCompanyData
ComputerNameRemoved$
ListOnly is False
NoDrivers isFalse
No KB equals False


X ComputerName Result KB Size Title


However, running ".ps1" using invoke-command with the removal of the "#region checks reboot.." the log file show's this, which is WRONG.


RemovedCompanyData
End_User_account_name
ListOnly is False
NoDrivers isFalse
No KB equals False


Even though we use the same administrator credentials that are used for logging in as administrators.


Now digging very deep into the problem, i believe there's a problem with "#region Load Embedded Functions" and "windows Updates" do not work with invoke-Command.


Any Ideas, anybody? Please and thank you.

 param
 (
     [string]$NoKB = $false,
     [string]$NoDrivers = $false,
     [string]$ListOnly = $false,
     [string]$email = $false
 )
    
 #region Define email, log and other static variables.
 $version = "RemovedCompanyData"
 $logfile = "C:\RemovedCompanyData" # Log file loacation.
 IF ($email -eq $false)
 {
     $mail = "RemovedCompanyData" #email sent to.
 }
 Else
 {
     $mail = "RemovedCompanyData"+";"+"$email" #email sent to.
 }
 $eSubject = "WUScript completed on " + $ENV:computername + " by " + $env:username # email subject line unless change later in the script.
 $fmail = $ENV:computername + "RemovedCompanyData"
 #endregion
 #region Checks that PSWindowsUpades module exists
 $testPathPSWU = Test-Path 'C:\AdminTools\PowerShell\PSWindowsUpdate\PSWindowsUpdate.psm1'
 IF ($testPathPSWU -eq $true)
 {
     Try
     {
         Import-Module 'C:\AdminTools\PowerShell\PSWindowsUpdate\PSWindowsUpdate' -ErrorVariable Err
     }
     Catch
     {
         Write-Host 'Exiting -PSWindowsUpdate failed to load'
         Get-Date | Out-File $logFile -Append
         $Err | Out-File $logFile -Append
         Exit
     }
 }
 Else
 {
     Write-Host 'Exiting -PSWindowsUpdate not available on' + $ENV:computername
     Get-Date | Out-File $logFile -Append
     'Exiting -PSWindowsUpdate not available on' + $ENV:computername | Out-File $logFile -Append
     Exit
 }
 $testPathEmail = Test-Path 'C:\AdminTools\PowerShell\PSWindowsUpdate\PSWindowsUpdate.psm1'
 IF ($testPathEmail -eq $true)
 {
     Try
     {
         Import-Module 'C:\Program Files\WindowsPowerShell\Modules\RemovedCompanyData.psm1' -ErrorVariable Err
         $sendmail = $true
     }
     Catch
     {
         Write-Host 'Sendmail failed to load'
         Get-Date | Out-File $logFile -Append
         $Err | Out-File $logFile -Append
         $sendmail=$false
     }
 }
 #endregion
 #region Check DoNotConnectToWindowsUpdateInternetLocations sets registy key value to 0 if needed.
 function Get-RegistryValue {
   param(
     $key,
     $name
   )
      
   $key = $key -replace ':',''
   $regkey = "Registry::$key"
   $regkey
   Get-ItemProperty -Path $regkey -Name $name | 
     Select-Object -ExpandProperty $name
 }
 $registryPath = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate"
 $Name = "DoNotConnectToWindowsUpdateInternetLocations"
 $value = "0"
 IF (!(Test-Path $registryPath))
 {
     #New-Item -Path $registryPath -Force | Out-Null
     #New-ItemProperty -Path $registryPath -Name $name -Value $value -PropertyType DWORD -Force | Out-Null
 }
 ELSE
 {    
 Set-ItemProperty -Name $name -Path $registryPath -Value $value -Force -verbos
     #New-ItemProperty -Path $registryPath -Name $name -Value $value -PropertyType DWORD -Force | Out-Null
 }
 #endregion
 #region Load Embeded Functions
 <#
     .SYNOPSIS
         List available updates.
        
     .DESCRIPTION
         Retrieves list of available updates to install
        
     .PARAMETER NoKB
         KB #s not to include in list
        
     .EXAMPLE
                 PS C:\> GetWUList
        
     .NOTES
         Additional information about the function.
 #>
 function GetWUList
 {
     param
     (
         [Parameter(Position = 0)]
         [string]$NoKB
     )
     Write-Host 'Getting update list'
     if ($NoKB -eq $null)
     {
         $UL = Get-WUList -WindowsUpdate -MicrosoftUpdate -Verbose
     }
     Else
     {
         $UL = Get-WUList -WindowsUpdate -MicrosoftUpdate -NotKBArticleID $NoKB -Verbose
     }
     $UL
     Get-Date | Out-File $logFile -Append
     $UL | Select-Object -property KB, Title, Size, Type | Out-File $logFile -Append
     $date = Get-Date
     $ebody = $ENV:computername + " Windows Updates ListOnly completed at " + $date + " running " + $version
     Send-Mail $mail $fmail $eSubject $eBody
 }
 <#
     .SYNOPSIS
         Installs windows updateW/ Drivers
        
     .DESCRIPTION
            
        
     .PARAMETER NoKB
         String of KB#s that shouldn't be installed likke 'KB2483139, KB982018, KB3139398'
        
     .EXAMPLE
         PS C:\> Install-Updates
        
     .NOTES
         Additional information about the function.
 #>
 function Install-Updates
 {
     param
     (
         [Parameter(Mandatory = $false,
                    Position = 0,
                    HelpMessage = 'Pass KB #s not to install.')]
         [string]$NoKB
     )
        
     If ($NoKB -eq $null)
     {
         Write-Host "Installing updates"
         Get-WUinstall -MicrosoftUpdate -AcceptAll -install -IgnoreReboot -OutVariable WULog -Verbose -ErrorAction Continue -ErrorVariable Err
     }
     Else
     {
         Write-Host "Installing updates without KB(s) "  $NoKB
         Get-WUinstall -MicrosoftUpdate -NotKBArticleID $NoKB -install -AcceptAll -IgnoreReboot -OutVariable WULog -Verbose -ErrorAction Continue -ErrorVariable Err
     }
     $date = Get-Date
     $WULog | Out-File $logFile -Append
     $Err | Out-File $logFile -Append
     #$ebody = $ENV:computername + " Windows Updates install completed at " + $date + " running " + $version
     If ($Err)
     {
         Send-Mail $mail $fmail $eSubject $Err
     }
        
 }
 <#
     .SYNOPSIS
         installs windows update without drives
        
     .DESCRIPTION
         A detailed description of the Install-UpdatesND function.
        
     .PARAMETER NoKB
         Pass KB #s to avoid installing.
        
     .EXAMPLE
         PS C:\> Install-UpdatesND -NoKB 'Value1'
        
     .NOTES
         Additional information about the function.
 #>
 function Install-UpdatesND
 {
     param
     (
         [Parameter(Mandatory = $false,
                    Position = 0,
                    HelpMessage = 'Pass KB #s to avoid installing.')]
         [string]$NoKB
     )
        
        
     IF ($NoKB -eq $null)
     {
         Write-Host "Installing updates NO DRIVERS"
         Get-WUinstall -UpdateType 'Software' -MicrosoftUpdate -AcceptAll -Install -IgnoreReboot -OutVariable WULog -Verbose -ErrorAction:Continue -ErrorVariable Err
     }
     Else
     {
         Write-Host "Installing updates NO DRIVERS & without KB(s) " $NoKB
         Get-WUinstall -UpdateType 'Software' -MicrosoftUpdate -NotKBArticleID $NoKB -AcceptAll -Install -IgnoreReboot -OutVariable WULog -Verbose -ErrorAction:Continue -ErrorVariable Err
     }
     $date = Get-Date
     $WULog | Out-File $logFile -Append
     $Err | Out-File $logFile -Append
     $ebody = $ENV:computername + " Windows Updates install completed at " + $date + " running " + $version
     Send-Mail $mail $fmail $eSubject $eBody
 }
 #endregion
 Get-Date | Out-File $logFile -Append
 $version | Out-File $logFile -Append
 $env:username | Out-File $logFile -Append
 'ListOnly is ' + $ListOnly | Out-File $logFile -Append
 'NoDrivers is' + $NoDrivers | Out-File $logFile -Append
 'No KB equals ' + $NoKB | Out-File $logFile -Append
 CLS
 Write-Host $version
 Write-Host "ListOnly is" $ListOnly
 Write-Host "NoDrivers is" $NoDrivers
 Write-Host "KB not to install is" $NoKB
    
 #region Checks reboot status and install or list updates.
 $RStatus = Get-WURebootStatus -Silent
 If ($RStatus -eq $false)
 {
     If($ListOnly -eq $false){
         If ($NoDrivers -eq $false){
         Install-Updates $NoKB
             $RStatus = Get-WURebootStatus -Silent
         Write-Host Reboot Required  $RStatus
         }
         Else{
         Install-UpdatesND $NoKB
         $RStatus = Get-WURebootStatus -Silent
         Write-Host Reboot Required  $RStatus
         }
     }
     Else
     {
     GetWUList $NoKB
     Write-Host "Press any key to continue ..."
     $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
     }
 }
 Else 
 {
     $ComputerName + " needs reboot" | Out-File $logFile -Append
     Write-Host "Press any key to continue ..."
     $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
 }
 #EndRegion
windows-server-powershellremote-desktop-serviceswindows-server-update-serviceswindows-sysinternals-pstools
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
1 Vote"
RichMatheisen-8856 answered RichMatheisen-8856 edited

I don't think you can run that remotely [run the Get-WURebootStatus cmdlet], even as an admin. But the value you want is really just something you can get from the machine's registry (if the machine isn't pending a reboot the key won't be there).

 https://www.reddit.com/r/PowerShell/comments/7j20kh/execute_powershell_on_remote_machine/


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AlexZhu-MSFT avatar image
1 Vote"
AlexZhu-MSFT answered

Hi,

It seems this is the expected behavior. If we distribute the policy under computer management, it runs under SYSTEM context.

$env:username | Out-File $logFile -Append

Line 222, $env:username is used. When the script is run by group policy in the background, the current user is SYSTEM (this is the computer itself, therefore we see hostname$ in the logfile). However, when a user is logged on, the script is run under user context, $env:username outputs the current logged on user.

Based on my testing (via below steps), it seems the script is working (w/o removal of the last section).

(1) Install-Module -Name PSWindowsUpdate
(3) created a RemovedCompanyData folder in c:\
(4) modify some lines to

line 11
$logfile = "C:\RemovedCompanyData\script_log" # Log file loacation.

line 24
$testPathPSWU = Test-Path 'C:\Program Files\WindowsPowerShell\Modules\PSWindowsUpdate\2.2.0.2\PSWindowsUpdate.psm1'


line 29
Import-Module 'C:\Program Files\WindowsPowerShell\Modules\PSWindowsUpdate\2.2.0.2\PSWindowsUpdate.psm1' -ErrorVariable Err

line 46
$testPathEmail = Test-Path 'C:\Program Files\WindowsPowerShell\Modules\PSWindowsUpdate\2.2.0.2\PSWindowsUpdate.psm1'


line 51
Import-Module 'C:\Program Files\WindowsPowerShell\Modules\PSWindowsUpdate\2.2.0.2\PSWindowsUpdate.psm1' -ErrorVariable Err

123071-powershell-03.png

123063-powershell-04.png

Alex
If the response is helpful, please click "Accept Answer" and upvote it.



powershell-03.png (147.0 KiB)
powershell-04.png (62.8 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.