【问题标题】:PowerShell's Get-ChildItem for username用户名的 PowerShell Get-ChildItem
【发布时间】:2011-02-22 17:40:13
【问题描述】:

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

#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 [环境]::用户名){
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedValueExpression

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

【问题讨论】:

    标签: powershell


    【解决方案1】:

    这就是你可能想要的:

    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}
    

    选择对象后,不能访问原来的 DirectoryInfo 对象

    -contains 是一个对象列表,你可能想要-match

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多