In my script I'm about to run a command
pandoc -Ss readme.txt -o readme.html
But I'm not sure if pandoc
is installed. So I would like to do (pseudocode)
if (pandoc in the path)
{
pandoc -Ss readme.txt -o readme.html
}
How can I do this for real?
The Test-Path Cmdlet $Folder = 'C:\Windows' "Test to see if folder [$Folder] exists" if (Test-Path -Path $Folder) { "Path exists!" } else { "Path doesn't exist." } This is similar to the -d $filepath operator for IF statements in Bash. True is returned if $filepath exists, otherwise False is returned.
Check if a file exists and show the properties of the file txt" if (Test-Path $fileToCheck -PathType leaf) { $file = Get-Item $fileToCheck $file. FullName $file. LastAccessTime $file. Length $file.
The Windows PATH environment variable is where applications look for executables -- meaning it can make or break a system or utility installation. Admins can use PowerShell to manage the PATH variable -- a process that entails string manipulation. To access the PATH variable, use: $env:Path.
-Leaf. An element that does not contain other elements, such as a file. The easiest way to get this information from the console is Get-Help Test-Path -Parameter PathType.
You can test through Get-Command (gcm)
if (Get-Command "pandoc.exe" -ErrorAction SilentlyContinue)
{
pandoc -Ss readme.txt -o readme.html
}
If you'd like to test the non-existence of a command in your path, for example to show an error message or download the executable (think NuGet):
if ((Get-Command "pandoc.exe" -ErrorAction SilentlyContinue) -eq $null)
{
Write-Host "Unable to find pandoc.exe in your PATH"
}
Try
(Get-Help gcm).description
in a PowerShell session to get information about Get-Command.
Here is a function in the spirit of David Brabant's answer with a check for minimum version numbers.
Function Ensure-ExecutableExists
{
Param
(
[Parameter(Mandatory = $True)]
[string]
$Executable,
[string]
$MinimumVersion = ""
)
$CurrentVersion = (Get-Command -Name $Executable -ErrorAction Stop).Version
If ($MinimumVersion)
{
$RequiredVersion = [version]$MinimumVersion
If ($CurrentVersion -lt $RequiredVersion)
{
Throw "$($Executable) version $($CurrentVersion) does not meet requirements"
}
}
}
This allows you to do the following:
Ensure-ExecutableExists -Executable pscp -MinimumVersion "0.62.0.0"
It does nothing if the requirement is met or throws an error it isn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With