Categories

Calling native commands from PowerShell

Every now and then I find myself facing task I am not sure how to solve using without using native commands. Just writing the native command followed by its parameters in PowerShell host and hitting Enter is usually not enough to run the command successfully. There are several ways to make the command work, let me show you the one I found most convenient.

In my examples I am going to use ‘icacls‘, native command that allows you to set file permissions easily. I don’t want to make any changes to your current files so first create a temporary file using technique shown in this tip and save its path into the $path variable.

PS> $path = [IO.Path]::GetTempFileName()

Next run the command as you would in Windows Command line to see it raise an exception in PowerShell:

You can also pass the command as named parameter or by position. Making calling the native commands easy.

In PowerShell 3.0, there is a new symbol called the stop-parsing symbol (–%) that makes using native commands a little easier. The –% symbol prevents PowerShell from parsing anything until the end of the line enabling you to call the command like this:

PS> Icacls $path --% /grant Administrators:(D,WDAC)

Notice that you must place the symbol after all the variables that should be expanded, in this case $path, making this approach applicable only in some cases. If you are finished playing with the temporary file you can delete it by this command:

Like this:

About the author: Jakub Jareš

Jakub Jareš is an IT professional with strong background in Windows desktop systems. He started with Powershell a few months ago, and couldn't let go ever since. Showing that with the right attitude, a bit of effort and lot of practice you can become advanced in Powershell in no time.