ValidateScript unexpectedly returning false when condition is true - powershell

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).

Related

Saving XML on remote machine using Invoke-Command

Basically, I'm loading the XML from my local machine, and then I'm trying to save it on a remote machine using Invoke-Command.
I know I can use Copy-item via UNC path, but it takes too long on some machines, and Invoke-Command is faster - I tested this already.
However, I think I'm passing the argument wrong?
The error I get is:
Method invocation failed because [System.String] does not contain a method named 'Save'.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
+ PSComputerName : -
This is how I'm passing it:
foreach ($serverPath in $serverLocations) {
if ($null -ne $serverPath) {
$generatedPath = "$(Get-Location)\Generated.ManageSQLJobs.xml"
[Xml]$generatedFile = Get-Content $generatedPath
Write-Log "INFO" "Checking on $serverPath" $ExecutionLogFullPath
$testPath = Invoke-Command -ComputerName "$serverPath" -ArgumentList [Xml]$generatedFile -ScriptBlock {
param (
$value
)
Test-Path -Path "C:\AppData\MonitoringConfig\"
if (!$testPath) {
$destinationPath = New-Item -Path "C:\AppData\" -Name "MonitoringConfig" -ItemType Directory
}
if ($testPath) {
$destinationPath = "C:\AppData\MonitoringConfig"
#Write-Log "INFO" "Exists on $serverPath." $ExecutionLogFullPath
}
$GetPathToDeleteXML = "C:\AppData\MonitoringConfig\Generated.ManageSQLJobs.xml"
if (Test-Path -Path $GetPathToDeleteXML) {
Remove-Item -Path * #-Filter Generated.ManageSQLJobs.xml
}
$GetPathForXML = "C:\AppData\MonitoringConfig\Generated.ManageSQLJobs.xml"
$value.Save($GetPathForXML.fullname)
}
}
}
-ArgumentList [Xml]$generatedFile
should be (note the (...)):
-ArgumentList ([Xml]$generatedFile)
[Xml]$generatedFile isn't recognized as an expression, because when PowerShell parses in argument mode (commands with arguments, shell-style), an initial [ isn't special.
In effect, your argument is interpreted as an expandable string, i.e. as if you had passed
"[Xml]$generatedFile".
Therefore, $value in your remotely executed script block received a [string] instance, not an [xml] instance, and strings don't have a .Save() method, which explains the error message.
Enclosing your argument in (...) forces its interpretation as an expression.
See this answer for a comprehensive overview of how PowerShell parses unquoted tokens in argument mode.
A general caveat re passing complex objects as arguments to code executed remotely / in background jobs:
Arguments passed to remote / background script blocks must undergo XML-based serialization and deserialization, because they pass computer / process boundaries.
Only a limited set of known types are deserialized faithfully (deserialized as the original type), others are emulated.
While [xml] instances, [string] instances and .NET primitive types such as [int] are faithfully deserialized, most other types are not.
See this answer for more information.

touch Function in PowerShell

I recently added a touch function in PowerShell profile file
PS> notepad $profile
function touch {Set-Content -Path ($args[0]) -Value ($null)}
Saved it and ran a test for
touch myfile.txt
error returned:
touch : The term 'touch' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ touch myfile
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (touch:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
With PowerShell there are naming conventions for functions. It is higly recommended to stick with that if only to stop getting warnings about it if you put those functions in a module and import that.
A good read about naming converntion can be found here.
Having said that, Powershell DOES offer you the feature of Aliasing and that is what you can see here in the function below.
As Jeroen Mostert and the others have already explained, a Touch function is NOT about destroying the content, but only to set the LastWriteTine property to the current date.
This function alows you to specify a date yourself in parameter NewDate, but if you leave it out it will default to the current date and time.
function Set-FileDate {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 0)]
[string[]]$Path,
[Parameter(Mandatory = $false, Position = 1)]
[datetime]$NewDate = (Get-Date),
[switch]$Force
)
Get-Item $Path -Force:$Force | ForEach-Object { $_.LastWriteTime = $NewDate }
}
Set-Alias Touch Set-FileDate -Description "Updates the LastWriteTime for the file(s)"
Now, the function has a name PowerShell won't object to, but by using the Set-Alias you can reference it in your code by calling it touch
Here is a version that creates a new file if it does not exist or updates the timestamp if it does exist.
Function Touch-File
{
$file = $args[0]
if($file -eq $null) {
throw "No filename supplied"
}
if(Test-Path $file)
{
(Get-ChildItem $file).LastWriteTime = Get-Date
}
else
{
echo $null > $file
}
}
If you have a set of your own custom functions stored in a .ps1 file, you must first import them before you can use them, e.g.
Import-module .\MyFunctions.ps1 -Force
To avoid confusion:
If you have placed your function definition in your $PROFILE file, it will be available in future PowerShell sessions - unless you run . $PROFILE in the current session to reload the updated profile.
Also note that loading of $PROFILE (all profiles) can be suppressed by starting a session with powershell.exe -NoProfile (Windows PowerShell) / pwsh -NoProfile (PowerShell (Core)).
As Jeroen Mostert points out in a comment on the question, naming your function touch is problematic, because your function unconditionally truncates an existing target file (discards its content), whereas the standard touch utility on Unix-like platforms leaves the content of existing files alone and only updates their last-write (and last-access) timestamps.
See this answer for more information about the touch utility and how to implement equivalent behavior in PowerShell.

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

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

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.

Powershell: Args/params not being populated

I have a PowerShell script:
param (
[Parameter(Mandatory=$true)][string]$input,
[Parameter(Mandatory=$true)][string]$table
)
Write-Host "Args:" $Args.Length
Get-Content $input |
% { [Regex]::Replace($_, ",(?!NULL)([^,]*[^\d,]+[^,]*)", ",'`$1'") } |
% { [Regex]::Replace($_, ".+", "INSERT INTO $table VALUES (`$1)") }
The Write-Host part is for debugging.
I run it as .\csvtosql.ps1 mycsv.csv dbo.MyTable (from powershell shell), and get
Args: 0
Get-Content : Cannot bind argument to parameter 'Path' because it is an empty s
tring.
At C:\temp\csvtosql.ps1:7 char:12
+ Get-Content <<<< $input |
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBinding
ValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl
lowed,Microsoft.PowerShell.Commands.GetContentCommand
I get exactly the same error with any parameters that I pass, also the same error if I try to use named parameters.
What can cause parameters not to be passed in?
UPDATE: PowerShell ISE asks me for these parameters using GUI prompts, then gives me the same error about them not being passed in.
Unless you marked a parameter with the ValueFromRemainingArguments attribute (indicates whether the cmdlet parameter accepts all the remaining command-line arguments that are associated with this parameter), Args is "disabled". If all you need is the arguments count call the special variable:
$PSBoundParameters.Count
Do not mix. Make use of $args or parameters.
Also do note that $input is a special variable, don't declare it as a parameter. http://dmitrysotnikov.wordpress.com/2008/11/26/input-gotchas/
You're calling your script with positional parameters (i.e. unnamed) and PowerShell doesn't know how to map them to your script parameters. You need to either call your script using the parameter names:
.\csvtosql.ps1 -input mycsv.csv -table dbo.MyTable
or update your script to specify your preferred order of positional parameters:
param (
[Parameter(Mandatory=$true,Position=0)]
[string]
$input,
[Parameter(Mandatory=$true,Position=1)]
[string]
$table
)