- Find computer name from command line
- Get DNS or FQDN(fully qualified domain name) of the computer
- Find computer name using wmic
- ComputerName
- Values
- Valid configuration passes
- Parent hierarchy
- Applies To
- XML example
- Работа с файлами и папками Working with Files and Folders
- Получение списка файлов и папок, содержащихся в папке Listing All the Files and Folders Within a Folder
- Копирование файлов и папок Copying Files and Folders
- Создание файлов и папок Creating Files and Folders
- Удаление всех файлов и папок, содержащихся в папке Removing All Files and Folders Within a Folder
- Подключение локальной папки как диска Mapping a Local Folder as a drive
- Чтение текстового файла в массив Reading a Text File into an Array
- Computer Host Name via a file
Find computer name from command line
You can find out your computer name from command line using hostname command.
Note that hostname prints only the NetBios name of the computer, not the full DNS name. It works on all Windows versions- XP, Vista, Windows 7, Server 2003 and Server 2008.
System name is also stored in the environment variable computername. We can print the computer name using this environment variable as follows.
Note that, %computername% is more convenient to use in batch files. We can straight away use %computername% wherever we want to refer the local host name.
Get DNS or FQDN(fully qualified domain name) of the computer
Find computer name using wmic
net config works on win7 to get fqdn name. but it’s printing as below
how to print only fqdn and no additional text in the line? if I could do this, I can read the value to a variable in batch script.
YOU NEED TO USE FOR /F %%
In network i want to know PC name with the help of user id to know on which machine he login into ?
Cmd pls
Hi, How do I get the Computer name using Curl,
I have the following curl and I want to access the hostname(pass it instead of ABCD).
curl -X PUT “http://localhost:14121/api/SetValue?hostName=ABCD&status=false” -H “accept: application/json” -d “Content-Length: 0”
hi. i have 2 pc. my compiuter name is m110pc-01 and m140pc-01.
how can i delete prefix >M rookie_b
ComputerName
ComputerName specifies the computer name used to access the computer from the network.
NoteВ В In WindowsВ 10, users can no longer enter a computer name during OOBE as the name is auto-generated. To set a default computer name pre-OOBE, OEMs can configure ComputerName in the Unattend.xml file and specify a name for the computer. After OOBE, end users can change this default computer name after OOBE by changing it in the System Properties page.
Values
If ComputerName is not specified, a random computer name is generated.
If ComputerName set to an asterisk (*) or is included but empty («»), Windows creates a random 15-character name using up to 7 characters from FullName and Organization, then a dash, then more random characters.
ComputerName is a string with a maximum length of 15 bytes of content:
ComputerName can use ASCII characters (1 byte each) and/or multi-byte characters such as Kanji, so long as you do not exceed 15 bytes of content.
ComputerName cannot use spaces or any of the following characters:
ComputerName cannot use some non-standard characters, such as emoji.
Computer names that cannot be validated through the DnsValidateName function cannot be used, for example, computer names that only contain numbers (0-9). For more information, see the DnsValidateName function.
Valid configuration passes
Parent hierarchy
Applies To
For a list of the Windows editions and architectures that this component supports, see Microsoft-Windows-Shell-Setup.
XML example
The following XML output shows how to set the computer name.
Работа с файлами и папками Working with Files and Folders
Просмотр содержимого дисков Windows PowerShell и управление хранящимися на них элементами аналогично управлению файлами и папками на физических дисках Windows. Navigating through Windows PowerShell drives and manipulating the items on them is similar to manipulating files and folders on Windows physical disk drives. В этой статье описывается выполнение конкретных задач по управлению файлами и папками с помощью PowerShell. This article discusses how to deal with specific file and folder manipulation tasks using PowerShell.
Получение списка файлов и папок, содержащихся в папке Listing All the Files and Folders Within a Folder
Извлечь все элементы непосредственно из папки можно с помощью командлета Get-ChildItem . You can get all items directly within a folder by using Get-ChildItem . Для отображения скрытых и системных элементов добавьте необязательный параметр Force . Add the optional Force parameter to display hidden or system items. Например, эта команда отображает непосредственное содержимое диска C Windows PowerShell (которое совпадает с содержимым физического диска C Windows): For example, this command displays the direct contents of Windows PowerShell Drive C (which is the same as the Windows physical drive C):
Эта команда выводит только элементы, содержащиеся на диске непосредственно, так же как и команда DIR оболочки Cmd.exe или команда ls оболочки UNIX. The command lists only the directly contained items, much like using Cmd.exe ‘s DIR command or ls in a UNIX shell. Для показа вложенных элементов необходимо также указать параметр -Recurse . In order to show contained items, you need to specify the -Recurse parameter as well. (Время выполнения этой операции будет очень велико.) Для вывода всего содержимого диска C введите: (This can take an extremely long time to complete.) To list everything on the C drive:
Командлет Get-ChildItem позволяет отфильтровать элементы с помощью параметров Path , Filter , Include и Exclude , но обычно осуществляется лишь фильтрация по имени. Get-ChildItem can filter items with its Path , Filter , Include , and Exclude parameters, but those are typically based only on name. Сложную фильтрацию на основе других свойств элементов можно выполнить с помощью Where-Object . You can perform complex filtering based on other properties of items by using Where-Object .
Следующая команда находит все исполняемые файлы в папке Program Files, которые были в последний раз изменены после 1 октября 2005 г. и размер которых не менее одного мегабайта и не более десяти мегабайт: The following command finds all executables within the Program Files folder that were last modified after October 1, 2005 and which are neither smaller than 1 megabyte nor larger than 10 megabytes:
Копирование файлов и папок Copying Files and Folders
Копирование выполняется с помощью командлета Copy-Item . Copying is done with Copy-Item . Следующая команда создает резервную копию C:\boot.ini в C:\boot.bak: The following command backs up C:\boot.ini to C:\boot.bak:
Если целевой файл уже существует, то попытка копирования завершается неудачей. If the destination file already exists, the copy attempt fails. Чтобы перезаписать имеющийся целевой файл, используйте параметр Force . To overwrite a pre-existing destination, use the Force parameter:
Эта команда работает, даже если целевой объект доступен только для чтения. This command works even when the destination is read-only.
Так же выполняется и копирование папок. Folder copying works the same way. Эта команда копирует папку C:\temp\test1 в новую папку C:\temp\DeleteMe рекурсивно. This command copies the folder C:\temp\test1 to the new folder C:\temp\DeleteMe recursively:
Можно также скопировать избранные элементы. You can also copy a selection of items. Следующая команда копирует все файлы TXT, содержащиеся в папке C:\data , в папку C:\temp\text : The following command copies all .txt files contained anywhere in C:\data to C:\temp\text :
Для копирования элементов файловой системы можно использовать и другие средства. You can still use other tools to perform file system copies. В Windows PowerShell по-прежнему работают команды XCOPY, ROBOCOPY и такие COM-объекты, как Scripting.FileSystemObject . XCOPY, ROBOCOPY, and COM objects, such as the Scripting.FileSystemObject, all work in Windows PowerShell. Например, можно воспользоваться COM-классом Scripting.FileSystem сервера сценариев Windows для создания резервной копии файла C:\boot.ini в файле C:\boot.bak : For example, you can use the Windows Script Host Scripting.FileSystem COM class to back up C:\boot.ini to C:\boot.bak :
Создание файлов и папок Creating Files and Folders
Создание новых элементов осуществляется одинаковым образом всеми поставщиками Windows PowerShell. Creating new items works the same on all Windows PowerShell providers. Если поставщик Windows PowerShell поддерживает более одного типа элементов (например, поставщик Windows PowerShell FileSystem различает каталоги и файлы), необходимо указать тип элемента. If a Windows PowerShell provider has more than one type of item—for example, the FileSystem Windows PowerShell provider distinguishes between directories and files—you need to specify the item type.
Эта команда создает папку C:\temp\New Folder : This command creates a new folder C:\temp\New Folder :
Эта команда создает пустой файл C:\temp\New Folder\file.txt . This command creates a new empty file C:\temp\New Folder\file.txt
При использовании параметра Force с командой New-Item для создания папки, которая уже существует, она не перезапишет и не заменит папку. When using the Force switch with the New-Item command to create a folder, and the folder already exists, it won’t overwrite or replace the folder. Будет просто возвращен имеющийся объект папки. It will simply return the existing folder object. Однако, если использовать New-Item -Force в уже имеющимся файле, файл будет полностью перезаписан. However, if you use New-Item -Force on a file that already exists, the file will be completely overwritten.
Удаление всех файлов и папок, содержащихся в папке Removing All Files and Folders Within a Folder
Удалить вложенные элементы можно с помощью командлета Remove-Item , однако он потребует подтверждения удаления, если элемент сам что-нибудь содержит. You can remove contained items using Remove-Item , but you will be prompted to confirm the removal if the item contains anything else. Например, при попытке удаления папки C:\temp\DeleteMe , которая содержит другие элементы, Windows PowerShell предварительно предложит подтвердить удаление этой папки: For example, if you attempt to delete the folder C:\temp\DeleteMe that contains other items, Windows PowerShell prompts you for confirmation before deleting the folder:
Если подтверждение для каждого вложенного элемента нежелательно, задайте параметр Recurse : If you do not want to be prompted for each contained item, specify the Recurse parameter:
Подключение локальной папки как диска Mapping a Local Folder as a drive
Отобразить локальную папку можно с помощью команды New-PSDrive . You can also map a local folder, using the New-PSDrive command. Следующая команда создает локальный диск P: , корневым каталогом которого является локальный каталог Program Files, отображающийся только в сеансе PowerShell: The following command creates a local drive P: rooted in the local Program Files directory, visible only from the PowerShell session:
Как и при использовании сетевых дисков, диски, отображенные в Windows PowerShell, немедленно становятся доступными оболочке Windows PowerShell. Just as with network drives, drives mapped within Windows PowerShell are immediately visible to the Windows PowerShell shell. Чтобы создать подключенный диск, отображающийся в проводнике, нужен параметр -Persist . In order to create a mapped drive visible from File Explorer, the parameter -Persist is needed. Но с этим параметром можно использовать только удаленные пути. However, only remote paths can be used with Persist.
Чтение текстового файла в массив Reading a Text File into an Array
Одним из наиболее общих форматов хранения текстовых данных является файл, отдельные строки которого рассматриваются как отдельные элементы. One of the more common storage formats for text data is in a file with separate lines treated as distinct data elements. Командлет Get-Content используется для чтения всего файла за один шаг, как показано далее: The Get-Content cmdlet can be used to read an entire file in one step, as shown here:
Командлет Get-Content сразу рассматривает данные, считанные из файла, как массив с одним элементом на строку содержимого файла. Get-Content already treats the data read from the file as an array, with one element per line of file content. Убедиться в этом можно, проверив свойство Length полученного содержимого: You can confirm this by checking the Length of the returned content:
Эта команда наиболее полезна для непосредственного ввода в Windows PowerShell информационных списков. This command is most useful for getting lists of information into Windows PowerShell directly. Например, можно хранить в файле C:\temp\domainMembers.txt список имен компьютеров или IP-адресов по одному имени на каждую строку файла. For example, you might store a list of computer names or IP addresses in a file C:\temp\domainMembers.txt , with one name on each line of the file. Вы можете использовать командлет Get-Content , чтобы извлечь содержимое файла и поместить его в переменную $Computers : You can use Get-Content to retrieve the file contents and put them in the variable $Computers :
Теперь переменная $Computers представляет собой массив, содержащий в каждом элементе имя компьютера. $Computers is now an array containing a computer name in each element.
Computer Host Name via a file
I’m looking for a way to find the host name of a computer via a file. Here is what I mean. I have a couple hard drives removed from old computers, but we forgot to label which machines they were removed from. Now, we need to know which hard drive is to which computer, but we don’t have the original hardware anymore, only the hard drives.
Does anyone know of any files that are created in the C:\Windows or the C:\Windows\System32 folders that contain the host name of the computer while it was booted? I have the ability to read the files on the hard drives via a USB adapter.
Thanks!
Probably the most dependable way is to peer into the System Registry file.
1) Copy the file: \Windows\System32\config\system from the subject drive onto your local hard drive
2) Start up Regedit (Start -> Run -> «regedit»)
3) Single-click on «HKEY_LOCAL_MACHINE» to select it
4) Do: File -> Load Hive. Then navigate to and select the «System» file that you copied from the external disk.
5) When asked for a Key name, enter any name — I’ll Use «EXT» for this example.
6) Double-click on HKEY_LOCAL_MACHINE and you will see a «EXT» key under it.
7) Navigate to EXT\ControlSet001\Control\ComputerName\ComputerName
8) There should be an entry in the right window with the computer name.
9) To clean up, single-click on the «EXT» key to select it then File->Unload Hive. Answer «Yes» in the next box.
64 people found this reply helpful
Was this reply helpful?
Sorry this didn’t help.
Great! Thanks for your feedback.
How satisfied are you with this reply?
Thanks for your feedback, it helps us improve the site.