3

In my current powershell script I have hash table with values. Am using this syntax

$x = $f.contains("$k")

but I figured recently that am having problems with this approach I was wondering if powershell has something that says "starts with," or related, that would search thru the hash table with "starts with" instead of contains

Example of the hash table:

"bio.txt" = "server1\datafiles\bio";
etc.......

EDIT Sample from comments

foreach ($key in $filehash.keys) { 
    $path = $filehash.get_Item($key)
    $filecount = 0
    foreach ($file in $FileArray) { 
        if ($file.LastWriteTime -lt($(GetDate).adddays(-1))) { 
            [string] $k = $key.ToLower()
            [string] $f = $file.name.ToLower() 
            if ($x = $f.contains("$k")) { } 
        }
    }
}
9
  • Are you searching for the keys or the values? Commented Feb 21, 2013 at 14:41
  • the example that caused this problem was lets say I had Commented Feb 21, 2013 at 14:43
  • "bio.txt" = "server1\datafiles\bio"; Commented Feb 21, 2013 at 14:43
  • 1
    "bio.csv" = "server1\datafiles\bio\csv"; Commented Feb 21, 2013 at 14:44
  • Use "Shift + return" for a new line Commented Feb 21, 2013 at 14:44

1 Answer 1

6

Try using -like to check if a string starts with yourvalue. I rewrote your sample in the comments to use it:

$filehash.GetEnumerator() | foreach {
    #$_ is now current object from hashtable(like foreach)
    #$_.key is key and $_.value is path
    $filecount = 0
    foreach ($file in $FileArray) {
        if ( ($file.LastWriteTime -lt $((Get-Date).AddDays(-1))) -and ($file.name -like "$($_.Key)*") ) {
            #process file

        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

foreach ($key in $filehash.keys) { $path = $filehash.get_Item($key) $filecount = 0 foreach ($file in $FileArray) { if ($file.LastWriteTime -lt($(GetDate).adddays(-1))) { [string] $k = $key.ToLower() [string] $f = $file.name.ToLower() if ($x = $f.contains("$k")) { }
instead of using contains, am wondering if I can change it to starts with or something similar to it
Can't you just use: if ($f -like "$k*") { #process if filename starts with $k } ? See updated answer
if ($x = $f.StartsWith("$k")) this is what I was looking for ... thanks everyone :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.