admin / 01.03.2018

Powershell поиск файлов

Содержание

Поиск открытых файлов при помощи PowerShell

Опубликовал admin

Июль 18, 2011

Часто администратору необходимо получить список открытых пользователями файлов. Имея привилегии локального или доменного админа, эту проблему решить просто. Открываем консоль PowerShell и вводим команду:

PS> openfiles   INFO: The system global flag ‘maintain objects list’ needs to be enabled to see local opened files. See Openfiles /?for more information.   Files opened remotely via local share points: ———————————————   INFO: No shared open files found.

PS> openfiles INFO: The system global flag ‘maintain objects list’ needs to be enabled to see local opened files. See Openfiles /? for more information. Files opened remotely via local share points: ——————————————— INFO: No shared open files found.


Чтобы принудительно закрыть файл используем параметр /Disconnect вместе с ID соединения:

Openfiles /id 1234/Disconnect

Openfiles /id 1234 /Disconnect

Понравилась статья? Оставьте комментарий или подпишитесь на RSS рассылку.

NET FILE — просмотр открытых сетевых файлов

NET FILE вывод списка открытых общих файлов

Команда NET FILE выводит имена открытых общих файлов на компьютере и количества блокировок для каждого файла, если они установлены.

Powershell — работа с файлами и папками

Также команда позволяет закрыть общий файл и удалить блокировки. Команда net file без параметров выводит список открытых файлов на сервере с операционной системе Windows.

Также для управления сетевыми параметрами ПК можно использовать команды:

  • NET SHARE — для управления общими ресурсами;
  • NET VIEW — для просмотра списка общих ресурсов;
  • NET USE — для подключения к общим сетевым ресурсам;
  • NET TIME — для синхронизации часов компьютера.

А для завершения текущих сеансов связи между компьютерами служит команда NET SESSION.

Синтаксис команды NET FILE

net file [номер [/close]], где

  • номер — идентификационный номер файла.
  • /close — закрытие открытого файла и снятие блокировки. Данная команда запускается на сервере, где находятся общие файлы.

Примеры команды NET FILE

  • Отображение справки для указанной команды net help file;
  • Чтобы просмотреть сведения о совместно используемых файлах введите net file;
  • Чтобы закрыть файл под номером 1, введите: net file 1 /close.

Видео — Работа с утилитой cmd NET FILE

PowerShell Get-Date and DateTime

Windows PowerShell Get-Date Format

Manipulating dates is always tricky.  However, PowerShell’s Get-Date cmdlet does a wonderful job of interpreting the different international formats for day / month / year.  As a result, whatever your computer’s country locale, it will be easy to calculate how many days there are to Christmas.

Topics for Windows PowerShell Get-Date and DateTime

 ♣

Introduction to the Get-Date Cmdlet

On this page I am making a change to my usual running order.  I want to start by tackling the challenge presented by a real-life task.  After showing examples of Get-Date in action I will encourage you to research more methods and properties for this PowerShell cmdlet.  The result will be that you have the skills to undertake other DateTime projects.

How Many Days to Christmas? (or Thanksgiving)

Our challenge is simple enough, to knock-up a simple script that will tell us how many days there are until Christmas, Thanksgiving, or any other date you care to place in a text string.

Here in the UK, our operating systems show dates in the format: dd mmmm yyyy.  Whereas in the United States your locale is displayed as mmmm dd yyyy.  Consequently, I was amazed that PowerShell could convert both "25 December 2014" and "November 28 2014" into date values that it could understand and perform calculations.

Example 1 — Calculate Days Until Christmas Using Lots of Variables

In example one I have used several variables that are not strictly necessary, I just wanted to show my thought process in creating this very simple PowerShell script.

# PowerShell DateTime Script to display days until Christmas
Clear-Host
$DecDate = "25 December 2014"
$NovDate ="November 28 2014"
$Thanksgiving = [system.datetime]$NovDate
$Christmas = [system.datetime]$DecDate
$Today = Get-Date
$Xmas = ($Christmas.DayOfYear — $Today.DayOfYear)
$Thanks = ($Thanksgiving.DayOfYear — $Today.DayOfYear)
"There are " + $Xmas + " days until " + $DecDate
"There are " + $Thanks + " days until " + $NovDate

Note 1: You may wish to examine the values for $DecDate and $NovDate, then change the sequence of day month to suit your locale.

Note 2: It’s interesting to see how PowerShell leverages .Net Framework, for example, it employs System.DateTime to convert a text string to a date format.

Note 3: I keep marvelling how PowerShell can understand both formats: dd mmmm yyyy, and mmmm dd yyyy.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM) v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Example 2 — Production Version of ‘How Many Days to Christmas’

# PowerShell DateTime Example
"There are " + (([system.datetime]"25 December 2014").DayOfYear — `
(Get-Date).DayOfYear) + " days until " + "24 December 2014"

Note 4: This is just one long command.  Observe how the backtick (`) enables the command to overspill onto the second line.  Alternatively, break the line at the open bracket symbol thus:

— (
Get-Date).DayOfYear) + " days until " + "24 December 2014"

Note 5: This command needed an extra set of round brackets to surround [system.datetime]"25 December 2014"

Note 6: It’s interesting to see how PowerShell interprets a mixture of "text strings" and date calculations.  As with types of bracket, you need the correct type of "double" speech marks here.

Further Research on PowerShell’s Get-Date

I’m hoping that the simple example above will give you ideas for date scripts, which will be useful in your PowerShell projects.  If so, then it’s well worth examining Get-Date’s properties, and in particular its methods.

a) Get-Date Methods and Properties

# Research PowerShell Get-Date Properties
Get-Date | Get-Member

Note 7: Normally it’s a cmdlet’s properties that I am most interested in, but with Get-Date it’s the methods that intrigue me, for example .AddDays() and .IsDaylightSavingTime().

b) AddDays Method

The purpose of this script is to list all the System Error messages from the last 8 days.

Incidentally, it’s amazing how often we use this method with a negative number to go back in time.

# PowerShell Get-Date example
Clear-Host
$Log8d = @{
Logname = ‘System’
EntryType = ‘Error’
After = (Get-Date).AddDays(-8)
}

Get-EventLog @Log8d

Note 8: See more on this @{..

Как найти большие файлы на диске с помощью PowerShell

technique of PowerShell ‘Splatting’

c) Another Job for .AddDays
Scenario: You want to list eventlog messages younger than 30 days.

# Date calculation with .AddDays()
Clear-Host
$DateCut = (Get-Date).AddDays(-20)
Get-EventLog System -EntryType Error |
Where-Object {$_.TimeWritten -ge $DateCut}

Guy Recommends: SolarWinds Engineer’s Toolset v10

This Engineer’s Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer’s Toolset now!

Download your fully functional trial copy of the Engineer’s Toolset v10

Get-Date Parameters

# Research PowerShell’s Get-Date Parameters
Clear-Host
Get-Help Get-Date -full

Thanks toPowerShell’s help, I learned about the format -Uformat.

Formatting Get-Date Challenge: 
UK readers may appreciate employing this -Uformat parameter to rearrange days and months:

# PowerShell Get-Date Format Example
Clear-Host
$Now = Get-Date -Uformat "%A, %d:%m:%Y"
Write-Host "Today in the UK is $Now enjoy your day!"

Bonus Technique — DateTime and ParseExact

Once again, here is PowerShell working with the .Net Framework class DateTime.  ParseExact is a neat method which can convert a text string into its DateTime equivalent.

# ParseExact Change date and time with custom specifier.
Clear-Host
$DateString = "Sun 26 Jan 2014 12:30 AM -06:00"
$Format = "ddd dd MMM yyyy h:mm tt zzz"
$Translate = [DateTime]::ParseExact($DateString, $Format, $Provider)
Write-Host "$DateString converts to $($Translate.ToString())."

Get-Date CSV Format

Here is an example which employs another PowerShell cmdlet called ConvertTo-Csv to control the date format.

Clear-Host
$DateCsv = Get-Date
ConvertTo-Csv -Inputobject $DateCsv -NoTypeinformation

Note 9: You could change the separator from a comma to a semi-colon by appending this parameter: -Delimiter ";"

See more on ConvertTo-Csv »

Summary of PowerShell Get-Time and DateTime

Scripting dates is always tricky.  In these examples we can see how PowerShell leverages .Net Framework to convert strings into PowerShell’s DateTime values, which in turn, can be use for calculations.

If you like this page then please share it with your friends

 


See more PowerShell examples for syntax advice

• PowerShell Tutorials   • Syntax   • Get-Verb   • PowerShell Nouns   • Get-Credential

• PowerShell -as   • Comparison operators  • Conditional operators   • Real-time Bandwidth Monitor

• Get-Date  • Quotes   • Windows PowerShell   • PowerShell Version Check   • Get-Member

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

 

 *


Просмотр содержимого дисков Windows PowerShell и управление хранящимися на них элементами аналогично управлению файлами и папками на физических дисковых накопителях Windows. В этом разделе мы обсудим выполнение отдельных задач управления файлами и папками.

Получение списка файлов и папок, содержащихся в папке

Извлечь все элементы непосредственно из папки можно при помощи командлета Get-ChildItem. Для отображения скрытых и системных элементов добавьте необязательный параметр Force. Например, эта команда отображает непосредственное содержимое диска C Windows PowerShell (которое совпадает с содержимым физического диска C Windows):

Эта команда выводит только элементы, содержащиеся на диске непосредственно, так же как и команда DIR оболочки Cmd.exe или команда ls оболочки UNIX. Для показа вложенных элементов необходимо также указать параметр -Recurse. (Время выполнения этой операции будет очень велико.) Для вывода всего содержимого диска C введите:

Get-ChildItem -Force C:\ -Recurse

Командлет Get-ChildItem позволяет отфильтровать элементы при помощи параметров Path, Filter, Include и Exclude, но обычно осуществляется лишь фильтрация по имени. Сложную фильтрацию на основе других свойств элементов можно выполнить при помощи командлета Where-Object.

Следующая команда находит все исполняемые файлы в папке Program Files, которые были в последний раз изменены после 1 октября 2005 г., и размер которых не менее 1 мегабайта и не более 10 мегабайт:

Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object -FilterScript {($_.LastWriteTime -gt «2005-10-01») -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}

Копирование файлов и папок

Копирование выполняется при помощи командлета Copy-Item.

Следующая команда создает резервную копию C:\boot.bak для файла C:\boot.ini:

Copy-Item -Path c:\boot.ini -Destination c:\boot.bak

Если целевой файл уже существует, то попытка копирования завершается неудачей.

Find text in a file with PowerShell

Для того чтобы перезаписать существующий целевой файл, используйте параметр Force:

Copy-Item -Path c:\boot.ini -Destination c:\boot.bak -Force

Эта команда работает даже если целевой файл помечен как файл только для чтения.

Так же выполняется и копирование папок. Эта команда рекурсивно копирует папку «C:\temp\test1» в новую папку «c:\temp\DeleteMe»:

Copy-Item C:\temp\test1 -Recurse c:\temp\DeleteMe

Можно также скопировать избранные элементы. Следующая команда копирует все файлы .txt, содержащиеся в папке «c:\data», в папку «c:\temp\text»:

Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination c:\temp\text

Для копирования элементов файловой системы можно использовать и другие средства. В Windows PowerShell по-прежнему работают команды XCOPY и ROBOCOPY и такие COM-объекты, как Scripting.FileSystemObject,. Например, можно воспользоваться COM-классом Scripting.FileSystem COM сервера сценариев Windows для создания резервной копии файла C:\boot.ini в файле C:\boot.bak:

(New-Object -ComObject Scripting.FileSystemObject).CopyFile(«c:\boot.ini», «c:\boot.bak»)

Создание файлов и папок

Создание новых элементов осуществляется одинаковым образом всеми поставщиками Windows PowerShell. Если поставщик Windows PowerShell поддерживает более одного типа элементов (например, поставщик Windows PowerShell FileSystem различает каталоги и файлы), необходимо указать тип элемента.

Эта команда создает новую папку «C:\temp\New Folder»:

New-Item -Path ‘C:\temp\New Folder’ -ItemType «directory»

Эта команда создает новый пустой файл «C:\temp\New Folder\file.txt»:

New-Item -Path ‘C:\temp\New Folder\file.txt’ -ItemType «file»

Удаление всех файлов и папок, содержащихся в папке

Удалить вложенные элементы можно при помощи командлета Remove-Item, однако он потребует подтверждения удаления, если элемент сам что-нибудь содержит. Например, при попытке удаления папки «C:\temp\DeleteMe», которая содержит другие элементы, Windows PowerShell предварительно предложит подтвердить удаление этой папки:

Remove-Item C:\temp\DeleteMe Confirm The item at C:\temp\DeleteMe has children and the -recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to continue? [Y] Yes [A] Yes to All 503 No [L] No to All [S] Suspend [?] Help (default is «Y»):

Если подтверждение для каждого вложенного элемента нежелательно, задайте параметр Recurse:

Remove-Item C:\temp\DeleteMe -Recurse

Отображение локальной папки в виде диска, доступного в Windows

Отобразить локальную папку можно при помощи команды subst. Следующая команда создает локальный диск P:, корневым каталогом которого является локальный каталог Program Files:

subst p: $env:programfiles

Как и в случае сетевых дисков, диски, отображенные в оболочке Windows PowerShell при помощи команды subst, немедленно становятся доступными оболочке Windows PowerShell.

Чтение текстового файла в массив

Одним из наиболее общих форматов хранения текстовых данных является файл, отдельные строки которого рассматриваются как отдельные элементы.

Командлет Get-Content используется для чтения всего файла за один шаг, как показано далее:

PS> Get-Content -Path C:\boot.ini [boot loader] timeout=5 default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS [operating systems] multi(0)disk(0)rdisk(0)partition(1)\WINDOWS=»Microsoft Windows XP Professional» /noexecute=AlwaysOff /fastdetect multi(0)disk(0)rdisk(0)partition(1)\WINDOWS=» Microsoft Windows XP Professional with Data Execution Prevention» /noexecute=optin /fastdetect

Командлет Get-Content сразу рассматривает данные, прочитанные из файла, как массив с одним элементом на строку содержимого файла. Убедиться в этом можно, проверив свойство Length полученного содержимого:

PS> (Get-Content -Path C:\boot.ini).Length 6

Эта команда наиболее полезна для непосредственного ввода в Windows PowerShell информационных списков. Например, можно хранить в файле «C:\temp\domainMembers.txt» список имен компьютеров или IP-адресов по одному имени на каждую строку файла. Можно использовать командлет Get-Content, чтобы извлечь содержимое файла и поместить его в переменную $Computers:

$Computers = Get-Content -Path C:\temp\DomainMembers.txt

Теперь переменная $Computers представляет собой массив, содержащий в каждом элементе имя компьютера.

Скрипты Powershell для работы с AD аккаунтамиСкрипт Powershell: отключение Out-of-Office сообщения в почтовом ящике

Скрипт Powershell: получение списка ACL прав всех папок и подпапок

Рубрики: Сисадмину

Этот скрипт для примера получает права папок и подпапок C:\Scripts и выводит результаты в CSV файл.

$OutFile = «C:\temp\Permissions.csv» $Header = «Folder Path,IdentityReference,AccessControlType,IsInherited,InheritanceFlags,PropagationFlags» Del $OutFile Add-Content -Value $Header -Path $OutFile $RootPath = «C:\Scripts» $Folders = dir $RootPath -recurse | where {$_.psiscontainer -eq $true} 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 $OutFile } }

Популярность: 1%

FILED UNDER : IT

Submit a Comment

Must be required * marked fields.

:*
:*