I\'ve tried enclosing the following in an if statement so I can execute another command if this succeeds:
Get-WmiObject -Class Win32_Share -ComputerName $Ser
Or if a failure returns no standard output, that would work for an if statement:
if (! (Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'")) {
'command failed'
}
Also there's now the or symbol "||" in powershell 7:
Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" || 'command failed'
Try the $? automatic variable:
$share = Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'"
if($?)
{
"command succeeded"
$share | Foreach-Object {...}
}
else
{
"command failed"
}
From about_Automatic_Variables:
$?
Contains the execution status of the last operation. It contains
TRUE if the last operation succeeded and FALSE if it failed.
...
$LastExitCode
Contains the exit code of the last Windows-based program that was run.
There are instances where any of the options are best suitable. Here is another method:
try {
Add-AzureADGroupMember -ObjectId XXXXXXXXXXXXXXXXXXX -RefObjectId (Get-AzureADUser -ObjectID "XXXXXXXXXXXXXX").ObjectId -ErrorAction Stop
Write-Host "Added successfully" -ForegroundColor Green
$Count = $Null
$Count = 1
}
catch {
$Count = $Null
$Count = 0
Write-Host "Failed to add: $($error[0])" -ForegroundColor Red
}
With try and catch, you don't only get the error message returned when it fails, you also have the $count variable assigned the number 0. When the command is successful, your $count value returns 1. At this point, you use this variable value to determine what happens next.
you can try :
$res = get-WmiObject -Class Win32_Share -Filter "Description='Default share'"
if ($res -ne $null)
{
foreach ($drv in $res)
{
$Localdrives += $drv.Path
}
}
else
{
# your error
}