Search code examples
powershellinstallationpsexec

PowerShell script - How to process result of executed command


I have a small script that copies files to a list of remote machines. In this script I use:

Copy-Item "$AppLocation\$AppName" -destination "\\$MachineName\c$\" -force

This can throw various types of errors. If this throws an error, I want to log the error to a file and then continue. My question is that I'd like to know what would be the right way to find out if the Copy-Item command was successful.

Next question is related:

psexec \\$MachineName -u $RemoteLogin -p $Remotepassword -s -i -d C:\$AppName

What would be a good way to find out how this command executed? I get a message in the console that it exited with 0 but I have no idea how I could get the return code into a local variable.

I can also use this:
(Get-WMIObject -ComputerName $MachineName -List | Where-Object -FilterScript {$_.Name -eq "Win32_Product"}).Install("C:\$AppName","","false")
which works fine, but still, no idea how to find out if it succeeded unless I read the output.

Thanks!


Solution

  • Concerning the first part of your question, you can use

    Copy-Item ... -ErrorAction Continue -ErrorVariable yourVariable
    

    Error action tells the cmdlet what to do if case of error , ErrorVariable will put any error in the variable of your choice ($yourVariable in the exemple).

    $? automatic variable contains the execution status of the last operation. If it's false, just check the content of $yourVariable to know what went wrong and do whatever you want with it (like write it in a file in your case).

    You can also use

    Copy-Item ... -ErrorAction Continue 2> [pathToLogFile]
    

    This will redirect the error stream of the cmdlet to a file of your choice...

    Concerning the second part of your question : $LASTEXITCODE contains the return code of your last executable.

    Have you considered using the remoting capabilities of Powershell 2 for more control ?

    Hope it helps

    Cédric