Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

powershell run executable

Running Programs with Elevated Privileges using Start-Process Command

Start-Process -FilePath "powershell.exe" -Verb RunAs
Start-Process -FilePath "C:\Temp\Log.txt" -Verb Print

In this tutorial, you will learn how to list files, folders, and subfolders using Windows CMD commands and PowerShell.

I’ll also demonstrate using the NTFS Permissions Tool, which is a graphical program that displays the permissions on folders and subfolders.

Open folders & files using Command Prompt & PowerShell

However, learning to work with the command line is a useful skill, as it gives you quick access to functions and operations. For instance, in some situations when working on Command Prompt or PowerShell, you need to open folders or files. You don’t have to exit the window just to find the folder or file.

Introduction to PowerShell’s Start-Process Command

The PowerShell Start-Process command is a powerful tool that is used to start a new program or script in a new process. This cmdlet lets us launch external programs directly from the command line or a PowerShell script. You can use it to start any program, including batch files, executables, and PowerShell scripts.

Running PowerShell Scripts with Start-Process Command

The PowerShell Start-Process command can also be used to start PowerShell scripts. To start a PowerShell script, you need to specify the location of the script using the FilePath parameter. Additionally, you can pass arguments to the script using the ArgumentList parameter.

Start-Process -FilePath "powershell.exe" -ArgumentList "-File C:\Scripts\MyScript.ps1"

This command would start the MyScript.ps1 script in a new PowerShell process.

Quick Links

Key Takeaways

  • To run an executable file without admin rights, launch PowerShell, type the ampersand (&) symbol, press Spacebar, enter your EXE file’s path in double quotes, and press Enter.
  • To launch an EXE file with admin rights, use the “Start-Process FilePath “powershell” -Verb RunAs” command where FilePath is the full path enclosed with double quotes to your executable file.

Running executables as a different user with Start-Process in PowerShell

Start-Process -FilePath "powershell.exe" -Credential (Get-Credential)
powershell start-process
# Parameters
$FilePath = "C:\Scripts\RunMe.bat"
$UserName = "Crescent\salaudeen"
$Password = "Password goes here"
 
#Prepare the Credentials
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePassword

#Start a process with 
Start-Process -FilePath $FilePath -Wait -Credential $Credential

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

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

Running Executables with Start-Process Command

Running executables with Start-Process in PowerShell is a straightforward process. By simply specifying the path of the executable as an argument to the Start-Process cmdlet, PowerShell launches the program and executes it. This method is particularly useful when you want to run standalone executables without any additional parameters or customization. Let’s take a look at an example:

To start an executable, you need to specify the location of the executable using the FilePath parameter.

Start-Process -FilePath "C:\MyProgram\MyProgram.exe"

This command would start the MyProgram.exe executable.

Running Batch Files with Start-Process Command

PowerShell is not limited to running standalone executables only; it can also execute scripts and batch files effortlessly. By utilizing the Start-Process cmdlet, we can launch scripts and batch files in PowerShell and automate complex tasks. This provides us with the flexibility to integrate PowerShell with other scripting languages and leverage their capabilities. Let’s take a look at an example of running a PowerShell script using Start-Process:

To start a batch file, you need to specify the location of the batch file using the FilePath parameter.

Start-Process -FilePath "C:\MyBatchFile.bat"

Running Programs with PowerShell’s Start-Process Command

Start-Process -FilePath "notepad.exe"

This command would start Notepad in a new process.

PowerShell Run Exe

If you want to run an executable in the background without displaying any windows or prompts, you can use the -WindowStyle Hidden parameter of the Start-Process cmdlet. Similarly, you can open any specified file (Non-executable file, such as a doc file) in a new window using:

Start-Process -FilePath "C:\Docs\AppLog.txt" -WindowStyle Maximized

This opens the file “C:\Docs\AppLog.txt” in a maximized window.

PowerShell to Open Files

To open a file in PowerShell, you can use the Start-process (or its alias: Start) command:

Start "C:\Temp\Archive.zip"

This method allows you to open files in the associated programs in PowerShell. In the above case, the zip file will be opened in WinRAR/WinZip/Windows Explorer, depending on your computer’s default program associations.

Open File Explorer from PowerShell
To open Windows File Explorer from PowerShell, Use: Start-Process Explorer

Common Errors and Troubleshooting Tips with Start-Process Command

While the PowerShell Start-Process command is a powerful tool, there are a few common errors that you may encounter.

  1. Access is denied: One common error is the “Access is denied” error. This error occurs when you try to run a program or script with elevated privileges, but you do not have permission to do so. To fix this error, you will need to log in as an administrator or use the RunAs parameter to run the program with elevated privileges.
  2. File not found: Another common error is the “File not found” error. This error occurs when you specify an incorrect file path. To fix this error, you will need to double-check the file path and make sure that it is correct. This includes verifying file permissions and network access if the executable resides on a remote machine. Always use the full path of the executable to avoid any ambiguity or reliance on the system’s PATH environment variable.
  3. Invalid Arguments: If the executable requires specific arguments, ensure that they are passed correctly using the ArgumentList parameter of the Start-Process cmdlet.

Using Arguments with Start-Process Command

As mentioned earlier, the PowerShell Start-Process command allows you to pass arguments to the program or script you are starting. This can be useful if you need to customize the behavior of the program or script.

For example, if you are starting a program that requires command-line arguments, you can pass those arguments using the ArgumentList parameter.

Start-Process -FilePath "myprogram.exe" -ArgumentList "-arg1 value1", "-arg2 value2"

This command would start the myprogram.exe program with the arguments “-arg1 value1” and “-arg2 value2”. The parameter values depend on the application you are running. Let’s take an example: Suppose you want to open a URL in Google Chrome. Here’s how you can do it:

Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "https://www.google.com" -Wait -WindowStyle Maximized
start-process argument

In this example, the -FilePath parameter specifies the path to the executable file for Chrome and the -ArgumentList parameter provides the URL to open in Chrome. The arguments are passed as a string, where a space separates each argument. It also uses a wait switch to wait for the process to close and Windowstyle parameters. This enables us to provide multiple args to the executable and customize its behavior.

Understanding the Start-Process Command

Run an Executable in PowerShell

The PowerShell Start-Process command has a number of different parameters that you can use to customize the way that the command runs. The most important parameter is the FilePath parameter, which specifies the location of the program or script that you want to start.

Another important parameter is the ArgumentList parameter, which allows you to pass arguments to the program or script you are starting. For example, if you are starting a PowerShell script, you can pass in parameters to the script using the ArgumentList parameter.

The Start-Process command also has parameters that let you specify the working directory, window style, and priority of the process you’re starting. These parameters can be useful if you need to start a program or script in a specific way. Along with other default parameters, Here is the list of important parameters of start-process cmdlet:

:/>  «Частота обновлений коллективных политики способы принудительного обновления таких политик на внешних компьютерах, работающих в домене Active Directory»
ParameterDescription
-FilePathSpecify the executable, application, file, batch, or script to run
-ArgumentListSpecifies parameters to use with the process to start
-CredentialUser account to run the process
-NoNewWindowOpen a window in the current console process
-PassthruReturns the process object of the process started. You can get the process ID from it.
-RedirectStandardErrorSpecify text file to redirect error output to
-RedirectStandardInputText file with input for the process
-RedirectStandardOutputSpecify text file to redirect output to
-UseNewEnvironmentThe process will use new environment variables specified for the process instead default, under: Machine and user
-WindowStyleSpecifies the state of the window: Normal, Hidden, Minimized, or Maximized
-LoadUserProfileLoads the Windows user profile from the HKEY_USERS registry key for the current user. This does not affect the PowerShell profiles.
-WaitWait for the process to complete before continuing with the script
-WorkingDirectoryThe location where the process should start in
CommonParametersVerbose, Debug,ErrorAction, ErrorVariable, WarningAction, WarningVariable,OutBuffer, PipelineVariable, and OutVariable

Manage user sessions and open files

It will take approximately 15 minutes to complete this section.

Manage user sessions and open files using the UI

Read through all steps below and watch the quick video before
continuing.

manage-sessions-files-ui.gif

  1. From the Amazon FSx console,
    click the link to the STG326 – SAZ file system and
    select the Network & security tab. Copy the DNS
    Name
    of the file system to the clipboard.

  2. Go to the remote desktop session for your Windows Instance 0.

  3. Paste the DNS Name copied above in the Another
    computer:
    text box and click Ok.

  4. From the left pane select Sessions.

  5. Review the open sessions to the file system.

  6. From the left pane select Open Files.

  7. Review the open files of the file system.

  8. Click Start >> Windows PowerShell.

    This section assumes that STG326 – SAZ is mapped as the
    Z:/ drive. If your Windows Instance 0 does not have a
    mapped Z:/ drive, map STG326 – SAZ as the Z:/ drive
    (see the previous section for step-by-step instructions).

  9. Run the DiskSpeed script below to test read performance of the
    mapped Z: drive.

$random = $(Get-Random)
fsutil file createnew Z:\${env:computername}-$random.dat 100000000000
C:\Tools\DiskSpd-2.0.21a\amd64\DiskSpd.exe -d120 -w0 -r -t1 -o32 -b64K -Su -L Z:\${env:computername}-$random.dat
  1. Do you see an open file?

    Check your email. You should eventually get a High Throughput
    Alarm email.

  2. What happened to the open file?

  3. What happened to the DiskSpd command in the PowerShell window?

  4. Close the PowerShell window. Run exit.

Manage user sessions and open files using the Amazon FSx CLI for Remote Management on PowerShell.

Read through all steps below and watch the quick video before
continuing.

manage-sessions-files-cli.gif

  1. Copy the script below into your favorite text
    editor.

    $WindowsRemotePowerShellEndpoint   # e.g. "fs-0123456789abcdef.example.com"
    
  2. From the Amazon FSx console,
    click the link to the STG326 – SAZ file system and
    select the Network & security tab. Copy the
    Windows Remote PowerShell Endpoint of the file system to the
    clipboard (e.g. fs-0123456789abcdef.example.com).

  3. Return to your favorite text editor and replace
    “windows_remote_powershell_endpoint” with the Windows
    Remote PowerShell Endpoint
    of STG326 – SAZ. Copy the
    updated script.

  4. Go to the remote desktop session for your Windows Instance 0.

  5. Click Start >> Windows PowerShell.

  6. Run the updated script in the Windows PowerShell window.

    • Run the command in the Remote Windows PowerShell
      Session
      window.

  7. What commands are available to manage open files?

    • Run the command in the Remote Windows PowerShell
      Session
      window.

  8. Open a new Windows PowerShell window.

    • Click Start >> Windows PowerShell.
  9. Run the DiskSpeed script below to test read performance of the
    mapped Z: drive in the new Windows PowerShell window.

$random = $(Get-Random)
fsutil file createnew Z:\${env:computername}-$random.dat 100000000000
C:\Tools\DiskSpd-2.0.21a\amd64\DiskSpd.exe -d120 -w0 -r -t1 -o32 -b64K -Su -L Z:\${env:computername}-$random.dat
  1. While the script is running, go back to the Remote Windows
    PowerShell Session
    window.

  2. Run the command in the Remote Windows PowerShell Session window.

  1. Do you see an open file?

  2. Close the open file.

  3. Run the command in the Remote Windows PowerShell Session window.
    Enter A for Yes to All at the prompt.

  1. What happened to the open file?

  2. What happened to the DiskSpd command in the other PowerShell window?

  3. End the remote PowerShell session. Run Exit-PSSession.

  4. Close the PowerShell window. Run exit.

Table of contents

  • Introduction to PowerShell’s Start-Process Command
  • Understanding the Start-Process Command
  • Running Programs with PowerShell’s Start-Process Command
  • Running Programs with Elevated Privileges using Start-Process Command
  • Running executables as a different user with Start-Process in PowerShell
  • Running PowerShell Scripts with Start-Process Command
  • Using Arguments with Start-Process Command
  • Running Executables with Start-Process Command
  • Running Batch Files with Start-Process Command
  • Common Errors and Troubleshooting Tips with Start-Process Command
  • Conclusion and Best Practices

Кто открыл файл в общей сетевой папке на сервере Windows?

Чтобы удаленно определить пользователя, который открыл (заблокировал) файл cons.adm в сетевой папке на сервере mskfs01, выполните команду:

Ключ /i используется, чтобы выполнялся поиск без учета регистра в имени файла.

Можно указать только часть имени файла. Например, чтобы узнать, кто открыл xlsx файл, в имени которого есть строка farm, воспользуйтесь таким конвейером:

С помощью PowerShell также можно получить информацию о пользователе, который открыл файл. Например:

Вывести все открытые по сети exe файлы:

Найти открытые файлы по части имени:

Вывести все файлы, открытые определенным пользователем:

Найти файлы, которые открыли с указанного компьютера:

In this article

Check it out.

Which Command Will You Use?

In this article, I showed you three different commands to get files, folders, and subfolders.

Which command did you find most useful? Let me know in the comments below.

Related Articles

Powershell List Folders and Subfolders

You can use the Get-Childitem PowerShell cmdlet to list files and folders. The Get-Childitem cmdlet is similar to dir but much more Powerful.

Let’s look at some examples

Example 1. List files and folders using Get-Childitem

This example gets the folder contents from a specific directory

Get-ChildItem -path c:\it\toolkit
powershell get list of folders

By default, the Get-ChildItem cmdlet lists the mode, LastWriteTime, Length, and Name of the filer or folder.

  • l = Link
  • d – directory
  • a = archive
  • r = read-only
  • h = hidden
  • s = system

Example 2. Get subfolders using Get-ChildItem

Use the -Recurse option to get subfolders and files.

Get-ChildItem -path c:\it\toolkit -Recurse
powershell list files and folders

Example 3. Get items using the Depth parameter

You can use the -Depth parameter to control how many subfolders deep to include in the list.

Get-ChildItem -Path C:\it -Depth 2

Example 4. PowerShell List only specific file types

In this example, I will list only files that end in a .msi file extension. This will search all subfolders in the directory path.

get-childitem -path c:\it -include *.msi -recurse
Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

Example 5. PowerShell List only folder or files name

The -Name parameter will only return the file or folder name.

Get-ChildItem -path c:\it\toolkit -Name
Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

Example 6. PowerShell List all Files and Folder Details

To display all details of a file or folder use the fl option.

Get-ChildItem -path c:\it\toolkit | FL

You can see below this command will display additional details, if there are any.

Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

Example 7. PowerShell count files and folders

To get a count of the files and folders use the measure-object option.

Get-ChildItem -path c:\it\toolkit | Measure-Object
powershell count folders

Example 8. Powershell Get Folder Size

You can also use the measure-object option to get the folder size.

Get-ChildItem -path c:\it\toolkit | Measure-Object -Property Length -sum
powershell get folder size

As you can see using PowerShell there are a lot of options when it comes to getting files and folders, you can create some really powerful reports.

:/>  Убрать хром из автозапуска виндовс 10

How to See Who Has Locked an Open File on Windows

The document filename is locked for editing by another user. To open a read-only copy of his document, click…

The /i switch is used to make the filename case insensitive when searching.

Search for open files by part of their name:

Find files opened from a specified remote computer:

Как удаленно закрыть открытые по сети файлы с помощью PowerShell?

Командлеты Get-SMBOpenFile и Close-SmbOpenFile можно использовать чтобы удаленно найти и закрыть открытые файлы. Сначала нужно подключиться к удаленному SMB серверу Windows через CIM сессию:

$sessn = New-CIMSession –Computername mskfs01

Также вы можете подключаться к удаленному серверам для запуска команд через командлеты PSRemoting: Enter-PSSession или Invoke-Command .

Следующая команда найдет сессию для открытого файла
*pubs.docx
и завершит ее.

Подтвердите закрытие файла, нажав
Y
. В результате вы разблокировали открытый файл. Теперь его могут открыть другие пользователи.

Get-SMBOpenFile - удаленное управление открытых файлов

С помощью PowerShell вы можете закрыть и осведомить на файловом сервере все файлы, открытые определенным пользователем (пользователь ушел домой и не освободил файлы). Например, чтобы сбросить все файловые сессии для пользователя ipivanov, выполните:

Принудительно закрыть открытый файл на сервере Windows

Можно закрыть открытый файл через консоль Computer Management. Найдите файл в списке секции Open Files, выберите в контекстном меню пункт “Close Open File”.

Закрыть открытые файлы в сетевой папке

Если на сервере по сети открыты сотни файлов, то найти нужный файл в графической консоли довольно сложно. Лучше использовать инструменты командной строки.

Закрыть файл можно, указав ID его SMB сессии. Получить ID сессии файла:

команда openfiles найти кем открыт файл

Теперь можно принудительно отключить пользователя по полученному идентификатору SMB сессии:

Openfiles /Disconnect /ID 3489847304

openfiles disconnect - закрыть открытый файл на сервере

SUCCESS: The connection to the open file "D:\path\REPORT2023.XLSX" has been terminated.

Вы разблокировали открытый файл и теперь его могут открыть другие пользователи.

Можно принудительно сбросить все сессии и освободить все файлы, открытые определённым пользователем:
openfiles /disconnect /s mskfs01 /u corp\aivanova /id *

Можно закрыть открытый файл по ID сессии с помощью PowerShell командлета Close-SmbOpenFile.

Close-SmbOpenFile - SessionId 3489847304

Найти и закрыть открытый файл одной командой:

powershell закрыть открытый файл на сервере

Для подтверждения сброса сессии и освобождения отрытого файла нажмите
Y
->
Enter
.

Чтобы закрыть файл без предупреждения, добавьте параметр
-Force
в последнюю команду.

С помощью Out-GridView можно сделать простую графическую форму для поиска и закрытия файлов. Следующий скрипт выведет список открытых файлов. Администратору нужно с помощью фильтров в таблице Out-GridView найти и выделить нужные файлы, а затем нажать ОК. В результате выбранные файлы будут принудительно закрыты.

Get-SmbOpenFile вместе с out-gridview - powershell скрипт с графическим интерефейсом по выбору и принудительному закрыттию заблокированных (открытых) файлов в windows

Принудительное закрытие открытого файла на файловом сервере, вызывает потерю несохраненных пользователем данных. Поэтому команды openfiles /disconnect и
Close-SMBOpenFile
нужно использовать с осторожностью.

Open folders & files using Command Prompt & PowerShell

In this guide, I’ll show you how to open folders right from Command Prompt and PowerShell on your Windows 11/10 PC.

What you will learn:

  1. How to navigate to a folder using Command Prompt and PowerShell.
  2. How to open a folder using Command Prompt and PowerShell.
  3. How to close a file using Command Prompt and PowerShell.

1] How to navigate to a folder using Command Prompt and PowerShell

Open the Command prompt by searching for cmd in the Start Menu and selecting Command Prompt. For PowerShell, you can also search for it and open from the Start Menu.

cd Path\To\Folder

NOTE: In the above command, replace Path\To\Folder with the actual path to the folder that you want to open. So, it can become:

cd C:\Users\<username>\Desktop\New Folder

To open a file saved in this folder, input the name of the file and press ENTER. Example,

Path\To\Folder new-file.txt

Alternatively, you can enter the full path to the file without using the cd command. For example,

C:\Users\<username>\Desktop\New Folder\new_file.txt

2] How to open a folder using Command Prompt and PowerShell

The first technique would open a file saved in a folder. However, if you wish to open the folder in File Explorer using Command Prompt or PowerShell, you make use of the start command.

Command Prompt

start C:\Users\<username>\Desktop\New Folder

If you want to open the current folder, run the start command with a fullstop (.):

start .

To open the parent folder to your current folder, use two fullstops (..):

start ..

On hitting ENTER, the specified folder will open in a File Explorer window.

ReadHow to open Folder with Keyboard Shortcut in Windows

PowerShell

Invoke-Item
ii

and add the path to the folder.

ii C:\Users\<username>\Desktop\New Folder
ii

TIP: This post will show you how to create, delete, find, rename, compress, hide, move, copy and manage a file or folder using Command Prompt

3] How to close a file using Command Prompt and PowerShell

To close an already opened file using the command line, you make use of the taskkill command. First, navigate to the folder using the first method:

C:\Path\To\Folder
taskkill /im filename.exe /t

In the above command, replace the filename part with the name of the file you want to close.

Note that this command closes every instant of the open file, and you risk losing unsaved data.

Now read: Ways to open a Command Prompt in a Folder.

I hope you find the post useful.

List Files and folders using the DIR Command

The dir command is built into all versions of Windows. It is an easy to use command to list files, folders, and subfolders from the Windows command prompt.

Let’s look at some examples.

Example 1. List files and folders in the current directory

To list the files and folders in the current directory, open the Windows command prompt, enter dir and press enter. The dir command by default does not display subfolders.

dir

In this example, my current location is c:\it, so when I run the dir command it will list everything in this folder.

cmd list folders

I have put the command output into colored boxes to explain what each column means.

  • Red = This column is the last modified date of the file or folder
  • Green = Indicates if the item is a folder, folders are labeled with DIR
  • Purple = The size of the file
  • Yellow = Name of the file or folder.

Example 2. List subfolders

Use the /s option to include subfolders.

dir /s

I ran the command from the c:\it location and it lists all subfolders and files from this directory. I’ve highlighted some of the subfolders in the screenshot below.

cmd list folder and subfolders

Example 3. Specify a directory path

To list files and folders from a specific directory enter the complete directory path.

dir /s c:\it

For example, if my current location is the root of c: and I type dir /s c:\it the command will display the items from the c:\it directory.

Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

Example 4. Export list of files and folders

To export the screen output use the command below. You can name the file whatever you want, in this example, I named the file files2.txt

dir > files2.txt

The file will be saved to the current directory.

Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

Pretty easy right?

I covered some of the most basic dir command options. To see a full list of options type dir /? and press enter.

Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

Get Folder and Subfolder NTFS Permissions

If you need a report of folders and subfolders that includes who has permission to what, then check out the NTFS Permissions Reporting Tool below.

Example 1. List NTFS Permissions on Shared Folder

Как открыть файл или папку с помощью командной подсказки или power shell в windows 11
  • DirectoryName = Path of the folder
  • Account = Account listed on the folder (this can be a user or group)
  • DirectoryOwner = Owner listed on the folder
  • DirectoryRights = Permissions the user or group has to the folder
  • Type = Allow or Deny
  • AppliesTo = What the permissions applies to
  • IsInherited = Are the permissions inherited from a parent folder
:/>  Как включить и отключить экранный диктор в Windows 10 | World-X

Example 2. List Folder Permissions on Local Folder

If you want to check the permissions on a local folder click the browse button or enter the folder path.

Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

Why Open EXE Files With PowerShell?

While the easiest way to launch files on Windows is to simply double-click your files, the usage of PowerShell to open files is handy in some cases.

For example, if your File Explorer utility isn’t working and restarting Windows Explorer hasn’t fixed the issue, you can use the PowerShell method to launch any executable file.

Another reason you may want to use a PowerShell command to launch files is if you’re writing a script. You may want to open a file in your script, which you can do by including the above PowerShell commands.

How to Launch an EXE File Without Admin Rights Using PowerShell

To start, open your PC’s Start Menu, find “PowerShell”, and launch the utility.

Windows 11's Start Menu with Windows PowerShell highlighted.

In PowerShell, type the ampersand (&) symbol, press Spacebar, enter your executable file’s path, and press Enter. If your file path has spaces, enclose the path with double quotes.

If you’re unsure how to locate your program’s file path, simply drag and drop your file onto your PowerShell window to automatically fill the file path. Another way to find a file’s path is to right-click the file, select “Properties,” open the “Details” tab, and look at the “Folder Path” value.

& "C:\Users\mahes\Desktop\My Files\FileZilla_3.62.2_win64-setup.exe"
A PowerShell window with a command that launches an EXE file on Windows 11.

PowerShell will launch your specified executable file, and you’re all set.

How to Launch an EXE File With Admin Rights Using PowerShell

Start-Process FilePath "powershell" -Verb RunAs

Although you only need to enclose the path with double quotes if the path has spaces, it’s a good practice to always use double quotes; it doesn’t cause any issues.

Start-Process "C:\Users\mahes\Desktop\My Files\FileZilla_3.62.2_win64-setup.exe" "powershell" -Verb RunAs
A PowerShell window with a command that opens an EXE file with admin rights on Windows 11.

View Open Files on Windows Server

You can use the graphical Computer Management snap-in to get a list of files open over the network in Windows

  1. Run the compmgmt.msc console and go to System Tools -> Shared Folders -> Open files;
  2. A list of open files is displayed on the right side of the window. Each entry shows the local path to the file, the user account name, the number of locks, and the mode in which the file is opened (Read or Write+Read).List of Open Files on Windows Server 2012 R2 shared folders

You can also list the files open on the server from the command line:

openfiles /Query /fo csv

Openfiles cli tool to manage open files

A more convenient way to work with the list of files that are open on the server is to use the Get-SmbOpenFile PowerShell cmdlet:

Display Folder Structure using TREE Command

The tree command is another built-in Windows command. This command will display the contents of a directory in a tree structure. This can be useful to give you an overview of the folder layout.

You must specify a path or this command will start at the root of c

Example 1. List all folders and subfolders using TREE

To list all folders and subfolders enter the tree command and the path.

tree c:\it\toolkit
Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

Example 2. List all folders and files using TREE

To include files with the tree command use the /f option.

tree c:\it\toolkit /f
Как открыть файл или папку с помощью командной подсказки или power shell в windows 11

In my experience, I never use the tree command. I find it more useful when a command provides more details like modified dates, permissions, ownership, and so on. If you just need to see the files and folders with no other details then this is a great option.

Conclusion and Best Practices

When using the Start-Process command, it is important to double-check your file paths and arguments to avoid common errors. Additionally, it is a good practice to test your commands in a test environment before running them in a production environment.

Now that you have a better understanding of the PowerShell Start-Process command, you can start using it to automate your tasks and streamline your workflow!

How do I run a PowerShell script like an EXE?

How do I run an EXE file in PowerShell?

To run an EXE file in PowerShell, you can use the “Start-Process” cmdlet. Here’s an example of the command you can use: “Start-Process -FilePath 'C:\Path\to\file.exe'“. Replace ‘C:\Path\to\file.exe‘ with the actual path to your EXE file.

How do I install an EXE file in PowerShell silently?

To install an EXE file silently using PowerShell, you can use the Start-Process cmdlet with the -ArgumentList parameter. Here’s an example of the command you can use: Start-Process -FilePath "path\to\file.exe" -ArgumentList "/silent"

How do I open an application in PowerShell?

How to run an exe file from the command line?

To run an EXE file from the command line, you need to navigate to the directory where the file is located using the “cd” command. Once you are in the current directory, you can simply type the name of an executable file and press enter to run it.

How do I run PS from the command prompt?

How can I wait for a process to finish before proceeding?

To make PowerShell wait for a process to finish before continuing, you can use the -Wait parameter with Start-Process. This parameter ensures that PowerShell waits for the process and all its descendants to exit before returning control.

Can I pass arguments to the executable with Start-Process?

Yes, you can pass arguments to the executable using the -ArgumentList parameter. Start-Process -FilePath "notepad.exe" -ArgumentList "C:\Temp\Logs.txt"

Can I capture the output of a process started with Start-Process?

Yes, you can capture the output of a process by using the -RedirectStandardOutput parameter and specifying a file path to store the output. For example:
Start-Process -FilePath "ping.exe" -ArgumentList "google.com" -RedirectStandardOutput "output.txt"
This command will start the ping command, ping google.com, and redirect the output to the “output.txt” file.

Can I start a process in a minimized or maximized window?

Yes, you can control the window state of the process using the -WindowStyle parameter. The available options are “Normal”, “Hidden”, “Minimized”, and “Maximized”. For example: Start-Process -FilePath "notepad.exe" -WindowStyle Minimized

Close Open Files on Windows Server

You can use the Computer Management console to close an open file. Locate the file in the list in the Open Files section and select ‘Close Open File’ from the menu.

close open file using computer managment console GUI

Finding the file you want in the graphical console can be difficult when there are hundreds of files open on the server. It’s better to use command line tools in this case.

You can close a file by specifying its SMB session ID. Get file session ID:

openfiles /disconnect /ID 3489847304

SUCCESS: The connection to the open file "D:\docs\public\REPORT2023.XLSX" has been terminated.

openfiles /disconnect /s lon-fs01/u corp\mjenny /id *

You can use the PowerShell cmdlet Close-SmbOpenFile to close an open file handler by session ID.

Close-SmbOpenFile -FileId 4123426323239

Find and close an open file with a one-line command:

To confirm the reset of the session and release the open file, press Y -> Enter.

Add the -Force parameter to the last command to close the file without warning.

powershell gui script to close open files using out-gridview

Вывод списка открытых файлов в сетевой папке Windows

Список открытых по сети файлов в Windows можно получить с помощью графической консоли Computer Management (Управление компьютером).

  1. Откройте консоль
    compmgmt.msc
    и перейдите в раздел System Tools -> Shared Folders -> Open files (Служебные программы -> Общие папки -> Открыты файлы);
  2. В правой части окна отображается список открытых файлов. Здесь указаны локальный путь к файлу, имя учетной записи пользователя, количество блокировок и режим, в котором открыт файл (Read или Write+Read).Открыты файлы на файловом сервере Windows

Также вы можете вывести список открытых на сервере файлов из командной строки:

Openfiles /Query /fo csv

Команда возвращает номер сессии, имя пользователя, количество блокировок и полный путь к файлу.

Openfiles /Query

Cо списком открытых файлов на сервере удобнее работать с помощью PowerShell командлета Get-SmbOpenFile:

В выводе команда содержится имя пользователя, имя (IP адрес) удаленного компьютера, с которого открыт файл), имя файла и ID файловой сессии.

poweshell вывод список пользователей, которые открыли файлы в сетевой папке windows

How to Remotely Close Open Files with PowerShell

The Get-SMBOpenFile and Close-SmbOpenFilecmdlets can be used to remotely find and close open (locked) files. The first step is to establish a CIM session with a remote Windows file server:

$sessn = New-CIMSession –Computername lon-fs01

You can also use the PSRemoting cmdlets (Enter-PSSession or Invoke-Command) to connect to a remote server and run commands.

PowerShell Get-SMBOpenFile - Close-SMBOpenFile

Оставьте комментарий