I have a script block which goes to the Dc and try linking a selected gpo and ou:
forEach ($line in $listBox1.selecteditems) {
try {
Invoke-Command -Session $s -ScriptBlock {New-GPLink -Name $using:line -Target $using:SWITCH -ErrorAction Stop | Out-Null}
$ResultsTextBox.AppendText("`r $line HAVE BEEN LINKED Successfully.`r")
} catch {
$ResultsTextBox.AppendText("`n $line IS NOT LINKED TO THIS OU`n")
}
}
Only problem here is the try catch wont work, what im trying to do is give the user information if he's trying to link an already linked gpo - ou. but what happens when i run this block is the user get output "... have been linked successfully" even the the link was already existed. and i will see an error output in the command line as follows:
The GPO named 'MSAVS-Policy1' is already linked to a Scope of Management with Path 'OU=Domain
Controllers,DC=shahar,DC=local'.
+ CategoryInfo : InvalidArgument: (Microsoft.Group...ewGPLinkCommand:NewGPLinkCommand) [New-GPLink], Argu
mentException
+ FullyQualifiedErrorId : UnableToCreateNewLink,Microsoft.GroupPolicy.Commands.NewGPLinkCommand
+ PSComputerName : dc01
Whats am i doing wrong here?
Since you're executing the New-GPLink
cmdlet remotely, we have 2 levels of error handling to consider - errors thrown by the commands inside the remote scriptblock, and then the errors (re-)thrown by Invoke-Command
.
The try
block is "blind" to what going on remotely, and can only catch the errors on the client, so Invoke-Command
will also have to treat throw errors as terminating, so add the parameter -ErrorAction
parameter to that as well:
try{
Invoke-Command {...} -ErrorAction Stop
}
catch{
# ...
}