Need Batch or Powershell script to find some files by its content (xls file with some string) and then upload to ftp server.
###########################################################
$Path = "f:/temp"
$Text = "123456"
$PathArray = #()
$Results = "F:/PROFIT/INSTALL/backup/search/test.txt"
# This code snippet gets all the files in $Path that end in ".txt".
Get-ChildItem $Path -Filter "*.txt" -Recurse|
Where-Object { $_.Attributes -ne "Directory"} |
ForEach-Object {
If (Get-Content $_.FullName | Select-String -Pattern $Text) {
$PathArray += $_.FullName
$PathArray | % {$_} | Out-File $Results
}
}
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}
#we specify the directory where all files that we want to upload
$Dir="F:/PROFIT/INSTALL/backup/search"
#ftp server
$ftp = "ftp://127.0.0.1"
$user = "ftp"
$pass = "ftp"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
#list every sql server trace file
foreach($item in (dir $Dir "*.*")){
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
}
Tried this, but each time have a problem:
Uploading test.txt... Исключение при вызове "UploadFile" с "2"
аргументами: "Невозможно разрешить уда ленное имя:
'127.0.0.1test.txt'" F:\PROFIT\INSTALL\backup\search\search.ps1:36
знак:5
+ $webclient.UploadFile($uri, $item.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
You have an error on concatenation of server and file name. Try Something like this :
#variables
$PathToSearch = "c:\temp"
$SearchText = "hello"
$Results = "c:\temp\test.txt"
$ftp = "ftp://127.0.0.1/"
$user = "ftp"
$pass = "ftp"
#get liste file to found with string
$PathArray=Get-ChildItem $PathToSearch -Filter "*.txt" -Recurse -file | Select-String -Pattern $SearchText | get-item | select Name, FullName
Write-Host "Files founded :"
$PathArray.FullName
#send to ftp server
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
$PathArray | % {
$uri = New-Object System.Uri($ftp+$_.Name)
$webclient.UploadFile($uri, $_.FullName)
$_.FullName | Out-File -FilePath $Results -Append
}
$webclient.Dispose()
Related
I'm trying to create a powershell script which checks a log file for lines of text and if the line exists restarts a service and resets/archives the log. I got it working before with 1 "checkstring" if you will, but I've been struggling to get it to work with a list of strings. Could anyone help me figure out where I'm going wrong?
This is the code I'm currently using:
$serviceName = "MySQL80"
$file = "test.txt"
$pwd = "C:\tmp\"
$checkStrings = New-Object System.Collections.ArrayList
# Add amount of checkstrings
$checkStrings.add("Unhandled error. Error message: Error retrieving response.")
$checkStrings.add("Unhandled error. Error message: Error retrieving response. Second")
$logName = "ServiceCheck.log"
$backupFolder = "Archive"
$logString = (Get-Date).ToString("ddMMyyyyHHmmss"), " - The service has been reset and the log moved to backup" -Join ""
Set-Location -Path $pwd
if(Test-Path -Path $file) {
if(Test-Path -Path $backupFolder) {
} else {
New-Item -Path $pwd -Name $backupFolder -ItemType "director"
}
foreach ($element in $checkStrings) {
$containsWord = $fileContent | %{$_ -match $element}
if ($containsWord -contains $true) {
Restart-Service -Name $serviceName
$backupPath = $pwd, "\", $backupFolder, "\", $date, ".log" -join ""
$currentFile = $pwd, "\", $file -join ""
Copy-Item $currentFile -Destination $backupPath
Get-Content $currentFile | select-string -pattern $checkString -notmatch | Out-File $currentFile
if(Test-Path -Path $logName) {
Add-Content $logName $logString
} else {
$logString | Out-File -FilePath $logName
}
}
}
}
I am trying to replace some of the sub-strings with some values across multiple files. I have written this code to do so.
$dirPath = 'C:\repos\sync_cpc_cva\ExpressV2\Parameters\AG08\KeyVault'
$ConfigPath = 'C:\repos\sync_cpc_cva\config.json'
$lookupTable = #{}
(Get-Content -Raw -Path $configPath | ConvertFrom-Json).psobject.properties | Foreach { $lookupTable[$_.Name] = $_.Value }
Get-ChildItem -Path $dirPath -Recurse -Filter *.json |
Foreach-Object {
Get-Content $_.FullName | ForEach-Object {
$line = $_
$lookupTable.GetEnumerator() | ForEach-Object {
if($line -match $_.Key) {
$line = $line -replace $_.Key, $_.Value
}
}
$line
} | Set-Content -Path $_.FullName
}
If I print the content, it has replaced all the values correctly, however, it is unable to set the contents into the same file. And I am getting following error while running the code :
Set-Content : The process cannot access the file
'C:\repos\sync_cpc_cva\ExpressV2\Parameters\AG08\KeyVault\KeyVault.USNat.json' because it is being used by another process.
At C:\repos\sync_cpc_cva\filltest.ps1:22 char:9
+ } | Set-Content -Path $_.FullName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Set-Content], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.SetContentCommand
Any idea how can I replace the sub-strings in the same file?
You have several inner foreach-object loops, so you modify the $_ operator while being used. I dont think this can work. Revolve it like this:
$lookupTable = #{}
(Get-Content -Raw -Path $configPath | ConvertFrom-Json).psobject.properties | Foreach { $lookupTable[$_.Name] = $_.Value }
$files = Get-ChildItem -Path $dirPath -Recurse -Filter *.json
foreach ($file in $files) {
$content = Get-Content $file.FullName
for($i=0;$i -lt $content.length; $i++) {
$lookupTable.GetEnumerator() | ForEach-Object {
$content[$i] = $content[$i] -replace $_.Key, $_.Value
}
}
$content | Set-Content $file.FullName
}
Hello and thank you in advance. Currently I have a script running that downloads files from one location to another. I'm trying to clean up the script to only download files that have _Lthumb in the file name. Any help would be greatly appreciated.
The following line in which I added is causing the problems. Wheni remove it, the script runs fine, but it doesn't filter the data by _Lthumb:
| Where-Object {$_.Name -Match '*_Lthumb'}
Here is the script, including the portion above that breaks it:
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
######################## Start Variables ########################
$destination = "\\pulse-dev.hinshawad.com\C$\ProfilePhotos\ProfilePictures"
$webUrl = "http://mysites.hinshawad.com"
$listUrl = "http://mysites.hinshawad.com/user photos/profile pictures/"
##############################################################
$web = Get-SPWeb -Identity $webUrl
$list = $web.GetList($listUrl)
function ProcessFolder {
param($folderUrl)
$folder = $web.GetFolder($folderUrl)
foreach ($file in $folder.Files | Where-Object {$_.Name -Match '*_Lthumb'} ) {
#Ensure destination directory
$destinationfolder = $destination + "/" + $folder.Url
if (!(Test-Path -path $destinationfolder))
{
$dest = New-Item $destinationfolder -type directory
}
#Download file
$binary = $file.OpenBinary()
#$stream = New-Object System.IO.FileStream($destinationfolder + "/" + $file.Name), Create
$stream = New-Object System.IO.FileStream($destinationfolder + "/" + ($file.Name -replace "_Lthumb")), Create
$writer = New-Object System.IO.BinaryWriter($stream)
$writer.write($binary)
$writer.Close()
}
}
#Download root files
ProcessFolder($list.RootFolder.Url)
#Download files in folders
#foreach ($folder in $list.Folders) {
#ProcessFolder($folder.URL)
#}
This is my code but i dont know what i need to supply:
$ServerList = Get-Content "C:\Users\munjanga\Desktop\Execute\Testing\servers.txt"
$ServerList
$Header="FolderPath,IdentityReference,AccessControlType,IsInherited,InheritedFlags,PropagationFlags"
Add-Content -Value $Header -Path $Output
Foreach ($Server in $ServerList) {
$output = "\\$server\C:\Users\munjanga\Desktop\Execute\Testing $server.output.csv"
Del $Output -ErrorAction SilentlyContinue
$RootPath ="\\$Server\C:\system.sav"
$Folders = dir $RootPath -recurse | where {$_.psiscontainer -eq $true} -ErrorAction SilentlyContinue
Add-Content -Value "$Header" -Path $Output
Foreach ($Folder in $Folders){
$ACLs = get-acl $Folder.fullname | ForEach-Object { $_.Access }
Foreach ($ACL in $ACLs){
$OutInfo = $Folder.Fullname + "," + $ACL.IdentityReference + "," + $ACL.AccessControlType + "," + $ACL.IsInherited + "," + $ACL.InheritanceFlags + "," + $ACL.PropagationFlags
Add-Content -Value $OutInfo -Path $output -ErrorAction SilentlyContinue
}
}
}
In line 4 you are invoking the Add-Content cmdlet, which requires a something to be passed to -Path, you are trying to use $Output, which is an empty (null) variable.
Assuming you are getting the warning on line 12 when calling Where-Object? It looks like you are trying to do a directory listing on a unc path that doesnt exist, getting nothing back to pipe to where. Is \$Server\C:\system.sav really supposed to be the admin share a la \$Server\C$\system.sav ?
I am using the following code to select a folder through the Windows Forms "Browse" function and then pass that path to the gci cmdlet
cls
Function Get-Directory($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
$OpenfolderDialog = New-Object System.Windows.Forms.FolderBrowserDialog
$OpenfolderDialog.RootFolder = $initialDirectory
$OpenfolderDialog.ShowDialog()| Out-Null
$StartDir = $OpenfolderDialog.SelectedPath
Return $StartDir | Out-String
}
$myDir = Get-Directory -initialDirectory "Desktop"
$Child = gci -path $mydir -r -Filter *.jpg
Foreach ($item in $Child) {Move-Item -path $item.pspath -Destination $myDir -Force}
but I get these errors:
***At C:\Test\Combine Pics2.ps1:17 char:13
+ $Child = gci <<<< -path $mydir -r -Filter *.jpg
+ CategoryInfo : ObjectNotFound: (C:\Test
:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Move-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\Test\Combine Pics2.ps1:19 char:43
+ Foreach ($item in $Child) {Move-Item -path <<<< $item.pspath -Destination $myDir -Force}
+ CategoryInfo : InvalidData: (:) [Move-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.MoveItemCommand***
The $myDir variable is of type String, why does it not pass to the -path parameter.
What if the user canceled the dialog? Give this a try:
Function Get-Directory($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenfolderDialog = New-Object System.Windows.Forms.FolderBrowserDialog
$OpenfolderDialog.RootFolder = $initialDirectory
$result = $OpenfolderDialog.ShowDialog()
if($result -eq 'ok')
{
$OpenfolderDialog.SelectedPath
}
else
{
"canceled"
}
}
$mydir = Get-Directory -initialDirectory Desktop
if($mydir -ne 'canceled')
{
gci -path $mydir
}
Try this:
Function Get-Directory($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$OpenfolderDialog = New-Object System.Windows.Forms.FolderBrowserDialog
$OpenfolderDialog.RootFolder = $initialDirectory
if ($OpenfolderDialog.ShowDialog() -eq "OK") {
#Continue only if a folder was selected
$OpenfolderDialog.SelectedPath
}
}
$myDir = Get-Directory -initialDirectory "Desktop"
#Continue only if a folder was selected
if($myDir) {
$Child = Get-ChildItem -path $mydir -Recurse -Filter *.jpg
Foreach ($item in $Child) {
Move-Item -path $item.pspath -Destination $myDir -Force
}
}
I cleaned it up with a few if-tests so it doesn't return errors when people cancel the dialog. There was no need to Out-String as SelectedPath returns a single string by itself.
I got a newline and carriage return at the end of the $mydir value, so try trimming with something like this to see if that is your issue:
$Child = gci -path $mydir.Trim("`r`n") -r -Filter *.jpg
Update: Better yet, just lose the Out-String in your function:
Return $StartDir