Search code examples
powershellformatinvoke-command

Simple Format of cscript invoke-command with a variable and argument in ScriptBlock


I have this "simple" script I am trying to run with an embedded variable in the path name, I have tried with and without the + and quotes around the whole thing, I cannot seem to get a variable to work in the path. If I run it like this, it outputs to C:\Scripts\Audit instead of to C:\Scripts\Audit\20161229_Audit\GPO_Reports. Can you not have variable in a ScriptBlock, I have seen comments on using an ArgumentList but I am not quite sure how to do this when a variable is to be used within a path name.

$Date = Get-Date -format yyyyMMdd
Invoke-Command -ComputerName localhost -ScriptBlock { cscript "c:\program files\GPMC\Scripts\GetReportsForAllGPOs.wsf" "C:\Scripts\Audit\"+$date+"_Audit\GPO_Reports /domain:contuso.local" } 

Solution

  • You have to pass the argumentlist inside the scriptblock since its not in the scope.

    Instead Of:

    $Date = Get-Date -format yyyyMMdd
    Invoke-Command -ComputerName localhost -ScriptBlock { cscript "c:\program files\GPMC\Scripts\GetReportsForAllGPOs.wsf" "C:\Scripts\Audit\"+$date+"_Audit\GPO_Reports /domain:contuso.local" }
    

    DO This:

    $Date = Get-Date -format yyyyMMdd
    Invoke-Command -ComputerName localhost -ScriptBlock {param($Date) cscript "c:\program files\GPMC\Scripts\GetReportsForAllGPOs.wsf" "C:\Scripts\Audit\$($date)_Audit\GPO_Reports /domain:contuso.local" } -ArgumentList $Date