I need help with this code:
#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
}
}
The aim of the code was to list all the directories in the C:\Users folder and then test for one that contained the current logging on users username. In the future the If Else part will carry out a test-path and then file copy if the directory exists for each occurence of a directory with the username in it. At present, all I get is this:
You must provide a value expression on the right-hand side of the ‘-contains’ operator.
At C:\testpath.ps1:12 char:31
+ if ($dir -contains <<<< [Environment]::UserName){
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedValueExpression
I was under the impression that I could use the -contains tool to test for a string with two wildcards so I am wondering where I am going wrong.
Here’s what you may want:
Two (of a number) of issues w/ your approach
After you do a select-object, you can’t access the original DirectoryInfo object
And
-containsis for a list of objects, you probably want-match