Logging during if-then and foreach Not Reading Variables RRS feed

  • Question

  • I have a script that performs well but I am having issues with the logging during a loop.

    The foreach is here:

    foreach ($server in $servers) {
        $server_ip = $server.ip
        $server_name = $
        if (Test-Connection -ComputerName $server.ip -Count 1 -ErrorAction SilentlyContinue) {
            Add-Content $filename "`r`nInstalling...`r`n$client_name`r`n$client_ip`r`n"
            Invoke-Command -ComputerName $server.ip -ScriptBlock $SB1
            Invoke-Command -ComputerName $server.ip -ScriptBlock $SB2
            Add-Content $filename "`r`nInstall Completed!`r`n"
            Add-Content $filename "`r`nCan't Install...`r`n$client_name`r`n$client_ip`r`n"
    Formatting aside, the Add-Content lines work fine when run independently in the shell, but don't add the variables to the text file when the script runs.  My best theory is that the loop is not waiting for the command to complete and is jumping ahead causing the variable to keep resetting.  My goal is to log all the installs so I can go to the log to verify.  Any thoughts?
    Wednesday, March 8, 2017 4:12 PM


All replies

  • The variables are never defined in the script.


    • Marked as answer by Ari W. _ Friday, March 10, 2017 4:10 PM
    Wednesday, March 8, 2017 4:22 PM
  • You need to write a short example script that contains only the absolute minimum amount of code needed to reproduce the problem.

    In other words, you need to follow the principle of reduction. This means to simplify the problem to the smallest possible script that still demonstrates the problem. This boils the problem down to its essence, thereby allowing us to focus on the specific problem and not have to wade through (and possibly debug) unrelated code. Reduction is also a useful exercise for you, because it allows you to verify that the problem really is what you think it is, rather than being a side effect of some other part of the script.*

    * Special thanks to Raymond Chen (The Old New Thing).

    -- Bill Stewart [Bill_Stewart]

    Wednesday, March 8, 2017 6:03 PM
  • The variables are never defined in the script.


    You are absolutely right! I had copied this from a different script and forgot to change "client" to "server" in every place.  Thanks for catching that!
    Friday, March 10, 2017 4:12 PM