Search code examples
powershellpowershell-4.0

Using Get-ChildItem with a string variable


I'm using Get-ChildItem to save file locations that match user-input parameters. I can't seem to figure out (I'm new to powershell) how to use string variables with cmdlets.

I'll define $search_param as it is in my script below.

I've tried using the built in debugger on powershell ise, and if anything it's confused me even more.

This is where I found that replacing the use of '$search_param' with the actual value of $search_param produced a csv output, but using '$search_param' gives no output. Some useful information might be that I defined $search_param with double quotations.

The line that is causing all the issues is:

Get-ChildItem 'C:\Users\USER\' -recurse '$search_param'

$search_param is defined as:

| where { $_.name -like "*peanut*" -or $_.name -like "*butter*" -or $_.name -like "*test*"} 
| where { $_.extension -in ".txt",".csv",".docx" } 
| where { $_.CreationTime -ge "08/07/1998" -and $_.CreationTime -le "08/07/2019" } 
| select FullName | Export-Csv -Path .\SearchResults.csv -NoTypeInformation

Funnily enough I had it all working before I went to lunch and came back to a different story..

I'm using Export-csv in another piece of my script and that is working as intended.

I may have touched something small that isn't related to the line I provided as I think this should be working..


Solution

  • Per Technician's comment:

    You can use invoke expression to "evaluate or run a specified string as a command and return the results of the expression or command."

    Invoke-Expression "Get-ChildItem 'C:\Users\SGouldin\' -recurse $search_param"
    

    From a little bit of research, relying on invoke expression isn't always the best practice. In my case, I needed it because of the way I was attempting to handle user input (some weeeeird string concatenation/joins).