简体   繁体   中英

How to correctly compose Invoke-Expression command to build variable value based on config file values

Please see latest code that is now working, there is no longer any need for any Invoke cmdlet:

$ClassificationList = $null
$classifications = $null
$ClassificationList = $ConfigFile.Settings.Project.Classifications

If ( $ClassificationList )
{
    $ClassificationList = $ClassificationList -replace ',','|'

    $classifications = $wsus.GetUpdateClassifications() | 
    where title -match $ClassificationList

    $updatescope.Classifications.Clear()
    $updatescope.Classifications.AddRange($classifications)
}

Original Question:

This question has been condensed to avoid confusion.

When executing the below code:

$ScriptText = 
@"
`$classifications = `$wsus.GetUpdateClassifications() | 
        ?   {
                $_.Title -eq 'Critical Updates' `
                -OR `
                $_.Title -eq 'Security Updates' `
                -OR `
                $_.Title -eq 'Definition Updates' 
            }
"@
$scriptBlock = [Scriptblock]::Create($ScriptText)
Invoke-Command -ScriptBlock {$scriptBlock}
Write-Host $classifications

The variable $classifications does not get populated, but executing the code without wrapping it into a script block works fine. I am trying to read from a config file all classifications I want to search WSUS for and dynamically add them to the above script, but executing that script when it is built does not appear to work, though no errors are thrown.

Don't define your code as a string and then put that string in a scriptblock.


  
  
    Invoke-Command -Scriptblock {$ScriptText} 
  

If you must create a scriptblock from a string you'd do it like this:

$ScriptText = "if ( 1 -ne 2 ) {
    Write-Host 'Hello'
} else {
    Write-Host 'GoodBye'
}"
Invoke-Command -ScriptBlock ([Scriptblock]::Create($ScriptText))

However, normally you'd create the scriptblock as a literal, either as a variable

$scriptblock = {
    if ( 1 -ne 2 ) {
        Write-Host 'Hello'
    } else {
        Write-Host 'GoodBye'
    }
}
Invoke-Command -ScriptBlock $scriptblock

or inline

Invoke-Command -ScriptBlock {
    if ( 1 -ne 2 ) {
        Write-Host 'Hello'
    } else {
        Write-Host 'GoodBye'
    }
}

I would do it this way.

$wsus.GetUpdateClassifications() | 
  where title -match 'critical updates|security updates|definition updates'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM