PowerCLI

  • 1.  Issue get the output from invoke-vmscript variable

    Posted Dec 17, 2024 03:36 AM

    Hi,

    I have issue getting the output from below script as variable filter is not working

    Please help!!

    $myuser = "bsuresh"
    $script = @'
    net localgroup administrators | where {$_ -AND $_ -notmatch "command completed successfully"} | select -skip 4 | where {$_ -like "$($myuser)"}
    '@


    $sInvoke = @{
    VM = $server
    GuestCredential = $Creds
    ScriptTYpe = 'powershell'
    ScriptText = $script
    }
    $result = Invoke-VMScript @sInvoke
    $result.scriptoutput

    If I run the command directly, this works but when used with the invoke-vmscript it is not working



  • 2.  RE: Issue get the output from invoke-vmscript variable

    Posted Dec 17, 2024 03:37 AM

    You are using single quotes in the here-string, that means the variable $($myuser) will not be resolved in the $script variable.



    ------------------------------


    Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference


    ------------------------------



  • 3.  RE: Issue get the output from invoke-vmscript variable

    Posted Dec 17, 2024 11:30 AM

    LucD,

    If I change to double quotes, I am getting the below error

    $myuser = "bsuresh"
    $script = @"
    net localgroup administrators | where {$_ -AND $_ -notmatch "command completed successfully"} | select -skip 4 | where {$_ -like $($myuser)}
    "@

    -AND : The term '-AND' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
    the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:44
    + & {net localgroup administrators | where { -AND  -notmatch "command c ...
    +                                            ~~~~
        + CategoryInfo          : ObjectNotFound: (-AND:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException




  • 4.  RE: Issue get the output from invoke-vmscript variable
    Best Answer

    Posted Dec 17, 2024 11:31 AM

    When you switch to double quotes all variables (all starting with $) will be substituted.
    Those you don't want to be substituted you will need to escape with a back-tick.



    ------------------------------


    Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference


    ------------------------------



  • 5.  RE: Issue get the output from invoke-vmscript variable

    Posted Dec 18, 2024 03:40 AM

    Thank you LucD,

    That worked. I tried as below and worked.

    $myuser = "bsuresh" 
    $script = @" 
    net localgroup administrators | Where-Object { `$_ -and `$_ -notmatch "command completed successfully" } | Select-Object -Skip 4 | Where-Object { `$_ -like '*$myuser'} 
    "@