关于foreach循环


0
wchuang asked 9年 ago

foreach循环,变量为一串字符怎么解决。
如下?
元素列表为目录。
$pathlist=”‘c:\test1’,’c:\test2′”
foreach($path in $athlist)
{…}

Mooser Lee 管理员 replied 9年 ago

PS> $pathlist=”‘c:\test1’,’c:\test2′” -split ‘,’PS> $pathlist | foreach { $_.substring(1 , $_.length-2) }c:\test1c:\test2

5 Answers
1
Best Answer
Mooser Lee 管理员 answered 9年 ago

这是直接遍历的目录结构:

PS> dir | select FullName

FullName
--------
D:\DICM\test1
D:\DICM\test2
D:\DICM\test3
D:\DICM\test4

这是通过$dirList目录列表过滤的目录结构

PS> $dirList='D:\DICM\test1','D:\DICM\test2'
PS> dir | where { $dirList -contains $_.FullName }


    目录: D:\DICM


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        2014/11/11     21:49            test1
d----        2014/11/11     21:50            test2


这是通过$dirList目录列表过滤的目录,并且在foreach中查询子目录。

PS> dir | where { $dirList -contains $_.FullName } | foreach { dir $_}


    目录: D:\DICM\test1


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2014/11/11     21:49          0 test1.txt


    目录: D:\DICM\test2


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2014/11/11     21:50          0 test2.txt
Mooser Lee 管理员 replied 9年 ago

这里不需要考虑大小写,因为powereshell默认是大小写不敏感的。比如PS> ‘a’,’B’ -contains ‘b’True

0
Mooser Lee 管理员 answered 9年 ago
PS> $pathlist="'c:\test1','c:\test2'" -split ','
PS> $pathlist | foreach { $_.substring(1 , $_.length-2) }
c:\test1
c:\test2
0
Mooser Lee 管理员 answered 9年 ago
PS> $pathlist="'c:\test1','c:\test2'" -split ','
PS> $pathlist | foreach { $_.substring(1 , $_.length-2) }
c:\test1
c:\test2
0
Mooser Lee 管理员 answered 9年 ago
PS> $pathlist="'c:\test1','c:\test2'" -split ','
PS> $pathlist | foreach { $_.substring(1 , $_.length-2) }
c:\test1
c:\test2
wchuang replied 9年 ago

是这样的,想要遍历一个目录,让取得的目录与目录组的的对象匹配,匹配上的就执行。相当于遍历刚才的$PathList

0
Liu Liu answered 9年 ago
wchuang replied 9年 ago

是这样的,想要遍历一个目录,让取得的目录与目录组的的对象匹配,匹配上的就执行。相当于遍历刚才的$PathList