In PowerShell, can Test-Path (or something else) be used to validate multiple files when declaring a string array parameter - powershell

I have a function that accepts a string array parameter of files and I would like to use Test-Path (or something else) to ensure that all the files in the string array parameter exists. I would like to do this in the parameter declaration if possible.
Is this possible?

You can use ValidateScript
param(
[parameter()]
[ValidateScript({Test-Path $_ })]
[string[]]$paths
)
For more documentation on parameter validation visit about_Functions_Advanced_Parameters

You can set the parameter to use a validation script like this:
Function DoStuff-WithFiles{
Param([Parameter(Mandatory=$true,ValueFromPipeline)]
[ValidateScript({
If(Test-Path $_){$true}else{Throw "Invalid path given: $_"}
})]
[String[]]$FilePath)
Process{
"Valid path: $FilePath"
}
}
It is recommended to not justpass back $true/$false as the function doesn't give good error messages, use a Throw instead, as I did above. Then you can call it as a function, or pipe strings to it, and it will process the ones that pass validation, and throw the error in the Throw statement for the ones that don't pass. For example I will pass a valid path (C:\Temp) and an invalid path (C:\Nope) to the function and you can see the results:
#("c:\temp","C:\Nope")|DoStuff-WithFiles
Valid path: c:\temp
DoStuff-WithFiles : Cannot validate argument on parameter 'FilePath'. Invalid path given: C:\Nope
At line:1 char:24
+ #("c:\temp","C:\Nope")|DoStuff-WithFiles
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (C:\Nope:String) [DoStuff-WithFiles], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,DoStuff-WithFiles
Edit: I partially retract the Throw comment. Evidently it does give descriptive errors when the validation fails now (thank you Paul!). I could have sworn it (at least used to) just gave an error stating that it failed the validation and left off what it was validating and what it was validating against. For more complex validation scripts I would still use Throw though because the user of the script may not know what $_ -match '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' means if the error throws that at them (validating IPv4 address).

As #Matt said. Test-Path already accepts pipeline input, so you really just have to send the array directly in:
#($path1, $path2) | Test-Path
Which then returns:
> #("C:\foo", "C:\Windows") | Test-Path
False
True
If you just want to know if ALL of them exist:
($pathArray | Test-Path) -notcontains $false
Which yields:
False

Related

ValidateScript unexpectedly returning false when condition is true

I have a PowerShell function I'm writing to build and execute a variety of logman.exe commands for me so I don't have to reference the provider GUIDs and type up the command each time I want to capture from a different source. One of the parameters is the file name and I am performing some validation on the parameter. Originally I used -match '.+?\.etl$' to check that the file name had the .etl extension and additionally did some validation on the path. I later decided to remove the path validation but neglected to change the validation attribute to ValidatePattern.
What I discovered was that while it worked perfectly on the machine I was using to author and validate it, on my Server 2016 Core machine it seemed to misbehave when calling the function but that if I just ran the same check at the prompt it worked as expected.
The PowerShell:
[Parameter(ParameterSetName="Server", Mandatory=$true)]
[Parameter(ParameterSetName="Client", Mandatory=$true)]
[ValidateScript({$FileName -match '.+?\.etl$'}]
[string] $FileName = $null
The Output:
PS C:\Users\Administrator> Start-TBLogging -ServerLogName HTTPSYS -FileName ".\TestLog.etl"
PS C:\Users\Administrator> Start-TBLogging : Cannot validate argument on parameter 'FileName'. The "$FileName -match '.+?\.etl$'" validation script
for the argument with value ".\TestLog.etl" did not return a result of True. Determine why the validation script failed,
and then try the command again.
At line:1 char:50
+ Start-TBLogging -ServerLogName HTTPSYS -FileName ".\TestLog.etl"
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Start-TBLogging], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Start-TBLogging
Trying it manually worked:
PS C:\Users\Administrator> $FileName = ".\TestLog.etl"
PS C:\Users\Administrator> $FileName -match '.+?\.etl$'
True
After changing the function to use ValidatePattern it works just fine everywhere but I was wondering if anyone could shed light on the discontinuity.
As Joshua Shearer points out in a comment on a question, you must use automatic variable $_ (or its alias form, $PSItem), not the parameter variable to refer to the argument to validate inside [ValidateScript({ ... })].
Therefore, instead of:
# !! WRONG: The argument at hand has NOT yet been assigned to parameter
# variable $FileName; by design, that assignment
# doesn't happen until AFTER (successful) validation.
[ValidateScript({ $FileName -match '.+?\.etl$' }]
[string] $FileName
use:
# OK: $_ (or $PSItem) represents the argument to validate inside { ... }
[ValidateScript({ $_ -match '.+?\.etl$' })]
[string] $FileName
As briantist points out in another comment on the question, inside the script block $FileName will have the value, if any, from the caller's scope (or its ancestral scopes).

Custom error from parameters in PowerShell

Is it possible to have ValidateScript generate a custom error message when a test fails, like say Test-Path?
Instead of this:
Test-Folder : Cannot validate argument on parameter 'Folder'. The "Test-Path $_ -Path Type Container" validation script for the argument with value "blabla" did not return a result of True. Determine why the validation script failed, and then try the comma and again.
It would be nice to have it report this instead in the $Error variable:
The 'Folder' is not found, maybe there are network issues?
Code:
Function Test-Folder {
Param (
[parameter(Mandatory=$true)]
[ValidateScript({Test-Path $_ -PathType Container})]
[String]$Folder
)
Write-Host "The folder is: $Folder"
}
Workaround 1:
I could remove the Mandatory=$true and change it as below. But this doesn't give me the correct Get-Help syntax and doesn't do the Test-Path validation, because it only checks if the parameter is present.
Function Test-Folder {
Param (
[parameter()]
[String]$Folder = $(throw "The $_ is not found, maybe there are network issues?")
)
Write-Host "The folder is: $Folder"
}
Workaround 2:
I found this workaround on a blog post, but the problem is that it generates two errors instead of one.
Function Test-Folder {
Param (
[parameter(Mandatory=$true)]
[ValidateScript({
if (Test-Path $_ -PathType Container) {$true}
else {Throw "The $_ is not found, maybe there are network issues?"}})]
[String]$Folder
)
Write-Host "The folder is: $Folder"
}
Workaround 3:
I could also try to make it more clear by adding a comment section. However, this is still not the desired result as the error needs to be readable to end users.
Function Test-Folder {
Param (
[parameter(Mandatory=$true)]
[ValidateScript({
# The folder is not found, maybe there are network issues?
Test-Path $_ -PathType Container})]
[String]$Folder
)
Write-Host "The folder is: $Folder"
}
Your ValidateScript should look something like this:
[ValidateScript({
try {
$Folder = Get-Item $_ -ErrorAction Stop
} catch [System.Management.Automation.ItemNotFoundException] {
Throw [System.Management.Automation.ItemNotFoundException] "${_} Maybe there are network issues?"
}
if ($Folder.PSIsContainer) {
$True
} else {
Throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' is not a container."
}
})]
That will give you a message like this:
Test-Folder : Cannot validate argument on parameter 'Folder'. Cannot
find path '\\server\Temp\asdf' because it does not exist. Maybe there are
network issues?
Or:
Test-Folder : Cannot validate argument on parameter 'Folder'. The path
'\\server\Temp\asdf' is not a container.
If the older versions of PowerShell are throwing a double error, you may need to test inside the function:
Function Test-Folder {
Param (
[parameter(Mandatory=$true)]
[String]$Folder
)
try {
$Folder = Get-Item $_ -ErrorAction Stop
} catch [System.Management.Automation.ItemNotFoundException] {
Throw [System.Management.Automation.ItemNotFoundException] "The '${Folder}' is not found, maybe there are network issues?"
}
if (-not $Folder.PSIsContainer) {
Throw [System.Management.Automation.ApplicationFailedException] "The path '${_}' is not a container."
}
Write-Host "The folder is: ${Folder}"
}
The part that I always hated in PowerShell was trying to figure out what error to catch; without catching all. Since I finally figure it out, here's how:
PS > Resolve-Path 'asdf'
Resolve-Path : Cannot find path '.\asdf' because it does not exist.
At line:1 char:1
+ Resolve-Path 'asdf'
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (asdf:String) [Resolve-Path], ItemNotFoundE
xception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand
PS > $Error[0].Exception.GetType().FullName
System.Management.Automation.ItemNotFoundException
You can just do
ValidateScript({Test-Path $_ -PathType Container}, ErrorMessage="Must exist")]
That gives you error messages like:
Cannot validate argument on parameter 'Folder'. Must exist
At least in current powershell versions (7.x at the time of writing this).
Generally, for you powershell-only devs, when you use attributes (stuff like [ValidateScript), then you can sometimes also set additional properties with the syntax as above. To see which properties, you can just google for the name of the attribute postfixed with "Attribute", eg "ValidateScriptAttribute", and then look at the "Properties" section for all writeable properties.
I think you've found the straightforward workarounds.
The parameter validation logic is extensible, but requires some C#. If you implement the abstract class System.Management.Automation.ValidateArgumentsAttribute, your implementation can throw a System.Management.Automation.ValidationMetadtaException that PowerShell will use to report the error, and you can naturally use any message you like when creating that exception.
I am not sure.
A suggestion: maybe you want to just trap the error, and make your own message.
trap [Error.Type] {
#"
The message you want displayed.
With maybe some additional information.
I.e.: The full message itself: {0}' -f $_.Error.Message;
continue;
}

How to provide Linux-style parameter names in a powershell script

I would like to create a Powershell script that takes parameters in the standard Linux style, i.e., --my-param, with a leading --. I thought this might be possible using the alias parameter attribute, as in
Param (
[parameter(Mandatory=$true)]
[alias("-my-param","p")]
[String]
$param
)
What I hoped with this was that the call
c:\src\ps\params.ps1 --my-param "x"
would be recognized as referring to the alias -my-param. Unfortunately, what I get is
C:\src\ps\params.ps1 : A positional parameter cannot be found that accepts argument 'x'.
At line:1 char:21
+ c:\src\ps\params.ps1 <<<< --my-param1 "x"
+ CategoryInfo : InvalidArgument: (:) [params.ps1], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,params.ps1
On the other hand, using the alias my-param in this lets me call the script with -my-param.
Is there a way of specifying parameter names with leading -- in Powershell?
Your syntax fails at tokenizer level. Compare:
[Management.Automation.PSParser]::Tokenize(
'Command -parameter',
[ref]$null
)
...and...
[Management.Automation.PSParser]::Tokenize(
'Command --parameter',
[ref]$null
)
As you can see former is seen by parser as parameter, latter - as argument.
So the only way would be parsing all arguments "internally" and guessing what is parameter (from your perspective), and what is argument.
I'm not aware of any libraries that will parse Unix-style parameters for you (which doesn't necessarily mean there isn't one...), but you could just not declare any parameters, and parse the parameters yourself in the body of the script.
This will create a hashtable of the parameters, where they keys are the parameter names and the values are the parameter values. Switch parameters will have null values.
$params = #{}
$MyInvocation.Line.Substring(($MyInvocation.Line.IndexOf('--') + 2)) -split ' --' | %{
$_ -match '(\S+) ?(.+)?' | Out-Null
$params.($matches[1]) = $matches[2]
}
$MyInvocation.Line gives you the command line that was used to invoke the script. $MyInvocation.Line.Substring(($MyInvocation.Line.IndexOf('--') + 2)) gives you everything following the first --.
$_ -match '(\S+) ?(.+)?' assigns the parameter name to the first match group, and the value to the second match group. The Out-Null prevents PowerShell from printing True for each iteration.
The reason I used (.+)? rather than (.*) is to make the values of switch parameters null. (.*) will match an empty string if there is nothing to match, making the value of $matches[2] an empty string, whereas (.+)? won't match, making $matches[2] null.
This is assuming that all parameters begin with --. If you want to allow a single hyphen, restrict single-dash parameter names to a single letter, or check for incorrectly declared parameters (for example throw an error if there's a triple-hyphen), you'll have to account for that in your code, but this is the basic idea.

Why doesn't $hash.key syntax work inside the ExpandString method?

The following Powershell script demonstrates the issue:
$hash = #{'a' = 1; 'b' = 2}
Write-Host $hash['a'] # => 1
Write-Host $hash.a # => 1
# Two ways of printing using quoted strings.
Write-Host "$($hash['a'])" # => 1
Write-Host "$($hash.a)" # => 1
# And the same two ways Expanding a single-quoted string.
$ExecutionContext.InvokeCommand.ExpandString('$($hash[''a''])') # => 1
$ExecutionContext.InvokeCommand.ExpandString('$($hash.a)') # => Oh no!
Exception calling "ExpandString" with "1" argument(s): "Object reference not set to an instance of an object."
At line:1 char:1
+ $ExecutionContext.InvokeCommand.ExpandString('$($hash.a)')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException
Anyone know why the $hash.key syntax works everywhere but inside explicit expansion? Can this be fixed, or do I have to suck it up and live with the $hash[''key''] syntax?
I use this method, since this bug exists in v4 (not in v5)
function render() {
[CmdletBinding()]
param ( [parameter(ValueFromPipeline = $true)] [string] $str)
#buggy
#$ExecutionContext.InvokeCommand.ExpandString($str)
"#`"`n$str`n`"#" | iex
}
Usage for your example:
'$($hash.a)' | render
The ExpandString api is not exactly meant for use from PowerShell scripts, it was added more for C# code. It's still a bug that your example doesn't work (and I think it's been fixed in V4), but it does mean there is a workaround - one that I recommend for general use.
Double quoted strings effectively (but not literally) call ExpandString. So the following should be equivalent:
$ExecutionContext.InvokeCommand.ExpandString('$($hash.a)')
"$($hash.a)"
I was trying to store text that prompts the user in a text file. I wanted to be able to have variables in the text file that are expanded from my script.
My settings are stored in a PSCustomObject called $profile and so in my text I was trying to do something like:
Hello $($profile.First) $($profile.Last)!!!
and then from my script I was trying to do:
$profile=GetProfile #Function returns PSCustomObject
$temp=Get-Content -Path "myFile.txt"
$myText=Join-String $temp
$myText=$ExecutionContext.InvokeCommand.ExpandString($myText)
which of course left me with the error
Exception calling "ExpandString" with "1" argument(s): "Object
reference not set to an instance of an object."
Finally I figured out I only needed to to store the PSCustomObject values I want in regular old variables, change the text file to use those instead of the object.property version and everything worked nicely:
$profile=GetProfile #Function returns PSCustomObject
$First=$profile.First
$Last=$profile.Last
$temp=Get-Content -Path "myFile.txt"
$myText=Join-String $temp
$myText=$ExecutionContext.InvokeCommand.ExpandString($myText)
And in the text I changed to
Hello $First $Last!!!

Passing an argument to a powershell script to be used for the Test-Path -include option?

this is my first time asking a question so bear with me. I am teaching myself powershell by writing a few basic maintenance scripts. My question is in regard to a clean up script I am writing which accepts arguments to determine the target directory and files to delete.
The Problem:
The script accepts an optional argument for a list of file extensions to look for when processing the deletion of files. I am trying to test for the existence of the files prior to actually running the delete. I use test-path with the –include parameter to run the check within a ValidateScript block. It works if I pass in a single file extension or no file extensions, however when I try to pass in more than one file extension it fails.
I have tried using the following variations on the code inside the script:
[ValidateScript({ Test-Path $targetDirChk -include $_ })]
[ValidateScript({ Test-Path $targetDirChk -include "$_" })]
[ValidateScript({ Test-Path $targetDirChk -include ‘$_’ })]
For each of the above possibilities I have run the script from the command line using the following variations for the multi extension file list:
& G:\batch\DeleteFilesByDate.ps1 30 G:\log *.log,*.ext
& G:\batch\DeleteFilesByDate.ps1 30 G:\log “*.log, *.ext”
& G:\batch\DeleteFilesByDate.ps1 30 G:\log ‘*.log, *.ext’
Example of the error message:
chkParams : Cannot validate argument on parameter 'includeList'. The " Test-Path $targetDirChk -include "$_" " validation script for the argument with value "*.log, *.ext" did not return true. Determine why the validation script failed and then try the command again.
At G:\batch\DeleteFilesByDate.ps1:81 char:10
+ chkParams <<<< #args
+ CategoryInfo : InvalidData: (:) [chkParams], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,chkParams
The full script is below. I have not yet added the actual code to delete files, because I am still working on accepting and validating the arguments passed in.
I have searched google and stackoverflow but I have not found a solution to this particular problem. I assume I am either doing something wrong with the code, or there is a better way to accomplish what I want to do.
Note:
I should mention that I also tried running the test-path with multiple file extensions outside of the script with no problems:
PS G:\batch\powershell> test-path G:\log\* -include *.log
True
PS G:\batch\powershell> test-path G:\log\* -include *.log, *.ext
True
Script:
# Check that the proper number of arguments have been supplied and if not provide usage statement.
# The first two arguments are required and the third is optional.
if ($args.Length -lt 2 -or $args.Length -gt 3 ){
#Get the name of the script currently executing.
$ScriptName = $MyInvocation.MyCommand.Name
$ScriptInstruction = #"
usage: $ScriptName <Number of Days> <Directory> [File Extensions]
This script deletes files from a given directory based on the file date.
Required Paramaters:
<Number of Days>:
This is an integer representing the number of days worth of files
that should be kept. Anything older than <Number of Days> will be deleted.
<Directory>:
This is the full path to the target folder.
Optional Paramaters:
[File Extensions]
This is the set of file extensions that will be targeted for processing.
If nothing is passed all files will be processed.
"#
write-output $ScriptInstruction
break
}
#Function to validate arguments passed in.
function chkParams()
{
Param(
[Parameter(Mandatory=$true,
HelpMessage="Enter a valid number of days between 1 and 999")]
#Ensure the value passed is between 1 and 999.
#[ValidatePattern({^[1-9][0-9]{0,2}$})]
[ValidateRange(1,999)]
[Int]
$numberOfDays,
[Parameter(Mandatory=$true,
HelpMessage="Enter a valid target directory.")]
#Check that the target directory exists.
[ValidateScript({Test-Path $_ -PathType 'Container'})]
[String]
$targetDirectory,
[Parameter(Mandatory=$false,
HelpMessage="Enter the list of file extensions.")]
#If the parameter is passed, check that files with the passed extension(s) exist.
[ValidateScript({ Test-Path $targetDirChk -include "$_" })]
[String]
$includeList
)
#If no extensions are passed check to see if any files exist in the directory.
if (! $includeList ){
$testResult = Test-path $targetDirChk
if (! $testResult ){
write-output "No files found in $targetDirectory"
exit
}
}
}
#
if ($args[1].EndsWith('\')){
$targetDirChk = $args[1] + '*'
} else {
$targetDirChk = $args[1] + '\*'
}
chkParams #args
-Include on Test-Path is a string[]. You probably want to mirror that definition:
[ValidateScript({ Test-Path $targetDirChk -include $_ })]
[String[]]
$includeList
And drop the "" from there because they will force the argument to be a string and thus trying to match a file that looks like `foo.log blah.ext.
You also have to either put parentheses around that argument when calling the function or remove the space.