Tag Archives: powershell

Powershell comparison: $null on the left

When I write powershell scripts, I always use below method to check whether variable is null or not.

if ($variable -eq $null) {
}

When I use VScode, VScode suggested me to put $null to left. Why?

Check below example:

$object = @(1, $null, 2, $null)

# "not safe" comparison with $null, perhaps a mistake
if ($object -eq $null) {
	# -eq gets @($null, $null) which is evaluated to $true by if
	'This is called.'
}

# safe comparison with $null
if ($null -eq $object) {
	'This is not called.'
}

So, the right way to compare is always put $null on the left side.

if ($null-eq $variable) {
}

copy permissions from one folder to another folder (Windows)

There are several ways to do this:

The easiest way is to use powershell command:

get-acl \SOURCE/FOLDER | set-acl \TARGETFOLDER

You can also use iCACLS to backup the permission to a file and restore it.

#backup
icacls d:data /save ntfsperms.txt
#restore
icacls d: /restore ntfsperms.txt

Note: icacls doesn’t support restore drive root permission