用户名的PowerShell Get-ChildItem

时间:2011-02-22 17:40:14

标签: powershell

我需要有关此代码的帮助:

#Set the starting directory to C:\Users
Set-Location "C:\Users\"

#Creates and empty array
$userdirs = New-Object System.Collections.ArrayList($null)

#List of all directories in Documents and Settings and this list is then manipulated to output the full directory path
$dirs = Get-ChildItem | Select-Object FullName | Where-Object {!($_.psiscontainer)} | foreach {$_.FullName}

#Adds the results of the Get-ChildItem manipulation to the array $userdirs
$userdirs.AddRange($dirs)

#Testing each member of array
#echo $userdirs
foreach ($dir in $userdirs){
    if ($dir -contains *[Environment]::UserName*){
        echo This path contains username
    }
    Else{
        echo This path does not
    }
}

代码的目的是列出C:\Users文件夹中的所有目录,然后测试包含当前登录用户用户名的目录。将来,If Else部分将执行测试路径,然后在目录存在的情况下执行文件复制,每个目录都包含用户名。目前,我得到的只是:

  

您必须在'-contains'运算符的右侧提供值表达式。
  在C:\ testpath.ps1:12 char:31
  + if($ dir -contains<<<< [Environment] :: UserName ){
     + CategoryInfo:ParserError:(:) [],ParentContainsErrorRecordException
     + FullyQualifiedErrorId:ExpectedValueExpression

我的印象是我可以使用-contains工具来测试带有两个通配符的字符串,所以我想知道我哪里出错了。

1 个答案:

答案 0 :(得分:2)

这是你可能想要的:

Set-Location "C:\Users\"
$dirs = Get-ChildItem | ? { $_.psiscontainer } | % { $_.FullName }

foreach ($dir in $userdirs)
{
    if ($dir -match $env:USERNAME)
    {
        Write-Host "$dir - This path contains username"
    }
}

您的方法中有两个(多个)问题

$dirs = Get-ChildItem | Select-Object FullName `
| Where-Object {!($_.psiscontainer)} | foreach {$_.FullName}

执行select-object后,无法访问原始DirectoryInfo对象

-contains用于对象列表,您可能需要-match

相关问题