Automating Windows Server Updates with PSwindowsUpdate module. Issue

  automation, powershell, windows, windows-update

I am trying to automate windows server update instllation for multiple servers. I have installed the module on all servers and also added the hostnames in winrm trust hosts.
All server hostnames are stored in txt file and are looped trought for each loop with different commands from teh PSwindowswupdate module.

$Hostname = Get-Content -Path "C:TEMPpowershell_patching_scriptmodulehostnamesallwsus.txt"

Import-Module PSWindowsUpdate

foreach ($i in $Hostname) {

write-host $i

Get-WUHistory -ComputerName $i -last 3


Issue is that randomly the loop is failing for some hostnames, with error :

BGxxxxxxx01 #this is the hostname
Get-WUHistory : BGxxxxxxx01: Unknown failure. 
At C:TEMPpowershell_patching_scriptModuleHistory.ps1:10 char:1
+ Get-WUHistory -ComputerName $i -last 3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (:) [Get-WUHistory], Exception
    + FullyQualifiedErrorId : Unknown,PSWindowsUpdate.GetWUHistory 

If I run the command with the hostname instead of variable it is failing again with the same error.
If I run the same but with $ in front of the hostname (even if such varaiable is not defined) the command works!ly appriciated

Get-WUHistory -ComputerName $BGxxxxxxx01 -last 3

Localy executed the commands are also working.

This issue seams to occure on random bases for multiple hostnames form my list.
I am unable find anything helpful regarding this error.

Any help will be highly appriciated!
Thanks in advance!

Source: Windows Questions