Greetings and happy holidays!
I hope this question hasn't been answered somewhere else, because I've searched Stack and Google for about an hour now and haven't yet seen examples or posts that answer exactly what I'm trying to accomplish.
I created a script that checks the WindowsUpdate and WindowsUpdate\AU registry keys and the associated values for correct data configuration. If they are inconsistent with the desired configuration, it corrects them. I'm at home, so the script below isn't exactly how I created it at the job (I obtained my registry keys / values differently), but should give you a general idea of what I'm looking to do:
param($comp, [string]$location)
switch($location)
{
"EAST" {$WUServerDesConfig = "https://myeastmp.domain.com:8531"}
"WEST" {$WUServerDesConfig = "https://mywestmp.domain.com:8531"}
}
$WUServerActual = Invoke-Command -ComputerName $comp -scriptblock {(Get-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate).WUServer}
if($WUServerActual -ne $WUServerDesConfig)
{
Invoke-Command -ComputerName $comp -ScriptBlock {Set-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name WUServer -Type String -Value $WUServerDesConfig}
}
This doesn't work, and it seems that the reason behind it is that you can't pass an ordinary variable to the -value parameter for Set-ItemProperty (I believe it takes an object). Why this is, I have absolutely no idea, because if I just replace the variable with the string itself, it works without incident. The problem with this approach, however, is that, depending upon region, the server changes.
I consider myself to have only intermediate knowledge of PowerShell thus far (getting better every day though, I swear), so any assistance or suggestions on how to best accomplish this would be appreciated. Thanks!
This is an issue that most people run into when they start using invoke-command.
The most common solution is to pass the values you want in and use the $args variable like this:
Invoke-Command -ComputerName $comp -ArgumentList $WUServerDesConfig -ScriptBlock {
Set-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name WUServer -Type String -Value $args[0]
}
Another common solution is to add a param block like this:
Invoke-Command -ComputerName $comp -ArgumentList $WUServerDesConfig -ScriptBlock {
param($param1)
Set-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name WUServer -Type String -Value $param1
}
But there is a solution that uses scope rules that feels like a much better fit most of the time. There is a $using: scope that will give you access to your variable inside a script block like this.
Invoke-Command -ComputerName $comp -ScriptBlock {
Set-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name WUServer -Type String -Value $Using:WUServerDesConfig
}
I took the time to point out the other methods to help anyone else that has this issue.