How to exclude directory in Get-ChildItem results? - powershell

My script is doing what I need it to do, but I would like to be able to exclude certain folders.
In this case, it would be \york\SedAwk\ and \york\_ROT\.
Now, if I only put one folder in the $exclude variable, it works as expected. It's when I put both (or more) that it excludes neither, and throws no errors either when running.
Here is the script:
param(
[string]$pattern,
[string]$path
)
$exclude = #('*\york\SedAwk\*','*\york\_ROT\*')
Get-ChildItem -path $path -Recurse -Filter *.html |
Where-Object{
ForEach-Object {
If (Get-Content $_.FullName | Select-String -Pattern "<h2>Stay Connected") {
Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<h2>Stay Connected" -Quiet
}
ElseIf (Get-Content $_.FullName | Select-String -Pattern "<h2>Soyez branch") {
Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<h2>Soyez branch" -Quiet
}
Else {
Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<\/main>" -Quiet
}
}
} |
Select Fullname | ?{$_.FullName -notlike $exclude}
And here is how I run it:
.\FindStringContent.ps1 -pattern "list-unstyled" -path "w:\test\york" | Export-CSV "C:\Tools\exclude.csv"

I don't like using the -Exclude parameter because it's not file/folder specific, if you have a file and a folder that matches the string you're excluding they'll both be excluded.
When i'm excluding files i exclude them based on the FullName property which you could put in your ForEach to check if any of the files is in your $exclude variable:
param(
[string]$pattern,
[string]$path
)
$exclude = 'SedAwk','_ROT'
Get-ChildItem -path $path -Recurse -Filter *.html |
Where-Object{$_.FullName -notlike $exclude -and ForEach-Object {
If ($exclude -notcontains $_.FullName) {
If (Get-Content $_.FullName | Select-String -Pattern "<h2>Stay Connected") {
Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<h2>Stay Connected" -Quiet
}
ElseIf (Get-Content $_.FullName | Select-String -Pattern "<h2>Soyez branch") {
Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<h2>Soyez branch" -Quiet
}
Else {
Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<\/main>" -Quiet
}
}
}
} | Select Fullname
Included suggested changes by TheMadTechnician

Related

cmdlet Get-Content at command pipeline position 1

I am trying to recursively find references of Constants.cs of an any other .cs files in a directory containing files with Paths. Name of the files are stored procedures and they have the references(Paths) for that stored procedure.
This is PowerShell Script that i have written.
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)]
[string]$ProceduresFile,
[Parameter(Position=1, Mandatory=$true)]
[string]$ReferencesDir,
[Parameter(Position=2, Mandatory=$true)]
[string]$Project,
[Parameter(Position=3, Mandatory=$false)]
[string]$OutputPath = "."
)
$ErrorActionPreference = "Stop"
$storedProcFromFile = [IO.File]::ReadAllLines($ProceduresFile)
function Search-PSfile
{
param(
[string] $ReferencesDir,
[string] $Project,
[string] $file
)
$procedureName = $file.Split(".")[0].ToLower()
$textName = "${procedureName}.txt"
$pattern = "\b${Project}\.\b"
#check for Constant.cs files in project directory-- returs true if present
$isConstantFile = [bool](Get-ChildItem -Path $ReferencesDir -Filter $textName -Recurse |
Get-Content |
Select-String -Pattern "\bConstants.cs\b" |
Select-String -Pattern $pattern -Quiet)
#check for .cs files in project directory besides Constants.cs .. returs true if present
$isOtherCsFile = [bool](Get-ChildItem -Path $ReferencesDir -Filter $textName -Recurse |
Get-Content |
Select-String -Pattern "\b.cs\b" |
Select-String -Pattern "\bConstants.cs\b" -NotMatch |
Select-String -Pattern $pattern -Quiet)
$filePattern = "\b${procedureName}\b"
#check for .sql files other than itself.. returs true if present
$isUsedSql = [bool](Get-ChildItem -Path $ReferencesDir -Filter $textName -Recurse |
Get-Content |
Select-String -Pattern "\.sql" |
Select-String -Pattern $filePattern -NotMatch -Quiet)
# if there are no constant files and no .sql file and no there .cs files then SP is not used
If(!$isConstantFile -and !$isUsedSql -and !$isOtherCsFile)
{
return $false
}
# If there are Constants.cs then write SP name in Used.txt end function
Elseif ($isConstantFile)
{
return $true
}
# If there are other .cs files then check if SP is commented out if yes then 'not used' else 'used'
Elseif ($isOtherCsFile)
{
Get-ChildItem -Path $ReferencesDir -Filter $textName -Recurse |
Get-Content |
Select-String -Pattern "\b.cs\b" |
Select-String -Pattern "\bConstants.cs\b" -NotMatch |
Select-String -Pattern $pattern |
ForEach-Object{
$isUnCommented = [bool](Get-Content |
Select-String -Pattern $filePattern |
Select-String -Pattern "\/\/" -NotMatch -Quiet)
if($isUnCommented)
{
return $true
}
else
{
return $false
}
}
}
# if there are no .cs files only .sql files then do a recusion and check for that .sql file
Elseif ($isUsedSql)
{
Get-ChildItem -Path $ReferencesDir -Filter $textName -Recurse |
Get-Content |
Select-String -Pattern "\.sql" |
Select-String -Pattern $filePattern -NotMatch |
ForEach-Object{
$sqlFile = (Get-Item $_).Name
Search-PSfile -ReferencesDir $ReferencesDir -Project $Project -file $sqlFile -OutputPath $OutputPath
}
}
}
function Write-PSfile
{
param(
[string]$OutputPath,
[string]$File,
[string]$FileName,
[string]$Text
)
$fileExist = Test-Path "${OutputPath}\${FileName}"
if(!$fileExist)
{
$line = "${File} | ${Text}"
New-Item -Path $OutputPath -Name $FileName -ItemType "file" -Value $line
}
else {
$line = "${File} | ${Text}"
$path = "${OutputPath}\${FileName}"
Add-Content -Path $path -Value $line
}
}
$storedProcFromFile | ForEach-Object{
$isUsed = Search-PSfile -ReferencesDir $ReferencesDir -Project $Project -file $_ -OutputPath $OutputPath
if($isUsed)
{
Write-PSfile -OutputPath $OutputPath -File $_ -FileName "Used.txt" -Text "Used"
}
else
{
Write-PSfile -OutputPath $OutputPath -File $_ -FileName "NotUsed.txt" -Text "Not Used"
}
}
Write-Host "Script Ran Successfully"
I am not sure why I am getting cmdlet Get-Content at command pipeline position 1 for second elseif Elseif ($isOtherCsFile)statement but others are working fine. Any Suggestion is welcome. Thankyou.

PowerShell Select-String still outputting blank space

I have a weird issue where I am blacklisting certain console output and it is successfully preventing the blacklisted lines from outputting to the console, but it is still including blank space where the line would be which makes the rest of the console jump around a lot and makes reading everything else impossible.
cd C:\Users\$env:UserName\AppData\LocalLow\VRChat\VRChat
$taco = Get-ChildItem -Attributes !Directory . | Sort-Object -Descending -Property LastWriteTime | select -First 1
Get-Content -Path $taco.name -tail 1 -Wait | Select-String -Pattern $contents -notMatch -SimpleMatch
Here is the full script
$file = '.\blacklist'
if (-not(Test-Path -Path $file -PathType Leaf)) {
try {
$null = New-Item -ItemType File -Path $file -Force -ErrorAction Stop
}
catch {
throw $_.Exception.Message
}
}
$blacklist = "blacklist"
$contents = Get-Content $blacklist
mode 300
$host.UI.RawUI.ForegroundColor = "White"
$host.UI.RawUI.BackgroundColor = "Black"
If ((Get-Content $file) -eq $Null) {
cd C:\Users\$env:UserName\AppData\LocalLow\VRChat\VRChat
$taco = Get-ChildItem -Attributes !Directory . | Sort-Object -Descending -Property LastWriteTime | select -First 1
Get-Content -Path $taco.name -tail 1 -Wait
}
else {
cd C:\Users\$env:UserName\AppData\LocalLow\VRChat\VRChat
$taco = Get-ChildItem -Attributes !Directory . | Sort-Object -Descending -Property LastWriteTime | select -First 1
Get-Content -Path $taco.name -tail 1 -Wait | Select-String -Pattern $contents -notMatch -SimpleMatch
}

Powershell : Get directory permission recursively

I am trying to get the CSV output like below so that user can filter in excel.
Folder,Group,Permission
I:\Folder1,corp\group1,ReadData,ExecuteFile,Synchronize
I:\Folder1\Folder2,corp\group2,ReadData,ExecuteFile,Synchronize
Below is what is started with. Very inefficient and does not give the desired CSV output. Will appreciate any help.
$output_file = $(get-date -f MM-dd-yyyy_HH_mm_ss)+'.txt'
"{0},{1},{2}" -f "Folder","Groups","Permissions"| add-content -path $output_file
$file_content = ''
function GetFolders($path = $pwd)
{
if( $path -ne $null) {
$new_row = Get-ACL $path | select -ExpandProperty Access | Where-Object IdentityReference -Like "CORP*" | SELECT $path, IdentityReference, FileSystemRights | Format-Table -HideTableHeaders | Out-String
$fileContent += $new_row
$fileContent | add-content -path $output_file
foreach ($item in Get-ChildItem $path)
{
if (Test-Path $item.FullName -PathType Container)
{
Write-Output $item.FullName
GetFolders $item.FullName
$new_row = Get-ACL $item.FullName | select -ExpandProperty Access | Where-Object IdentityReference -Like "CORP*" | SELECT $item.FullName, IdentityReference, FileSystemRights | Format-Table -HideTableHeaders | Out-String
$fileContent += $new_row
$fileContent | add-content -path $output_file
}
}
}
}
GetFolders "J:\"
You were on the right path but went off-course a bit.
Set-Content -Path $FileName -Value 'Folder,Groups,Permissions'
(Get-Acl -Path $Path).Access |
Where-Object -Property IdentityReference -like 'corp*' |
ForEach-Object {
Add-Content -Path $FileName -Value "$Path,$($_.IdentityReference),$($_.FileSystemRights -replace '\s')"
}
To be a little more fancy (if you want to edit the code in the subexpressions or something of that nature)
$Val = {"$Path,$($_.IdentityReference),$($_.FileSystemRights -replace '\s')"}
... -Value (&$Val) ...

PowerShell get-child item and get-content a few folders deep

My script below only works for 1 folder using the "$_" before prior to the location of the file:
get-childitem E:\WebSystems\Configs\ | Foreach-Object {get-content E:\WebSystems\Configs\$_\Web.config} | foreach-object {$_ -replace "Web1", "Web2"} | set-content E:\WebSystems\Configs\$_\Web.config}
How about two folders deep? ex: E:\WebSystems\Configs\Folder1\Folder2\Web.config
The following script doesn't work.
get-childitem E:\WebSystems\Configs\ | Foreach-Object {get-content E:\WebSystems\Configs\$_\$_\Web.config} | foreach-object {$_ -replace "Web1", "Web2"} | set-content E:\WebSystems\Configs\$_\$_\Web.config}
This should work:
get-childitem -recurse -include Web.Config | foreach-object { $name = $_.FullName; get-content $name } | foreach-object {$_ -replace "Web1", "Web2" } | set-content $name
I implore you to test this on an isolated temporary directory. You might want to try this at first:
get-childitem -recurse -include Web.Config | foreach-object { $name = $_.FullName; get-content $name } | foreach-object {$_ -replace "Web1", "Web2" } | set-content "$name.modified"

Replace multiple strings in a file using powershell

I am using following coe to replace the string
$folders=Get-ChildItem -Path "C:\temp\Database Scripts"
foreach($folder in $folders)
{
Write-Host $folder
$spath=[string]::Concat("C:\temp\Database Scripts\", $folder)
$subfolders=Get-ChildItem $spath
foreach($subfolder in $subfolders )
{
if($subfolder -match "Running Scripts")
{
$subfolerpath=[string]::Concat($spath,"\",$subfolder,"\*")
$files =get-childitem -Path $subfolerpath -include "AVEVAScripts*"
if($files -ne $null)
{
foreach( $file in $files)
{
Write-Host $file;
(Get-Content $file) | ForEach-Object {$_ -replace "DATABASE_USER","fhghjgj" `
-replace "DATABASE_PASSWORD", "DFGHFHJGJH" } |Set-Content $file
}
}
}
}
}
But ending up with following error.
Set-Content : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
Please help :)
Remove the $x in the end of Set-Content. $x is never declared.
Also, you could simplify it a lot. Ex:
Get-ChildItem -Filter "Running Scripts" -Path "C:\temp\Database Scripts" -Recurse | ForEach-Object {
Get-ChildItem -Path $_.FullName -Filter "AVEVAScripts*" -Recurse | ForEach-Object {
(Get-Content $_.FullName) | ForEach-Object {
$_ -replace "DATABASE_USER","fhghjgj" -replace "DATABASE_PASSWORD", "DFGHFHJGJH"
} | Set-Content $_.FullName
}
}
Or find all files that includes "AVEVAScripts" in it's name, then check if their full path includes "Running Scripts"
Get-ChildItem -Filter "AVEVAScripts*" -Path "C:\temp\Database Scripts" -Recurse |
Where-Object { $_.FullName -like "*Running Scripts*" } |
ForEach-Object {
(Get-Content $_.FullName) | ForEach-Object {
$_ -replace "DATABASE_USER","fhghjgj" -replace "DATABASE_PASSWORD", "DFGHFHJGJH"
} | Set-Content $_.FullName
}