Using $? And !$? in PowerShell

 

   This is very helpful when you need to validate the last operation if it has information (values), in other words, if the last command was successfully.
For example, I want to validate if a folder exists in my computer:
PS C:\> $Folder = Get-ChildItem -Path c:\temp
if($?)
{
    Write-Host “The folder Temp already exists” -ForegroundColor Yellow
}
else
{
    Write-Host “The folder Temp does not exists” -ForegroundColor Yellow
}
The folder Temp already exists
PS C:\> 
Let’s give it a try with a folder that doesn’t exist
PS C:\> $Folder = Get-ChildItem -Path c:\temp\NewOne
if($?)
{
    Write-Host “The folder Temp already exists” -ForegroundColor Yellow
}
else
{
    Write-Host “The folder Temp does not exists” -ForegroundColor Yellow
}
Get-ChildItem : Cannot find path ‘C:\temp\NewOne’ because it does not exist.
At line:1 char:11
+ $Folder = Get-ChildItem -Path c:\temp\NewOne
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\temp\NewOne:String) [Get-Chil
   dItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChi
   ldItemCommand
The folder Temp does not exists
PS C:\> 
Yo can use !$?also, just change the order in the if-else. I mean first the validation if the result will be false, it’s easier if we see this example:
PS C:\> $Folder = Get-ChildItem -Path c:\temp
if(!$?)
{
    Write-Host “The folder Temp does not exists” -ForegroundColor Yellow
}
else
{
    Write-Host “The folder Temp already exists” -ForegroundColor Yellow
}
The folder Temp already exists
PS C:\> 
Now let’s try with a folder that does not exist
PS C:\> $Folder = Get-ChildItem -Path c:\temp\NewOne
if(!$?)
{
    Write-Host “The folder Temp does not exists” -ForegroundColor Yellow
}
else
{
    Write-Host “The folder Temp already exists” -ForegroundColor Yellow
}
Get-ChildItem : Cannot find path ‘C:\temp\NewOne’ because it does not exist.
At line:1 char:11
+ $Folder = Get-ChildItem -Path c:\temp\NewOne
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\temp\NewOne:String) [Get-Chil
   dItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChi
   ldItemCommand
The folder Temp does not exists
PS C:\>
Thanks for reading

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s