It is possible to assign a scriptblock to a variable
$scriptBlock = { ... }
Also you have an error in your code: You check the connection for $2FQDN
(instead of $1FQDN
) in your first if
.
Additionally, you could simplify your code further: both bodies of the if-else are identical.
My suggestion:
$scriptBlock = {
# Loads of registry keys...
}
$faultReport = @()
$computerName = $null
if (Test-Connection $1FQDN -Quiet -count 2) {
$computerName = $1FQDN
}
elseif (Test-Connection $2FQDN -Quiet -count 2) {
$computerName = $2FQDN
}
if ($computerName) {
try {
Invoke-Command -ComputerName $computerName -ScriptBlock $scriptBlock
}
Catch {
$faultReport += $computerName
}
}
Note: Always use proper indentation. I can never stress that enough. It makes reading and troubleshooting your own code so much easier.
CLICK HERE to find out more related problems solutions.