Find a particular file name existence and execute batch command - powershell

I am looking for a PS script which will search for a particular file name and check its existence. If file exists it should execute a batch command.
$version = "1.1.0"
$packageName = "example.DTO.$version"
Get-ChildItem "d:\Test" | Where-Object { $_.Name -match "$packageName.nupkg" }
and my batch command
C:\NugetRestore\nuget.exe push "d:\Test\$packageName.nupkg" saranuget -Source "http://123.456.78.90/myget" -Timeout 120
I am unable to integrate both this.

This covers where the test matches multiple files:
$version = "1.1.0"
$packageName = "example.DTO.$version"
$FileCheck = Get-ChildItem "d:\Test" | Where-Object { $_.Name -match "$packageName.nupkg" }
$FileCheck | ForEach-Object {
C:\NugetRestore\nuget.exe push "$($_.Fullname)" saranuget -Source "http://123.456.78.90/myget" -Timeout 120
}

Related

Create exception in L4j script

Hope anyone can help me out:
Trying to make an exception in $arrfiles for L4j code.
Original : $arrFiles | ? {$_ -match '.jar$'} | % {
My try:
$arrFiles | ? { ($_ -match '.jar$') -and ($_ -notmatch 'jbcdserver.jar')} | % {
I would like to make some exclusions but if i can get one should be fine.
$arrFiles giving me output like c:\program files\application\jbcdserver.jar
this is a peace of the script:
#get a list of all files-of-interest on the device (depending on scope) :: GCI is broken; permissions errors when traversing root dirs cause aborts (!!!)
$arrFiles=#()
foreach ($drive in $varDrives) {
gci "$drive `\"` -force | ? {$_.PSIsContainer} | % {
gci -path "$drive `\$_\" `-rec -force -include *.jar,*.log,*.txt -ErrorAction 0 | % {
$arrFiles+=$_.FullName
}
}
}
#scan i: JARs containing vulnerable Log4j code
write-host "====================================================="
write-host "- Scanning for JAR files containing potentially insecure Log4j code..."
$arrFiles | ? {$_ -match '.jar$'} | % {
if (select-string -Quiet -Path $_ "JndiLookup.class") {
write-DRMMAlert "! ALERT: Potentially vulnerable file at $($_)!"
write-DRMMDiag #($arrFiles | out-string)
if (!(test-path "$env:PROGRAMDATA\CentraStage\L4Jdetections.txt" -ErrorAction SilentlyContinue)) {set-content -path "$env:PROGRAMDATA\CentraStage\L4Jdetections.txt" -Value "! CAUTION !`r`n$(get-date)"}
Add-Content "$env:PROGRAMDATA\CentraStage\L4Jdetections.txt" -Value "POTENTIALLY VULNERABLE JAR: $($_)"
$script:varDetection=1
Write-EventLog -LogName "Application" -Source "Log4J" -EventID 1004 -EntryType Error -Message "ALERT!: Potentially vulnerable files gevonden, check Programdata\centrastage\L4Jdetections.txt"
exit 1
}
Not giving me any Exclusion in script

A parameter cannot be found that matches parameter name 'File'

Power shell script (delete old backup files)
$date = (get-date).AddDays(-10)
$files = Get-ChildItem -Path "\\\sc-sqlbackups\sqlbackups\SA144\Milli\teste" -Files | ?{$_.LastWriteTime -lt $date}
foreach ($file in $files) {
Write-Host "Removing $file"
$file | Remove-Item -ErrorAction SilentlyContinue
}
the above command runs without an issue in Windows powershell(Windows 10). But when I create a SQL Server job with the same command I get the
ERROR
A job step received an error at line 2 in a PowerShell script.
The corresponding line is
'$files = Get-ChildItem -Path "\\sc-sqlbackups\sqlbackups\SA144\Milli\teste" -File | ?{$_.LastWriteTime -lt $date} '. Correct the script and reschedule the job. The error information returned by PowerShell is: 'A parameter cannot be found that matches parameter name 'File'.
-Files is not support in old PS Verisons.
use Where-Object { $_.PSIsContainer -eq $false } Instead!

Powershell search path with wildcard-string-wildcard

I am trying to search a log file for updates that were not installed, then using the returned array install the updates. Problem is my files are named:
Windows6.1-KB3102429-v2-x64.msu
My parsed array has a item of KB3102429 how can I use a wild card - call the array item - then another wildcard .msu
my code is listed below:
# Read KBLIST.txt and create array of KB Updates that were not installed
$Failed = Get-Content -Path C:/Updates/KBLIST.txt | Where-Object {$_ -like '*NOT*'}
# create a list of all items in Updates folder
$dir = (Get-Item -Path "C:\Updates" -Verbose).FullName
# Parse the $Failed array down to just the KB#######
for($i = $Failed.GetLowerBound(0); $i -le $Failed.GetUpperBound(0); $i++)
{
$Failed[$i][1..9] -join ""
# Search the $dir list for files that contain KB####### and end in .msu then quiet install
Foreach($item in (ls $dir *$Failed[$i]*.msu -Name))
{
echo $item
$item = "C:\Updates\" + $item
wusa $item /quiet /norestart | Out-Null
}
}
It works down to the Foreach($item in (ls $dir *$Failed[$i]*.msu -Name)).
If I just use * instead of the wildcard,string,wildcard it returns a list of all the .msu files for the basic syntax it correct.
It was hard to follow your work since you used aliases, but I think this should be able to accomplish what you're looking for.
$UpdateFolder = 'C:\Updates'
$FailedUpdates = Get-Content -Path C:/Updates/KBLIST.txt | Where-Object {$_ -like '*NOT*'}
foreach ( $Update in $FailedUpdates )
{
Write-Host -Object "Update $Update failed"
$UpdatePath = Get-Item -Path "$UpdateFolder\*$Update*.msu" | Select-Object -ExpandProperty FullName
Write-Host -Object "`tReinstalling from path: $UpdatePath"
wusa $UpdatePath /quiet /norestart | Out-Null
}

Get-ChildItem error handling when using long file paths

I am trying to handle errors when scanning through folders. Let's say I have something like:
Get-ChildItem $somepath -Directory | ForEach-Object {
if(error occurred due to too long path) {
skip this folder then
} else {
Write-Host $_.BaseName
}
}
When I do this I print the folders in $somepath until one of them is too long and then the loop stops. Even when using SilentlyContinue. I want to print even after reaching a folder that is too long.
If you can install a non-ancient PowerShell version (3.0 or newer), simply prepend the path with \\?\ to overcome the 260-character limit for full path:
Get-ChildItem "\\?\$somepath" | ForEach {
# ............
}
You could try ignoring the files longer 260 characters by using the Where-Object cmdlet.
Get-ChildItem $somepath -Directory -ErrorAction SilentlyContinue `
| Where-Object {$_.length -lt 261} `
| ForEach-Object { Write-Host $_.BaseName }
Or you could use the following (Ref).
cmd /c dir $somepath /s /b | Where-Object {$_.length -lt 261}
I will add my solution since the neither on this page worked for me. I am using relative paths, so I can't use the \\ prefix.
$TestFiles = Get-ChildItem $pwd "*Tests.dll" -Recurse | Where-Object {$_.FullName.length -lt 261} | Select-Object FullName -ExpandProperty FullName | Where-Object FullName -like "*bin\Release*"
Write-Host "Found TestFiles:"
foreach ($TestFile in $TestFiles) {
Write-Host " $TestFile"
}

Write parts from filename including the first line in merged txt / csv -file with powershell

I'm currently working on a PowerShell script that reads out the default printer on several workstations and write the information in a textfile to a network drive. My last question regarding some text replacements inside the script was successfully solved. But now I work on the second part.
Get-WmiObject -Class Win32_Printer -Filter "Default = $true" | % {
$_.Name -replace '(?:.*)\\NDPS-([^\.]+)(?:.*)', 'PS-$1'
} | Out-File -FilePath "H:\daten\printer\$($env:COMPUTERNAME)_defaultprinter.txt"
Get-WmiObject Win32_Printer -Filter "Default = $true" `
| Select-Object -expandProperty Name `
| Out-File -FilePath "P:\batch\migration\Printer\$($env:COMPUTERNAME)_$($env:USERNAME)_defaultprinter.txt"
The last line of the provided code writes the default printer to the network drive. Now I have there nearly 1500 single txt-files. For better analysis I use the following PowerShell script to merge all the single txt files to one big file.
Get-ChildItem -path \\samplepath\prgs\prgs\batch\migration\Printer -recurse | ? {
! $_.PSIsContainer
} | ? {
($_.name).contains(".txt")
} | % {
Out-File -filepath \\samplepath\prgs\prgs\batch\migration\Printer\gesamt_printer.txt -inputobject (get-content $_.fullname) -Append
}
I receive a file wich contains the default printer information from every txt-file but I need the $($env:USERNAME)-part from the filename as a separate value in addition to the printer information in on line to use the data in Excel. Can someone please provide me a tip how to insert the part from filename in the merged file?
You could extract the username part from the file name like this:
$_.Name -match '^.*?_(.*)_.*?\.txt$'
$username = $matches[1]
The group in the regular expression (accsisible via $matches[1]) contains the text between the first and the last underscore in the filename.
You could use it like this:
$root = "\\samplepath\prgs\prgs\batch\migration\Printer"
$outfile = "$root\gesamt_printer.txt"
Get-ChildItem $root -Recurse | ? {
-not $_.PSIsContainer -and $_.Extension -eq ".txt"
} | % {
$_.Name -match '^.*?_(.*)_.*?\.txt$'
$username = $matches[1]
$content = Get-Content $_.FullName
"{0},{1}" -f ($content, $username) | Out-File $outfile -Append
}
You could also directly create a CSV:
$root = "\\samplepath\prgs\prgs\batch\migration\Printer"
$outfile = "$root\gesamt_printer.txt"
$getPrinter = { Get-Content $_.FullName }
$getUser = { $_.Name -match '^.*?_(.*)_.*?\.txt$' | Out-Null; $matches[1] }
Get-ChildItem $root -Recurse `
| ? { -not $_.PSIsContainer -and $_.Extension -eq ".txt" } `
| select #{n="Username";e=$getUser},#{n="Printer";e=$getPrinter} `
| Export-Csv $outfile -NoTypeInformation
Note that these code sample don't contain any checks to exclude file names that don't have at least two underscores in them.