how to get-content of text file on multiple servers using powershell - file-get-contents

I'm trying to see if I can read a specific txt file (last x rows) on multiple servers.
I have tried this but its incorrect, can you please help me out?
Get-Content C:\Users\admin\server.txt | ForEach-Object {Get-Content "C:\project\file.log" | Select -Last 20}
The file is located on the same folder on each server.
The server.txt has all server names to which i have access with my current user, like
Server1
Server2
Server3
Thank you!

okay, guessing your server.txt file contains server names like \Server1 \Server2 with a line containing a single server name? What I see is wrong is this.
1) Change your ForEach to
Foreach-object($)
2) Inside your Foreach build the correct path. The $ var will be \Server1 so append \c$\Project\file.log
Not sure why the underscore is not showing up but the $ needs an underscore after it.

$server_names = Get-Content "C:\Users\hostlist.txt"
Foreach ($server in $server_names) {Get-Content "\$server\c$\test.log" | Select -Last 20}

Related

WinSCP - How to download only folders/files 1 day old while excluding empty folders/files? [duplicate]

I am limited to PuTTY and WinSCP only.
I am trying to download log directories with log files. For example, I want to grab all log_files 6 days old or newer. log_dir2 and log_dir3 including the folders match the criteria, while log_dir1 and its files does not.
DIR/log_dir1/log_files % older than 6 days
DIR/log_dir2/log_files % meets criteria
DIR/log_dir3/log_files % meets criteria
My problem is that while the log_files of log_dir1 are not downloaded, the syntax I am currently using downloads the log_dir1 folder. Normally, not a big deal, but we are talking hundreds of log_dir folders (all empty as the files are older than 6 days). For reasons beyond my control, I cannot move or archive these old log directories with their log files.
My question is simply, how do I change my syntax to ignore folders that are older than 6 days as well as files.
get -filemask="*>6D" /DIR/* C:\temp
I have tried several different combinations of parameters and I have read the support page about Directory Masks and Path Masks. I cannot get any of them working (version issue?). Can anyone explain their syntax better than the help page. I will update tomorrow with the current version of WinSCP that I am using.
Time constraint in WinSCP file mask cannot be used for directories.
But you can prevent WinSCP from creating the empty folders. Use -rawtransfersettings switch with ExcludeEmptyDirectories setting.
get -rawtransfersettings ExcludeEmptyDirectories=1 -filemask="*>6D" /DIR/* C:\temp
This is the original answer, before WinSCP supported ExcludeEmptyDirectories. It might still be useful as a basis for implementations that have even more specific constraints.
You can implement this custom logic easily in PowerShell script with a use of WinSCP .NET assembly:
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "username"
Password = "password"
SshHostKeyFingerprint = "..."
}
$remotePath = "/remote/path"
$localPath = "C:\local\path"
$limit = (Get-Date).AddDays(-6)
$session = New-Object WinSCP.Session
# Connect
$session.Open($sessionOptions)
# Enumerate files to download
$fileInfos =
$session.EnumerateRemoteFiles(
$remotePath, $Null, [WinSCP.EnumerationOptions]::AllDirectories) |
Where-Object { $_.LastWriteTime -gt $limit }
foreach ($fileInfo in $fileInfos)
{
$localFilePath =
[WinSCP.RemotePath]::TranslateRemotePathToLocal(
$fileInfo.FullName, $remotePath, $localPath)
# If the corresponding local folder does not exist yet, create it
$localFileDir = Split-Path -Parent $localFilePath
if (!(Test-Path -Path $localFileDir))
{
Write-Host "Creating local directory $localFileDir..."
New-Item $localFileDir -ItemType directory | Out-Null
}
Write-Host "Downloading file $($fileInfo.FullName)..."
# Download file
$sourcePath = [WinSCP.RemotePath]::EscapeFileMask($fileInfo.FullName)
$transferResult = $session.GetFiles($sourcePath, $localFilePath)
# Did the download succeeded?
if (!$transferResult.IsSuccess)
{
# Print error (but continue with other files)
Write-Host ("Error downloading file ${remoteFilePath}: " +
$transferResult.Failures[0].Message)
}
}
$session.Dispose()
Write-Host "Done."
Run the script (download.ps1) like:
powershell.exe -ExecutionPolicy Unrestricted -File download.ps1

Why -NotMatch is not working while using within a PowerShell script?

I have one XML file. I want to search for a string and then delete that line from the file.
Now the problem is that when I run following code from PS console, it works fine - deletes the line which contains "test3". But when I put the same code inside a PS script and run it, it is NOT deleting the intended line. Can you please let me know if I am missing something?
test.txt:
test1
test2
test3
test4
test5
test6
Code:
$loc = "D:\test.txt"
$msg = "test3"
$newF = Get-Content -Path $loc | where {$_ -notmatch $msg}
$newF
I am using PSVersion: 5.1.14393.1358.
Works absolutely fine. See the picture below.
Works fine from the console also.
-notmatch is designed to work with a regex. I'd suggest using -notlike in the future. As others have stated, your limited example is not reproducible.
Doc on -notmatch: Link

Filtering text files in cmd?

Is there any way that one can filter a text file in Windows' CMD as with awk in shell script?
I have a somehow large file and I only need the last column from each row. This will be done extremely easy with awk, but I have no means of using that now.
Try this our
Get-Content .\test.csv | %{ $_.Split(',')[1]; }
or for more reference
check out this site
[1]: http://windows-powershell-scripts.blogspot.in/2009/06/awk-equivalent-in-windows-powershell.html
This will return every last term after the last comma in a .csv file for example:
#echo off
type "file.csv" | repl ".*,(.*)" "$1" >"newfile.txt"
This uses a helper batch file called repl.bat (by dbenham) - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
Place repl.bat in the same folder as the batch file or in a folder that is on the path.

powershell script that reads the last modified date of a folder

I need a script that reads the last modified date of a file and by whom it was modified and outputs to excel. I found a script that changes the modification date.
$a = get-date
$b = Get-ChildItem "C:\Intel" -recurse | ? { !$_.psiscontainer }
foreach ($i in $b)
{
$i.LastWriteTime = $a
}
$b
You can easily get the LastWriteTime by checking the LastWriteTime proprty of a file.
get-childitem * | select FullName,LastWriteTime,Owner
You can check the owner of a file which may or may not be the last person to modify depending on the file type. Some office files will change owner to the last person to write to them but I don't know that this is reliable.
get-childitem * | ForEach-Object {get-acl $_ | select owner}
NTFS doesn't log the last person to modify a file. You can either turn on auditing and check the system audit eventlog or look into the filesystemwatcher class and build a custom script that watches for changes to a folder. (Warning: this may cause performance issues.)

Get dbname from multiple web.config files with powershell

I would like to issue a powershell command to return me the connection string (specifically I am looking for the db name value) for all the web sites on a web server...
So I would like to see something like
site1 dbname=Northwind
site2 dbname=Fitch
site3 dbname=DemoDB
I have tried using the IIS Powershell snap-in... I thought I was close with this:
PS C:\Windows\system32> Get-WebApplication | Get-WebConfiguration -filter /connectionStrings/*
but... after looking at the results... my answer doesn't appear to be in there
I am very new to powershell - so excuse my ignornance and inexperience
Any help appreciated!
thanks!
Hopefully, this will get you started. This just assumes there will be a web.config file at the physical path of the web application's physical path. It does not recurse to find other web.config files in the web application. It also assumes your connection strings are in the connectionStrings configuration element.
Import-Module WebAdministration
Get-WebApplication | `
ForEach-Object {
$webConfigFile = [xml](Get-Content "$($_.PhysicalPath)\Web.config")
Write-Host "Web Application: $($_.path)"
foreach($connString in $webConfigFile.configuration.connectionStrings.add)
{
Write-Host "Connection String $($connString.name): $($connString.connectionString)"
$dbRegex = "((Initial\sCatalog)|((Database)))\s*=(?<ic>[a-z\s0-9]+?);"
$found = $connString.connectionString -match $dbRegex
if ($found)
{
Write-Host "Database: $($Matches["ic"])"
}
}
Write-Host " "
}
This post may give you an idea to start with. Basically load in the web.config file as an XML file and then just find the node where the connection string is.
Do something like $myFile = ([xml] Get-Content web.config). You can then pipe that to Get-Member ( $myFile | Get-Member -MemberType Property) to start working your way into the file to see what node has it. I'm not at a computer where I can show you some screenshots to explain it more, but you can check this chapter out from PowerShell.com "Master PowerShell" e-book that explains working with XML very well.

Resources