I'm iterating through a directory tree but trying to filter out a number of things.
This is my cobbled together code;
Get-ChildItem -Path $pathName -recurse -Filter index.aspx* -Exclude */stocklist/* | ? {$_.fullname -NotMatch "\\\s*_"} | Where {$_.FullName -notlike "*\assets\*" -or $_.FullName -notlike ".bk"}
Remove the name index.aspx from the returned item.
I want to filter out any file that starts with and underscore.
Exclude anything that contains /stocklist/ in its path.
Exclude anything that contains /assets/ in its path.
And exclude anything that contains .bk in its path.
This is working for everything but for the .bk in it's path. I'm pretty sure it's a syntax error on my part.
Thanks in advance.
You can create a regex string and use -notmatch on the file's .DirectoryName property in a Where-Object clause to exclude the files you don't need:
$excludes = '/stocklist/', '/assets/', '.bk'
# create a regex of the folders to exclude
# each folder will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($excludes | ForEach-Object { [Regex]::Escape($_) }) -join '|'
Get-ChildItem -Path $pathName -Filter 'index.aspx*' -File -Recurse |
Where-Object{ $_.DirectoryName -notmatch $notThese -and $_.Name -notmatch '^\s*_' }
Related
So, i've been scratching my head for a while now and can't seem to figure it out.
I want to delete files and folders older than 'x' days <-- this works fine
I want to delete empty directories left behind <-- this works fine as well
I also want to have some exceptions: filenames and foldernames. The filename exception works fine, but folders don't. There is something strange though. If i put only 1 name in the array of folders i don't want to delete, it works just fine. But if i put multiple in, it suddenly doesn't work anymore?
I have the idea it might be something simple i'm completely missing
$limit = (Get-Date).AddDays(-120)
$path = "C:\Users\user\Documents\files"
$ExcludedFileNames = #("*file1*", "*file2*")
$ExcludedFolders = #("*folder1*", "*folder2*")
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force -exclude $ExcludedFileNames |
Where-Object {($_.FullName -notlike $ExcludedFolders) -and (!$_.PSIsContainer) -and ($_.LastWriteTime -lt $limit) } |
Remove-Item -Force
# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
Instead of $.FullName i tried $.Name
Instead of -notlike i tried -notin
I also tried removing the array and put the variables after where-object
I also tried to copy other code from lots of posts but didn't seem to help.
The problem is that -notlike expects a single string as it's right-hand side operand, and so the $ExcludedFolders variable is coerced into the stringvalue "*folder1* *folder2*".
The comparison 'C:\some\path\to\a\folder1\with\a\file.exe' -notlike '*folder1* *folder2*' obviously fails.
You can solve this by using the -notmatch regex operator instead:
$ExcludedFolders = #('folder1', 'folder2') # note that we no longer need the wildcards
# later
... |Where-Object {$_.FullName -notmatch ($ExcludedFolders.ForEach{[regex]::Escape($_)} -join '|') -and (-not $_.PsIsContainer) -and $_.LastWriteTime -lt $limit}
The | is the alternation operator in regex, effectively functioning as an OR
I would use wildcards on the file names to use with the -Exclude parameter, and create a regex string for the foldernames to exclude you can use in the Where-Object clause.
Something like this:
$limit = (Get-Date).AddDays(-120).Date # set to midnight instead of the current time
$path = 'C:\Users\user\Documents\files'
$ExcludedFileNames = '*file1*', '*file2*' # wildcards for the Exclude parameter
$ExcludedFolders = 'folder1','folder2' # can be a partial name, do not use wildcards here
# create a regex string for the folder names to exclude
# each item will be Regex Escaped and joined together with the OR symbol '|'
$FoldersToSkip = ($ExcludedFolders | ForEach-Object { [Regex]::Escape($_) }) -join '|'
# Delete files older than the $limit.
Get-ChildItem -Path $path -File -Recurse -Force -Exclude $ExcludedFileNames |
Where-Object {($_.DirectoryName -notmatch $FoldersToSkip) -and ($_.LastWriteTime -lt $limit) } |
Remove-Item -Force
# Delete any empty directories left behind after deleting the old files.
(Get-ChildItem -Path $path -Recurse -Directory -Force).FullName |
Where-Object { !( Get-ChildItem -Path $_ | Select-Object -First 1 ) } |
Sort-Object -Property Length -Descending |
Remove-Item -Force
We have a situation where the cp.exe and cp.dll are getting copied in build artifacts of all the folders and we want them only to be part of PS.Manager.Service and PS.A.Service folder/Artifacts.
From rest all the folders both the cp.exe and its cp.dll must be deleted. I tried doing that with the below script but It is not working. I am not sure what am I missing here.
Any suggestions would really help.
Thanks.
$SourceDirectory = "e:\cache\Agent03\2\s"
$EXcludeManagerFolder = "e:\cache\Agent03\2\s\PS.Manager.Service"
$EXcludeAFolder = "e:\cache\Agent03\2\s\PS.A.Service"
gci -path "$SourceDirectory" -Include "cp.exe, cp.dll" -Exclude "$EXcludeManagerFolder","$EXcludeAFolder " -Recurse -Force | Remove-Item -Recurse -Force
As zett42 already commented, Include, Exclude (and also Filter) only work on the objects Name, not the full path.
The easiest way is to create a regex string with the folders you need to exclude so you can match (or -notmatch in this case)
$SourceDirectory = "e:\cache\Agent03\2\s"
# create a regex of the files and/or folders to exclude
$exclude = 'PS.Manager.Service', 'PS.A.Service' # foldernames to exclude
# each item will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|'
(Get-ChildItem -Path $SourceDirectory -Include 'cp.exe', 'cp.dll' -File -Recurse).FullName |
Where-Object { $_ -notmatch $notThese } |
Remove-Item -Force
Get-ChildItem "I:\TEMP_Dir_SSN\" | %{
if($_.name -ne "fullpath.txt" -or $_.name -ne "SSN_FILES.txt"){
remove-item $_.fullname
}
}
There are two files in the same directory that I don't want to delete. I want to delete all but two .txt files. They need to be preserved in the same directory. However, the rest is garbage and can be removed.
You can utilize Where-Object in your pipeline to accomplish what you're trying to do.
Get-ChildItem "I:\TEMP_Dir_SSN\" |
Where-Object { (($_.Name -notlike 'fullpath.txt') -and
($_.Name -notlike 'SSN_FILES.txt')) } |
Remove-Item
Just a note for more terse reading/writing, you can use the built-in alias GCI and Where
I would use the Exclude parameter to exclude the files:
Get-ChildItem "I:\TEMP_Dir_SSN" -Exclude "fullpath.txt","SSN_FILES.txt" | Remove-Item
I want to get all files in subfolders, of the same root folder, that all contain the same string ("foo") in the name of the subfolder(s). Below gives me no error, and no output. I don't know what I'm missing.
Get-ChildItem $rootfolder | where {$_.Attributes -eq 'Directory' -and $_.BaseName -contains 'foo'}) | echo $file
Ultimately, I would like to not just echo their names, but move each file to a target folder.
Thank you.
Here is a solution that includes moving the child files of each folder to a new target folder:
$RootFolder = '.'
$TargetFolder = '.\Test'
Get-ChildItem $RootFolder | Where-Object {$_.PSIsContainer -and $_.BaseName -match 'foo'} |
ForEach-Object { Get-ChildItem $_.FullName |
ForEach-Object { Move-Item $_.FullName $TargetFolder -WhatIf } }
Remove -WhatIf when you are happy it's doing what it should be.
You might need to modify the Get-ChildItem $_.FullName part if you (for example) want to exclude sub-directories of the folders, or if you want to include child items in all subfolders of those paths, but not the folders themselves.
replace
Get-ChildItem $rootfolder | where {$_.Attributes -match 'Directory' -and $_.basename -Match 'foo'}) | echo $file
with
Get-ChildItem $rootfolder | where {($_.Attributes -eq 'Directory') -and ($_.basename -like '*foo*')} | Move-Item $targetPath
your request:
that all contain the same string ("foo")
you have to use the -like comparison operator. Also for exact match I would use -eq (case sensitive version is -ceq) instead of -match since its used for matching substrings and patterns.
workflow:
Gets all the files in directory, sending it through pipe to Where-Object cmdlet where you are filtering based on properties Attributes and Basename. When the filtering is done, its being sent to cmdlet Move-Item.
Adapt the first two vars to your environment.
$rootfolder = 'C:\Test'
$target = 'X:\path\to\whereever'
Get-ChildItem $rootfolder -Filter '*foo*' |
Where {$_.PSiscontainer} |
ForEach-Object {
"Processing folder: {0} " -f $_
Move $_\* -Destination $target
}
I'm creating a small script which will list EXE files on the computer.
$computername = get-content env:computername
get-childitem C: -recurse | ? {$_.fullname -notmatch 'C:\\Windows'} | where {$_.extension -eq ".exe"} | format-table fullname | Out-File "\\server\incomming\$computername.txt"
The problem is that -notmatch doesn't accept more statements. I could copy-paste ? {$_.fullname -notmatch 'C:\\Windows'} and use for other folders like Program Files (x86), Program Files and so on. But I wouldn't like to bloat a script too much.
Is there a way I could exclude numerous folders with -notmatch statement?
You can use the logical operators like -and for more complex logical expressions.
Get-ChildItem C:\ -Recurse | Where-Object { ($_.FullName -notmatch "C:\\Windows") -and ($_.FullName -notmatch "C:\\Program Files") }
For many paths, I'd add them to an array or a hash table before calling Get-ChildItem and use Where-Object check if the pipeline file object path is present in the array or hash table. Eventually, you have to list the paths somewhere, but not necessarily in a single command. For example:
$excludedPaths = #("C:\Windows", "C:\Program Files");
Get-ChildItem C:\ -Recurse | Where-Object { $excludedPaths -notcontains $_.Directory }
Thanks for the answers!
And is it possible to get output longer than it is now?
It is now something like 100 symbols and then it ends with dots if path is longer than that.
I've get something like this -
C:\my files\my programs\prog...
I would use something like this:
get-childitem -literalpath e:\*.exe -Recurse | where { $_.DirectoryName -notmatch "Windows" -and $_.DirectoryName -notmatch "MyOtherFiles"}