- Работа с переменными окружения в Powershell Env
- Изменение переменных окружения пользователя в Powershell
- Изменение переменных Env компьютера в Powershell
- Создание новых переменных Environment в Powershell
- Resolve-Path
- Syntax
- Description
- Examples
- Example 1: Resolve the home folder path
- Example 2: Resolve the path of the Windows folder
- Example 3: Get all paths in the Windows folder
- Example 4: Resolve a UNC path
- Example 5: Get relative paths
- Example 6: Resolve a path containing brackets
- Parameters
- Inputs
- Outputs
- Notes
- Get-Location
- Syntax
- Description
- Examples
- Example 1: Display your current drive location
- Example 2: Display your current location for different drives
- Example 3: Get locations using stacks
- Example 4: Customize the PowerShell prompt
- Parameters
- Inputs
- Outputs
- Notes
- Test-Path
- Syntax
- Description
- Examples
- Example 1: Test a path
- Example 2: Test the path of a profile
- Example 3: Check whether there are any files besides a specified type
- Example 4: Check for a file
- Example 5: Check paths in the Registry
- Example 6: Test if a file is newer than a specified date
- Example 7: Test a path with null as the value
- Example 8: Test a path with whitespace as the value
- Parameters
- Inputs
- Outputs
- Notes
Работа с переменными окружения в Powershell Env
09 августа 2019
При работе с переменными окружения в Powershell есть ряд проблем, с которыми мы можем столкнуться. Если мы выполним следующую команду, то увидим, что у нас есть диск и именем Env, который и хранит переменные:
Мы можем в него перейти и увидеть все переменные окружения:
Если мы попробуем изменить переменные следующим способом, то они будут работать только в рамках PS и до окончания сеанса (перезагрузки например):
Способ выше аналогичен этому:
Если нам нужно сделать переменную среды постоянной есть решение для компьютера и конкретного пользователя.
Изменение переменных окружения пользователя в Powershell
У нас есть ветка реестра, которая отвечает за область пользователя:
В деталях мы уже рассматривали как работать в powershell с реестром и не будем разбирать в деталях. Способом ниже мы обратимся к Path и добавим значение «C:\Git\»:
Обращайте внимание, что у вас стоит ; перед новым значением (если вы изменяете Path), и что вы сохраняете предыдущее значение путем сложения.
Получение списка USB устройств в Powershell
Изменение переменных Env компьютера в Powershell
У нас есть другая ветка реестра, которая хранит значения переменных компьютера:
Изменяются они так же, как и в случае с пользователем:
Создание новых переменных Environment в Powershell
Мы можем просто создать новую переменную обращаясь напрямую к реестру, но эти способы были рассмотрены в статье по ссылке выше и есть более простой способ.
Resolve-Path
Resolves the wildcard characters in a path, and displays the path contents.
Syntax
Description
The Resolve-Path cmdlet displays the items and containers that match the wildcard pattern at the location specified. The match can include files, folders, registry keys, or any other object accessible from a PSDrive provider.
Examples
Example 1: Resolve the home folder path
The tilde character (
) is shorthand notation for the current user’s home folder. This example shows Resolve-Path returning the fully qualified path value.
Example 2: Resolve the path of the Windows folder
When run from the root of the C: drive, this command returns the path of the Windows folder in the C: drive.
Example 3: Get all paths in the Windows folder
This command returns all of the folders in the C:\Windows folder. The command uses a pipeline operator (|) to send a path string to Resolve-Path .
Example 4: Resolve a UNC path
This command resolves a Universal Naming Convention (UNC) path and returns the shares in the path.
Example 5: Get relative paths
This command returns relative paths for the directories at the root of the C: drive.
Example 6: Resolve a path containing brackets
This example uses the LiteralPath parameter to resolve the path of the Test[xml] subfolder. Using LiteralPath causes the brackets to be treated as normal characters rather than a regular expression.
Parameters
Specifies a user account that has permission to perform this action. The default is the current user.
Type a user name, such as User01 or Domain01\User01, or pass a PSCredential object. You can create a PSCredential object using the Get-Credential cmdlet. If you type a user name, this cmdlet prompts you for a password.
This parameter is not supported by any providers installed with PowerShell.
Type: | PSCredential |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the path to be resolved. The value of the LiteralPath parameter is used exactly as typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences.
Type: | String [ ] |
Aliases: | PSPath, LP |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the PowerShell path to resolve. This parameter is required. You can also pipe a path string to Resolve-Path . Wildcard characters are permitted.
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
Indicates that this cmdlet returns a relative path.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
You can pipe a string that contains a path to this cmdlet.
Outputs
System.Management.Automation.PathInfo, System.String
Returns a PathInfo object. Returns a string value for the resolved path if you specify the Relative parameter.
Notes
The *-Path cmdlets work with the FileSystem, Registry, and Certificate providers.
Resolve-Path is designed to work with any provider. To list the providers available in your session, type Get-PSProvider . For more information, see about_providers.
Resolve-Path only resolves existing paths. It cannot be used to resolve a location that does not exist yet.
Get-Location
Gets information about the current working location or a location stack.
Syntax
Description
The Get-Location cmdlet gets an object that represents the current directory, much like the print working directory (pwd) command.
When you move between PowerShell drives, PowerShell retains your location in each drive. You can use this cmdlet to find your location in each drive.
You can use this cmdlet to get the current directory at run time and use it in functions and scripts, such as in a function that displays the current directory in the PowerShell prompt.
You can also use this cmdlet to display the locations in a location stack. For more information, see the Notes and the descriptions of the Stack and StackName parameters.
Examples
Example 1: Display your current drive location
This command displays your location in the current PowerShell drive.
For instance, if you are in the Windows directory of the C: drive, it displays the path to that directory.
Example 2: Display your current location for different drives
This example demonstrates the use of Get-Location to display your current location in different PowerShell drives. Set-Location is used to change the location to several different paths on different PSDrives.
Example 3: Get locations using stacks
This example shows how to use the Stack and StackName parameters of Get-Location to list the locations in the current location stack and alternate location stacks.
The Push-Location cmdlet is used to change into three different locations. The third push uses a different stack name. The Stack parameter of Get-Location displays the contents of the default stack. The StackName parameter of Get-Location displays the contents of the stack named Stack2 .
Example 4: Customize the PowerShell prompt
This example shows how to customize the PowerShell prompt.
The function that defines the prompt includes a Get-Location command, which is run whenever the prompt appears in the console.
The format of the default PowerShell prompt is defined by a special function named prompt . You can change the prompt in your console by creating a new function named prompt .
To see the current prompt function, type the following command: Get-Content Function:\prompt
Parameters
Gets the current location in the specified PowerShell drive.
For instance, if you are in the Cert: drive, you can use this parameter to find your current location in the C: drive.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Gets the current location in the drive supported by the specified PowerShell provider. If the specified provider supports more than one drive, this cmdlet returns the location on the most recently accessed drive.
For example, if you are in the C: drive, you can use this parameter to find your current location in the drives of the PowerShell Registry provider.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Indicates that this cmdlet displays the locations added to the current location stack. You can add locations to stacks by using the Push-Location cmdlet.
To display the locations in a different location stack, use the StackName parameter. For information about location stacks, see the Notes.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies, as a string array, the named location stacks. Enter one or more location stack names.
To display the locations in the current location stack, use the Stack parameter. To make a location stack the current location stack, use the Set-Location cmdlet.
This cmdlet cannot display the locations in the unnamed default stack unless it is the current stack.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Inputs
None
You cannot pipe input to this cmdlet.
Outputs
System.Management.Automation.PathInfo or System.Management.Automation.PathInfoStack
If you use the Stack or StackName parameters, this cmdlet returns a PathInfoStack object. Otherwise, it returns a PathInfo object.
Notes
PowerShell supports multiple runspaces per process. Each runspace has its own current directory. This is not the same as [System.Environment]::CurrentDirectory . This behavior can be an issue when calling .NET APIs or running native applications without providing explicit directory paths. The Get-Location cmdlet returns the current directory of the current PowerShell runspace.
This cmdlet is designed to work with the data exposed by any provider. To list the providers in your session, type Get-PSProvider . For more information, see about_Providers.
The ways that the PSProvider, PSDrive, Stack, and StackName parameters interact depends on the provider. Some combinations will result in errors, such as specifying both a drive and a provider that does not expose that drive. If no parameters are specified, this cmdlet returns the PathInfo object for the provider that contains the current working location.
A stack is a last-in, first-out list in which only the most recently added item is accessible. You add items to a stack in the order that you use them, and then retrieve them for use in the reverse order. PowerShell lets you store provider locations in location stacks. PowerShell creates an unnamed default location stack and you can create multiple named location stacks. If you do not specify a stack name, PowerShell uses the current location stack. By default, the unnamed default location is the current location stack, but you can use the Set-Location cmdlet to change the current location stack.
To manage location stacks, use the PowerShell *-Location cmdlets, as follows.
To add a location to a location stack, use the Push-Location cmdlet.
To get a location from a location stack, use the Pop-Location cmdlet.
To display the locations in the current location stack, use the Stack parameter of the Get-Location cmdlet. To display the locations in a named location stack, use the StackName parameter of the Get-Location cmdlet.
To create a new location stack, use the StackName parameter of the Push-Location cmdlet. If you specify a stack that does not exist, Push-Location creates the stack.
To make a location stack the current location stack, use the StackName parameter of the Set-Location cmdlet.
The unnamed default location stack is fully accessible only when it is the current location stack. If you make a named location stack the current location stack, you can no longer use the Push-Location or Pop-Location cmdlets to add or get items from the default stack or use this cmdlet to display the locations in the unnamed stack. To make the unnamed stack the current stack, use the StackName parameter of the Set-Location cmdlet with a value of $null or an empty string ( «» ).
Test-Path
Determines whether all elements of a path exist.
Syntax
Description
The Test-Path cmdlet determines whether all elements of the path exist. It returns $True if all elements exist and $False if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or leaf element. If the Path is whitespace an empty string, then $False is returned. If the Path is $null , array of $null or empty array, a non-terminating error is returned.
Examples
Example 1: Test a path
This command checks whether all elements in the path exist, that is, the C: directory, the Documents and Settings directory, and the DavidC directory. If any are missing, the cmdlet returns $False . Otherwise, it returns $True .
Example 2: Test the path of a profile
These commands test the path of the PowerShell profile.
The first command determines whether all elements in the path exist. The second command determines whether the syntax of the path is correct. In this case, the path is $False , but the syntax is correct $True . These commands use $profile , the automatic variable that points to the location for the profile, even if the profile does not exist.
For more information about automatic variables, see about_Automatic_Variables.
Example 3: Check whether there are any files besides a specified type
This command checks whether there are any files in the Commercial Buildings directory other than .dwg files.
The command uses the Path parameter to specify the path. Because the path includes a space, the path is enclosed in quotation marks. The asterisk at the end of the path indicates the contents of the Commercial Building directory. With long paths, such as this one, type the first few letters of the path, and then use the TAB key to complete the path.
The command specifies the Exclude parameter to specify files that will be omitted from the evaluation.
In this case, because the directory contains only .dwg files, the result is $False .
Example 4: Check for a file
This command checks whether the path stored in the $profile variable leads to a file. In this case, because the PowerShell profile is a .ps1 file, the cmdlet returns $True .
Example 5: Check paths in the Registry
These commands use Test-Path with the PowerShell registry provider.
The first command tests whether the registry path of the Microsoft.PowerShell registry key is correct on the system. If PowerShell is installed correctly, the cmdlet returns $True .
Test-Path does not work correctly with all PowerShell providers. For example, you can use Test-Path to test the path of a registry key, but if you use it to test the path of a registry entry, it always returns $False , even if the registry entry is present.
Example 6: Test if a file is newer than a specified date
This command uses the NewerThan dynamic parameter to determine whether the «PowerShell.exe» file on the computer is newer than «July 13, 2009».
The NewerThan parameter works only in file system drives.
Example 7: Test a path with null as the value
The error returned for null , array of null or empty array is a non-terminating error. It can be suppress by using -ErrorAction SilentlyContinue . The following example shows all cases which return the NullPathNotPermitted error.
Example 8: Test a path with whitespace as the value
When a whitespace or empty string is provided for the the -Path parameter, it returns False. The following example show whitespace and empty string.
Parameters
This parameter is not supported by any providers installed with PowerShell. To impersonate another user, or elevate your credentials when running this cmdlet, use Invoke-Command.
Type: | PSCredential |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies items that this cmdlet omits. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as «*.txt». Wildcard characters are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies a filter in the format or language of the provider. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcard characters, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when it retrieves the objects instead of having PowerShell filter the objects after they are retrieved.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies paths that this cmdlet tests. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as «*.txt». Wildcard characters are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Indicates that this cmdlet tests the syntax of the path, regardless of whether the elements of the path exist. This cmdlet returns $True if the path syntax is valid and $False if it is not.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a path to be tested. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcard characters. If the path includes characters that could be interpreted by PowerShell as escape sequences, you must enclose the path in single quote so that they won’t be interpreted.
Type: | String [ ] |
Aliases: | PSPath, LP |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specify a time as a DateTime object.
Type: | Nullable [ DateTime ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specify a time as a DateTime object.
Type: | Nullable [ DateTime ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a path to be tested. Wildcard characters are permitted. If the path includes spaces, enclose it in quotation marks.
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
Specifies the type of the final element in the path. This cmdlet returns $True if the element is of the specified type and $False if it is not. The acceptable values for this parameter are:
- Container. An element that contains other elements, such as a directory or registry key.
- Leaf. An element that does not contain other elements, such as a file.
- Any. Either a container or a leaf.
Tells whether the final element in the path is of a particular type.
Up to PowerShell version 6.1.2, when the IsValid and PathType switches are specified together, the Test-Path cmdlet ignores the PathType switch and only validates the syntactic path without validating the path type.
According to issue #8607, fixing this behavior may be a breaking change in a future version, where the IsValid and PathType switches belong to separate parameter sets, and thus, cannot be used together avoiding this confusion.
Type: | TestPathType |
Aliases: | Type |
Accepted values: | Any, Container, Leaf |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
You can pipe a string that contains a path, but not a literal path, to this cmdlet.
Outputs
The cmdlet returns a Boolean value.
Notes
The cmdlets that contain the Path noun (the Path cmdlets) work with path names and return the names in a concise format that all PowerShell providers can interpret. They are designed for use in programs and scripts where you want to display all or part of a path name in a particular format. Use them as you would use Dirname, Normpath, Realpath, Join, or other path manipulators.
The Test-Path is designed to work with the data exposed by any provider. To list the providers available in your session, type Get-PSProvider . For more information, see about_Providers.