diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md index 04768bd79f33..dfdbb2dda125 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md @@ -209,7 +209,7 @@ An expression was expected after '('. The following examples work: ``` -PS> 2uL.GetType().Name +PS> 2L.GetType().Name Int64 PS> 1.234.GetType().Name Double diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md index 04768bd79f33..dfdbb2dda125 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md @@ -209,7 +209,7 @@ An expression was expected after '('. The following examples work: ``` -PS> 2uL.GetType().Name +PS> 2L.GetType().Name Int64 PS> 1.234.GetType().Name Double diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md index 04768bd79f33..dfdbb2dda125 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_numeric_literals.md @@ -209,7 +209,7 @@ An expression was expected after '('. The following examples work: ``` -PS> 2uL.GetType().Name +PS> 2L.GetType().Name Int64 PS> 1.234.GetType().Name Double diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_numeric_literals.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_numeric_literals.md index 04768bd79f33..dfdbb2dda125 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_numeric_literals.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_numeric_literals.md @@ -209,7 +209,7 @@ An expression was expected after '('. The following examples work: ``` -PS> 2uL.GetType().Name +PS> 2L.GetType().Name Int64 PS> 1.234.GetType().Name Double diff --git a/reference/7/CimCmdlets/CimCmdlets.md b/reference/7/CimCmdlets/CimCmdlets.md new file mode 100644 index 000000000000..6a91f4211c2d --- /dev/null +++ b/reference/7/CimCmdlets/CimCmdlets.md @@ -0,0 +1,60 @@ +--- +ms.date: 02/20/2019 +schema: 2.0.0 +locale: en-US +keywords: powershell,cmdlet +Help Version: 6.1.0.1 +Download Help Link: https://go.microsoft.com/fwlink/?linkid=855946 +Module Guid: fb6cc51d-c096-4b38-b78d-0fed6277096a +Module Name: CimCmdlets +--- +# CimCmdlets Module + +## Description + +Contains cmdlets that interact with Common Information Model (CIM) Servers like the Windows +Management Instrumentation (WMI) service. + +## CimCmdlets Cmdlets + +### [Export-BinaryMiLog](Export-BinaryMiLog.md) +Creates a binary encoded representation of an object or objects and stores it in a file. + +### [Get-CimAssociatedInstance](Get-CimAssociatedInstance.md) +Retrieves the CIM instances that are connected to a specific CIM instance by an association. + +### [Get-CimClass](Get-CimClass.md) +Gets a list of CIM classes in a specific namespace. + +### [Get-CimInstance](Get-CimInstance.md) +Gets the CIM instances of a class from a CIM server. + +### [Get-CimSession](Get-CimSession.md) +Gets the CIM session objects from the current session. + +### [Import-BinaryMiLog](Import-BinaryMiLog.md) +Used to re-create the saved objects based on the contents of an export file. + +### [Invoke-CimMethod](Invoke-CimMethod.md) +Invokes a method of a CIM class. + +### [New-CimInstance](New-CimInstance.md) +Creates a CIM instance. + +### [New-CimSession](New-CimSession.md) +Creates a CIM session. + +### [New-CimSessionOption](New-CimSessionOption.md) +Specifies advanced options for the `New-CimSession` cmdlet. + +### [Register-CimIndicationEvent](Register-CimIndicationEvent.md) +Subscribes to indications using a filter expression or a query expression. + +### [Remove-CimInstance](Remove-CimInstance.md) +Removes a CIM instance from a computer. + +### [Remove-CimSession](Remove-CimSession.md) +Removes one or more CIM sessions. + +### [Set-CimInstance](Set-CimInstance.md) +Modifies a CIM instance on a CIM server by calling the **ModifyInstance** method of the CIM class. \ No newline at end of file diff --git a/reference/7/CimCmdlets/Export-BinaryMiLog.md b/reference/7/CimCmdlets/Export-BinaryMiLog.md new file mode 100644 index 000000000000..194943794a72 --- /dev/null +++ b/reference/7/CimCmdlets/Export-BinaryMiLog.md @@ -0,0 +1,94 @@ +--- +ms.date: 02/20/2019 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +online version: http://go.microsoft.com/fwlink/?LinkId=301310 +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +--- + +# Export-BinaryMiLog + +## SYNOPSIS +Creates a binary encoded representation of an object or objects and stores it in a file. + +## SYNTAX + +```powershell +Export-BinaryMiLog [-InputObject ] [-Path] +``` + +## DESCRIPTION + +The `Export-BinaryMILog` cmdlet creates a binary-based representation of an object or objects and +stores it in a file. You can then use the `Import-BinaryMiLog` cmdlet to re-create the saved object +based on the contents of that file. + +This cmdlet is similar to `Import-Clixml`, except that `Export-BinaryMILog` stores the resulting +object in a binary encoded file. + +## EXAMPLES + +### Example 1 - Create a binary representation of CimInstances + +```powershell +Get-CimInstance Win32_Process | Export-BinaryMiLog -Path "Processes.bmil" +``` + +This command exports CimInstances to a binary MI log file specified by the Path parameter. +See the example for Import-BinaryMiLog to see how to recreate the CimInstances by importing this file. + +## PARAMETERS + +### -InputObject + +Specifies the input to this cmdlet. You can use this parameter, or you can pipe the input to this +cmdlet. + +```yaml +Type: CimInstance +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Path + +Specifies the path of the file in which to store the binary representation of the object. The +**Path** parameter supports wild cards and relative paths. This cmdlet generates an error if the +path resolves to more than one file. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: True +``` + +## INPUTS + +### Microsoft.Management.Infrastructure.CimInstance + +## OUTPUTS + +### System.Object + +## NOTES + +## RELATED LINKS + +[Get-CimInstance](get-ciminstance.md) + +[Import-BinaryMiLog](import-binarymilog.md) + +[Import-Clixml](../microsoft.powershell.utility/import-clixml.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/Get-CimAssociatedInstance.md b/reference/7/CimCmdlets/Get-CimAssociatedInstance.md new file mode 100644 index 000000000000..0a7ab842868d --- /dev/null +++ b/reference/7/CimCmdlets/Get-CimAssociatedInstance.md @@ -0,0 +1,315 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- + +# Get-CimAssociatedInstance + +## SYNOPSIS +Retrieves the CIM instances that are connected to a specific CIM instance by an association. + +## SYNTAX + +### ComputerSet (Default) +``` +Get-CimAssociatedInstance [[-Association] ] [-ResultClassName ] [-InputObject] + [-Namespace ] [-OperationTimeoutSec ] [-ResourceUri ] [-ComputerName ] + [-KeyOnly] [] +``` + +### SessionSet +``` +Get-CimAssociatedInstance [[-Association] ] [-ResultClassName ] [-InputObject] + [-Namespace ] [-OperationTimeoutSec ] [-ResourceUri ] -CimSession + [-KeyOnly] [] +``` + +## DESCRIPTION +The Get-CimAssociatedInstance cmdlet retrieves the CIM instances connected to a specific CIM +instance, called the source instance, by an association. + +In an association, each CIM instance has a named role and the same CIM instance can participate in +an association in different roles. + +If the InputObject parameter is not specified, the cmdlet works in one of the following ways: + +- If neither the ComputerName parameter nor the CimSession parameter is specified, then this cmdlet + works on local Windows Management Instrumentation (WMI) using a Component Object Model (COM) + session. +- If either the ComputerName parameter or the CimSession parameter is specified, then this cmdlet + works against the CIM server specified by either the ComputerName parameter or the CimSession + parameter. + +## EXAMPLES + +### Example 1: Get all the associated instances of a specific instance +``` +PS C:\>$disk = Get-CimInstance -ClassName Win32_LogicalDisk -KeyOnly + +PS C:\>Get-CimAssociatedInstance -InputObject $disk[1] +``` + +This set of commands retrieves the instances of the class named Win32_LogicalDisk and stores the +information in a variable named $disk using the Get-CimInstance cmdlet. The first logical disk +instance in the variable is then used as the input object for the Get-CimAssociatedInstance cmdlet +to get all the associated CIM instances of the specified CIM instance. + +### Example 2: Get all the associated instances of a specific type +``` +PS C:\>$disk = Get-CimInstance -ClassName Win32_LogicalDisk -KeyOnly + +PS C:\>Get-CimAssociatedInstance -InputObject $disk[1] -ResultClass Win32_DiskPartition +``` + +This set of commands retrieves all of the instances of the class named Win32_LogicalDisk and stores +them in a variable named $disk. The first logical disk instance in the variable is then used as the +input object for the Get-CimAssociatedInstance cmdlet to get all the associated instances that are +associated through the specified association class Win32_DiskPartition. + +### Example 3: Get all the associated instances through qualifier of a specific class +``` +PS C:\>$s = Get-CimInstance -Query "Select * from Win32_Service where name like 'Winmgmt'" + +PS C:\>Get-CimClass -ClassName *Service* -Qualifier "Association" + +PS C:\>$c.CimClasName +Win32_LoadOrderGroupServiceDependencies +Win32_DependentService +Win32_SystemServices +Win32_LoadOrderGroupServiceMembers +Win32_ServiceSpecificationService + +PS C:\>Get-CimAssociatedInstance -InputObject $s -Association Win32_DependentService +``` + +This set of commands retrieves the services that depend on Windows Management Instrumentation (WMI) +service and stores them in a variable named $s. The association class name for the +Win32_DependentService is retrieved using the Get-CimClass cmdlet by specifying Association as the +qualifier and is then passed with $s to the Get-CimAssociatedInstance cmdlet to get all the +associated instances of the retrieved association class. + +## PARAMETERS + +### -Association +Specifies the name of the association class. + +If you do not specify this parameter, the cmdlet returns all existing association objects +irrespective of their type. + +For example, if class A is associated with class B through two associations, AB1 and AB2, then this +parameter can be used to specify the type of association, either AB1 or AB2. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -CimSession +Runs the command using the specified CIM session. Enter a variable that contains the CIM session, or +a command that creates or gets the CIM session, such as New-CimSession or Get-CimSession. For more +information, see about_CimSessions. + +```yaml +Type: CimSession[] +Parameter Sets: SessionSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ComputerName +Specifies the name of the computer on which you want to run the CIM operation. +You can specify a fully qualified domain name (FQDN) or a NetBIOS name. + +If you specify this parameter, the cmdlet creates a temporary session to the specified computer +using the WsMan protocol. + +If you do not specify this parameter, the cmdlet performs the operation on the local computer using +Component Object Model (COM). + +If multiple operations are being performed on the same computer, connecting using a CIM session +gives better performance. + +```yaml +Type: String[] +Parameter Sets: ComputerSet +Aliases: CN, ServerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Specifies the input to this cmdlet. +You can use this parameter, or you can pipe the input to this cmdlet. + +```yaml +Type: CimInstance +Parameter Sets: (All) +Aliases: CimInstance + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -KeyOnly +Returns objects with only key properties populated. + +This reduces the amount of data that is transferred over the network. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Namespace +Specifies the namespace for the CIM operation. + +The default namespace is root/cimv2. + +> [!NOTE] +> You can use tab completion to browse the list of namespaces, because Windows PowerShell gets a +> list of namespaces from the local WMI server to provide the list of namespaces. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -OperationTimeoutSec +Specifies the amount of time that the cmdlet waits for a response from the computer. + +By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout +value for the server. + +If the OperationTimeoutSec parameter is set to a value less than the robust connection retry timeout +of 3 minutes, network failures that last more than the value of the OperationTimeoutSec parameter +are not recoverable, because the operation on the server times out before the client can reconnect. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: OT + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ResourceUri +Specifies the resource uniform resource identifier (URI) of the resource class or instance. The URI +is used to identify a specific type of resource, such as disks or processes, on a computer. + +A URI consists of a prefix and a path to a resource. +For example: + +- `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` +- `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings` + +By default, if you do not specify this parameter, the DMTF standard resource URI +`http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. + +ResourceURI can only be used with CIM sessions created using the WSMan protocol, or when specifying +the ComputerName parameter, which creates a CIM session using WSMan. If you specify this parameter +without specifying the ComputerName parameter, or if you specify a CIM session created using DCOM +protocol, you will get an error, because the DCOM protocol does not support the ResourceURI +parameter. + +If both the ResourceUri parameter and the Filter parameter are specified, the Filter parameter is +ignored. + +```yaml +Type: Uri +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResultClassName +Specifies the class name of the associated instances. +A CIM instance can be associated with one or more CIM instances. +All associated CIM instances are returned if you do not specify the result class name. + +By default, the value of this parameter is null, which means all associated CIM instances will be returned. + +You can filter the association results to match a specific class name. +Filtering happens on the server. +If this parameter is not specified, Get-CIMAssociatedInstance returns all existing associations. +For example, if class A is associated with classes B, C and D, then this parameter can be used to restrict the output to a specific type (B, C or D). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None +This cmdlet accepts no input objects. + +## OUTPUTS + +### System.Object +This cmdlet returns an object. + +## NOTES + +## RELATED LINKS + +[Get-CimClass](get-cimclass.md) + +[Get-CimInstance](get-ciminstance.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/Get-CimClass.md b/reference/7/CimCmdlets/Get-CimClass.md new file mode 100644 index 000000000000..011dd4743e82 --- /dev/null +++ b/reference/7/CimCmdlets/Get-CimClass.md @@ -0,0 +1,261 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- + +# Get-CimClass + +## SYNOPSIS +Gets a list of CIM classes in a specific namespace. + +## SYNTAX + +### ComputerSet (Default) +``` +Get-CimClass [[-ClassName] ] [[-Namespace] ] [-OperationTimeoutSec ] + [-ComputerName ] [-MethodName ] [-PropertyName ] [-QualifierName ] + [] +``` + +### SessionSet +``` +Get-CimClass [[-ClassName] ] [[-Namespace] ] [-OperationTimeoutSec ] + -CimSession [-MethodName ] [-PropertyName ] [-QualifierName ] + [] +``` + +## DESCRIPTION +The Get-CimClass cmdlet retrieves a list of CIM classes in a specific namespace. + +If there is no class name supplied, then the cmdlet returns all the classes in the namespace. + +Unlike a CIM instance, CIM classes do not contain the CIM session or computer name from which they are retrieved. + +## EXAMPLES + +### Example 1: Get all the class definitions +``` +PS C:\>Get-CimClass +``` + +This command gets all the class definitions under the namespace root/cimv2. + +### Example 2: Get the classes with a specific name +``` +PS C:\>Get-CimClass -ClassName *disk* +``` + +This command gets the classes that contain the word disk in their names. + +### Example 3: Get the classes with a specific method name +``` +PS C:\>Get-CimClass -ClassName Win32* -MethodName Term* +``` + +This command gets the classes that start with the name Win32 and have a method name that starts with Term. + +### Example 4: Get the classes with a specific property name +``` +PS C:\>Get-CimClass -ClassName Win32* -PropertyName Handle +``` + +This command gets the classes that start with the name Win32 and have a property named Handle. + +### Example 5: Get the classes with a specific qualifier name +``` +PS C:\>Get-CimClass -ClassName Win32*Disk* -QualifierName Association +``` + +This command gets the classes that start with the name Win32, contain the word Disk in their names and have the specified qualifier Association. + +### Example 6: Get the class definitions from a specific namespace +``` +PS C:\>Get-CimClass -Namespace root/standardCimv2 -ClassName *Net* +``` + +This command gets the class definitions that contain the word Net in their names from the specified namespace root/standardCimv2. + +### Example 7: Get the class definitions from a remote server +``` +PS C:\>Get-CimClass -ClassName *disk* -ComputerName Server01, Server02 +``` + +This command gets the class definitions that contain the word disk in their names from the specified remote servers Server01 and Server02. + +### Example 8: Get the classes by using a CIM session +``` +PS C:\>$s = New-CimSession -ComputerName Server01, Server02 + + + +PS C:\>Get-CimClass -ClassName *disk* -CimSession $s +``` + +This set of commands creates a session with multiple computers and stores it into a variable $s using the New-CimSession cmdlet, and then gets the classes using the Get-CimClass cmdlet. + +## PARAMETERS + +### -CimSession +Runs the cmdlet in a remote session or on a remote computer. +Enter a computer name or a session object, such as the output of a New-CimSession or Get-CimSession cmdlet. +The default is the current session on the local computer. + +```yaml +Type: CimSession[] +Parameter Sets: SessionSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ClassName +Specifies the name of the CIM class for which to perform the operation. +NOTE: You can use tab completion to browse the list of classes, because PowerShell gets a list of classes from the local WMI server to provide a list of class names. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ComputerName +Specifies the computer on which you want to run the CIM operation. +You can specify a fully qualified domain name (FQDN) a NetBIOS name, or an IP address. + +If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the WsMan protocol. + +If you do not specify this parameter, the cmdlet performs the operation on the local computer using Component Object Model (COM). + +If multiple operations are being performed on the same computer, using a CIM session gives better performance. + +```yaml +Type: String[] +Parameter Sets: ComputerSet +Aliases: CN, ServerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -MethodName +Finds the classes that have a method matching this name. + +You can use wildcard characters with this parameter. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Namespace +Specifies the namespace for CIM operation. + +The default namespace is root/cimv2. +NOTE: You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -OperationTimeoutSec +Specifies the amount of time that the cmdlet waits for a response from the computer. + +By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. + +If the OperationTimeoutSec parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the OperationTimeoutSec parameter are not recoverable, because the operation on the server times out before the client can reconnect. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: OT + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -PropertyName +Finds the classes which have a property matching this name. + +You can use wildcard characters with this parameter. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -QualifierName +Filters the classes by class level qualifier name. +You can use wildcard characters with this parameter. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None +This cmdlet accepts no input objects. + +## OUTPUTS + +### Microsoft.Management.Infrastructure.CimClass +This cmdlet returns a CIM class object. + +## NOTES + +## RELATED LINKS + +[New-CimSession](New-CimSession.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/Get-CimInstance.md b/reference/7/CimCmdlets/Get-CimInstance.md new file mode 100644 index 000000000000..69f16ec4e027 --- /dev/null +++ b/reference/7/CimCmdlets/Get-CimInstance.md @@ -0,0 +1,522 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 02/21/2019 +schema: 2.0.0 +--- + +# Get-CimInstance + +## SYNOPSIS +Gets the CIM instances of a class from a CIM server. + +## SYNTAX + +### ClassNameComputerSet (Default) + +``` +Get-CimInstance [-ClassName] [-ComputerName ] [-KeyOnly] [-Namespace ] + [-OperationTimeoutSec ] [-QueryDialect ] [-Shallow] [-Filter ] [-Property ] + [] +``` + +### ResourceUriSessionSet + +``` +Get-CimInstance -CimSession -ResourceUri [-KeyOnly] [-Namespace ] + [-OperationTimeoutSec ] [-Shallow] [-Filter ] [-Property ] [] +``` + +### QuerySessionSet + +``` +Get-CimInstance -CimSession [-ResourceUri ] [-Namespace ] + [-OperationTimeoutSec ] -Query [-QueryDialect ] [-Shallow] [] +``` + +### ClassNameSessionSet + +``` +Get-CimInstance -CimSession [-ClassName] [-KeyOnly] [-Namespace ] + [-OperationTimeoutSec ] [-QueryDialect ] [-Shallow] [-Filter ] [-Property ] + [] +``` + +### CimInstanceSessionSet + +``` +Get-CimInstance -CimSession [-ResourceUri ] [-OperationTimeoutSec ] + [-InputObject] [] +``` + +### CimInstanceComputerSet + +``` +Get-CimInstance [-ResourceUri ] [-ComputerName ] [-OperationTimeoutSec ] + [-InputObject] [] +``` + +### ResourceUriComputerSet + +``` +Get-CimInstance -ResourceUri [-ComputerName ] [-KeyOnly] [-Namespace ] + [-OperationTimeoutSec ] [-Shallow] [-Filter ] [-Property ] [] +``` + +### QueryComputerSet + +``` +Get-CimInstance [-ResourceUri ] [-ComputerName ] [-Namespace ] + [-OperationTimeoutSec ] -Query [-QueryDialect ] [-Shallow] [] +``` + +## DESCRIPTION + +The `Get-CimInstance` cmdlet gets the CIM instances of a class from a CIM server. You can specify +either the class name or a query for this cmdlet. This cmdlet returns one or more CIM instance +objects representing a snapshot of the CIM instances present on the CIM server. + +If the **InputObject** parameter is not specified, the cmdlet works in one of the following ways: + +- If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this + cmdlet works on local Windows Management Instrumentation (WMI) using a Component Object Model + (COM) session. +- If either the **ComputerName** parameter or the **CimSession** parameter is specified, then this + cmdlet works against the CIM server specified by either the **ComputerName** parameter or the + **CimSession** parameter. + +If the **InputObject** parameter is specified, the cmdlet works in one of the following ways: + +- If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this + cmdlet uses the CIM session or computer name from the input object. +- If the either the **ComputerName** parameter or the **CimSession** parameter is specified, then + this cmdlet uses the either the CimSession parameter value or **ComputerName** parameter value. + +## EXAMPLES + +### Example 1: Get the CIM instances of a specified class + +```powershell +Get-CimInstance -ClassName Win32_Process +``` + +This command retrieves the CIM instances of a class named **Win32_Process**. + +### Example 2: Get a list of namespaces from a WMI server + +```powershell +Get-CimInstance -Namespace root -ClassName __Namespace +``` + +This command retrieves a list of namespaces under the Root namespace on a WMI server. + +### Example 3: Get instances of a class filtered by using a query + +```powershell +Get-CimInstance -Query "SELECT * from Win32_Process WHERE name LIKE 'p%'" +``` + +This command retrieves all the CIM instances that start with the letter p of a class named +**Win32_Process** using the query specified by a **Query** parameter. + +### Example 4: Get instances of a class filtered by using a class name and a filter expression + +```powershell +Get-CimInstance -ClassName Win32_Process -Filter "Name like 'p%'" +``` + +This command retrieves all the CIM instances that start with the letter "p" of a class named +**Win32_Process** using the Filter parameter. + +### Example 5: Get the CIM instances with only key properties filled in + +```powershell +$x = New-CimInstance -ClassName Win32_Process -Namespace root\cimv2 -Property @{ "Handle"=0 } -Key Handle -ClientOnly +Get-CimInstance -CimInstance $x +``` + +This set of commands creates a new CIM instance in memory for a class named **Win32_Process** with +the key property `@{ "Handle"=0 }` and stores it in a variable named `$x`. The variable is passed as +a CIM instance to the `Get-CimInstance` cmdlet to get a particular instance. + +### Example 6: Retrieve CIM instances and reuse them + +```powershell +$x,$y = Get-CimInstance -ClassName Win32_Process +$x | Format-Table -Property Name,KernelModeTime -AutoSize +$x | Get-CimInstance | Format-Table -Property Name,KernelModeTime -AutoSize +``` + +This set of commands gets the CIM instances of a class named **Win32_Process** and stores them in +the variables `$x` and `$y`. The variable `$x` is then formatted in a table containing only the +powershell and the powershell attributes, the table set to **AutoSize**. + +### Example 7: Get CIM instances from remote computer + +```powershell +Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName Server01,Server02 +``` + +This command retrieves the CIM instances of a class named **Win32_ComputerSystem** from the remote +computers named Server01 and Server02. + +### Example 8: Getting only the key properties, instead of all properties + +```powershell +Get-CimInstance -Class Win32_Process -KeyOnly +$x = Get-CimInstance -Class Win32_Process -KeyOnly +$x | Invoke-CimMethod -MethodName GetOwner +``` + +This command retrieves only the key properties, which reduces the size of the object and network +traffic. + +### Example 9: Getting only a subset of properties, instead of all properties + +```powershell +Get-CimInstance -Class Win32_Process -Property Name,KernelModeTime +$x = Get-CimInstance -Class Win32_Process -Property Name,KernelModeTime +$x | Invoke-CimMethod -MethodName GetOwner +``` + +The instance retrieved with the Property parameter can be used to perform other CIM operations, for +example `Set-CimInstance` or `Invoke-CimMethod`. + +This command retrieves only a subset of properties, which reduces the size of the object and network +traffic. + +### Example 10: Get the CIM instance using CIM session + +```powershell +$s = New-CimSession -ComputerName Server01,Server02 +Get-CimInstance -ClassName Win32_ComputerSystem -CimSession $s +``` + +This set of commands creates a CIM session on the computers named Server01 and Server02 using the +`New-CimSession` cmdlet and stores the session information in a variable named `$s`. The contents of +the variable are then passed to `Get-CimInstance` by using the **CimSession** parameter, to get the +CIM instances of the class named **Win32_ComputerSystem**. + +## PARAMETERS + +### -CimSession + +Specifies the CIM session to use for this cmdlet. Enter a variable that contains the CIM session or +a command that creates or gets the CIM session, such as the `New-CimSession` or `Get-CimSession` +cmdlets. For more information, see [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md). + +```yaml +Type: CimSession[] +Parameter Sets: ResourceUriSessionSet, QuerySessionSet, ClassNameSessionSet, CimInstanceSessionSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ClassName + +Specifies the name of the CIM class for which to retrieve the CIM instances. You can use tab +completion to browse the list of classes, because PowerShell gets a list of classes from the local +WMI server to provide a list of class names. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, ClassNameSessionSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ComputerName + +Specifies computer on which you want to run the CIM operation. You can specify a fully qualified +domain name (FQDN), a NetBIOS name, or an IP address. If you do not specify this parameter, the +cmdlet performs the operation on the local computer using Component Object Model (COM). + +If you specify this parameter, the cmdlet creates a temporary session to the specified computer +using the WsMan protocol. + +If multiple operations are being performed on the same computer, connect using a CIM session for +better performance. + +```yaml +Type: String[] +Parameter Sets: ClassNameComputerSet, CimInstanceComputerSet, ResourceUriComputerSet, QueryComputerSet +Aliases: CN, ServerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Filter + +Specifies a where clause to use as a filter. Specify the clause in either the **WQL** or the **CQL** +query language. + +Note: Do not include the where keyword in the value of the parameter. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, ClassNameSessionSet, ResourceUriComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -InputObject + +Specifies a CIM instance object to use as input. + +If you are already working with a CIM instance object, you can use this parameter to pass the CIM +instance object in order to get the latest snapshot from the CIM server. When you pass a CIM +instance object as an input, `Get-CimInstance` returns the object from server using a get CIM +operation, instead of an enumerate or query operation. Using a get CIM operation is more efficient +than retrieving all instances and then filtering them. + +If the CIM class does not implement the get operation, then specifying the **InputObject** parameter returns an error. + +```yaml +Type: CimInstance +Parameter Sets: CimInstanceSessionSet, CimInstanceComputerSet +Aliases: CimInstance + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -KeyOnly + +Indicates that only objects with key properties populated are returned. Specifying the **KeyOnly** +parameter reduces the amount of data transferred over the network. + +Use the KeyOnly parameter to return only a small portion of the object, which can be used for other +operations, such as the `Set-CimInstance` or `Get-CimAssociatedInstance` cmdlets. + +```yaml +Type: SwitchParameter +Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, ClassNameSessionSet, ResourceUriComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Namespace + +Specifies the namespace of CIM class. + +The default namespace is **root/cimv2**. You can use tab completion to browse the list of +namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the +list of namespaces. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, QuerySessionSet, ClassNameSessionSet, ResourceUriComputerSet, QueryComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -OperationTimeoutSec + +Specifies the amount of time that the cmdlet waits for a response from the computer. By default, the +value of this parameter is 0, which means that the cmdlet uses the default timeout value for the +server. + +If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry +timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** +parameter are not recoverable, because the operation on the server times out before the client can +reconnect. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: OT + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Property + +Specifies a set of instance properties to retrieve. Use this parameter when you need to reduce the +size of the object returned, either in memory or over the network. + +The object returned always has key properties populated, irrespective of the set of properties +listed by the Property parameter. Other properties of the class are present but they are not +populated. + +```yaml +Type: String[] +Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, ClassNameSessionSet, ResourceUriComputerSet +Aliases: SelectProperties + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Query + +Specifies a query to run on the CIM server. If the value specified contains double quotes `"`, +single quotes `'`, or a backslash `\`, you must escape those characters by prefixing them with the +backslash character. If the value specified uses the WQL **LIKE** operator, then you must escape +the following characters by enclosing them in square brackets `[]`: percent `%`, underscore `_`, +or opening square bracket `[`. + +You cannot use a metadata query to retrieve a list of classes or an event query. +To retrieve a list of classes, use the `Get-CimClass` cmdlet. +To retrieve an event query, use the `Register-CimIndicationEvent` cmdlet. + +You can specify the query dialect using the QueryDialect parameter. + +```yaml +Type: String +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -QueryDialect + +Specifies the query language used for the Query parameter. The acceptable values for this parameter +are: **WQL** or **CQL**. The default value is **WQL**. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, QuerySessionSet, ClassNameSessionSet, QueryComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ResourceUri + +Specifies the resource uniform resource identifier (URI) of the resource class or instance. The URI +is used to identify a specific type of resource, such as disks or processes, on a computer. + +A URI consists of a prefix and a path to a resource. For example: + +- `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` +- `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings` + +By default, if you do not specify this parameter, the DMTF standard resource URI +`http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. + +**ResourceURI** can only be used with CIM sessions created using the WSMan protocol, or when +specifying the **ComputerName** parameter, which creates a CIM session using WSMan. If you specify +this parameter without specifying the **ComputerName** parameter, or if you specify a CIM session +created using DCOM protocol, you will get an error, because the DCOM protocol does not support the +**ResourceURI** parameter. + +If both the **ResourceUri** parameter and the **Filter** parameter are specified, the **Filter** +parameter is ignored. + +```yaml +Type: Uri +Parameter Sets: ResourceUriSessionSet, ResourceUriComputerSet, QuerySessionSet, QueryComputerSet, CimInstanceSessionSet, CimInstanceComputerSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Shallow + +Indicates that the instances of a class are returned without including the instances of any child +classes. By default, the cmdlet returns the instances of a class and its child classes. + +```yaml +Type: SwitchParameter +Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, QuerySessionSet, ClassNameSessionSet, ResourceUriComputerSet, QueryComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### CIM Instance + +This cmdlet accepts an input objects specified with the InputObject parameter. + +## OUTPUTS + +### CIM Instance + +This cmdlet returns one or more CIM instance objects representing a snapshot of the CIM instances +on the CIM server. + +## NOTES + +## RELATED LINKS + +[Format-Table](../microsoft.powershell.utility/format-table.md) + +[Get-CimAssociatedInstance](Get-CimAssociatedInstance.md) + +[Get-CimClass](Get-CimClass.md) + +[Invoke-CimMethod](invoke-cimmethod.md) + +[New-CimInstance](New-CimInstance.md) + +[Register-CimIndicationEvent](Register-CimIndicationEvent.md) + +[Remove-CimInstance](remove-ciminstance.md) + +[Set-CimInstance](Set-CimInstance.md) diff --git a/reference/7/CimCmdlets/Get-CimSession.md b/reference/7/CimCmdlets/Get-CimSession.md new file mode 100644 index 000000000000..b5fc672cfc21 --- /dev/null +++ b/reference/7/CimCmdlets/Get-CimSession.md @@ -0,0 +1,247 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- + +# Get-CimSession + +## SYNOPSIS + +Gets the CIM session objects from the current session. + +## SYNTAX + +### ComputerNameSet (Default) +``` +Get-CimSession [[-ComputerName] ] [] +``` + +### SessionIdSet +``` +Get-CimSession [-Id] [] +``` + +### InstanceIdSet +``` +Get-CimSession -InstanceId [] +``` + +### NameSet +``` +Get-CimSession -Name [] +``` + +## DESCRIPTION + +The Get-CimSession cmdlet gets the CIM session objects created in the current PowerShell session. + +If used without any parameters, the cmdlet gets all of the CIM sessions created in the current PowerShell session. +You can use the parameters of `Get-CimSession` to get the sessions that are for particular computers, or you can identify sessions by their names, IDs, or instance IDs. + +For more information about PowerShell sessions, see [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md). + +## EXAMPLES + +### Example 1: Get CIM sessions from the current PowerShell session + +By default, `Get-CimSession` only gets information about the CIM sessions that exist in the current PowerShell session. +Get-CimSession does not get CIM sessions that were created in other PowerShell sessions or that were created on other computers. + +```powershell +New-CimSession -ComputerName Server01,Server02 + +Get-CimSession +``` + +```Output +Id : 1 +Name : CimSession1 +InstanceId : d1413bc3-162a-4cb8-9aec-4d2c61253d59 +ComputerName : Server01 +Protocol : WSMAN + +Id : 2 +Name : CimSession2 +InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710 +ComputerName : Server02 +Protocol : WSMAN +``` + +This command first creates CIM sessions by using [`New-CimSession`](New-CimSession.md), and then gets the CIM sessions by using `Get-CimSession`. + +### Example 2: Get the CIM sessions to a specific computer + +```powershell +Get-CimSession -ComputerName Server02 +``` + +```Output +Id : 2 +Name : CimSession2 +InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710 +ComputerName : Server02 +Protocol : WSMAN +``` + +This command gets the CIM sessions that are connected to the computer named Server02. + +### Example 3: Get a list of CIM sessions and then format the list + +```powershell +Get-CimSession | Format-Table -Property ComputerName,InstanceId +``` + +```Output +ComputerName InstanceId +------------ ---------- +Server01 d1413bc3-162a-4cb8-9aec-4d2c61253d59 +Server02 c0095981-52c5-4e7f-a5bb-c4c680541710 +``` + +This command gets all of the CIM sessions in the current PowerShell session, and then formats the list in a table containing only the **ComputerName** and **InstanceID** properties. + +### Example 4: Get all the CIM sessions that have specific names + +```powershell +Get-CimSession -ComputerName Serv* +``` + +```Output +Id : 1 +Name : CimSession1 +InstanceId : d1413bc-162a-4cb8-9aec-4d2c61253d59 +ComputerName : Server01 +Protocol : WSMAN + +Id : 2 +Name : CimSession2 +InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710 +ComputerName : Server02 +Protocol : WSMAN +``` + +This command gets all of the CIM sessions that have names that begin with the characters serv. + +### Example 5: Get a specific CIM session + +```powershell +Get-CimSession -ID 2 +``` + +```Output +Id : 2 +Name : CimSession2 +InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710 +ComputerName : Server02 +Protocol : WSMAN +``` + +This command gets the CIM session that has an ID of 2. + +## PARAMETERS + +### -ComputerName + +Specifies an array of names of computers. +Gets the CIM sessions that connect to the specified computers. + +You can specify a fully qualified domain name (FQDN) or a NetBIOS name. + +```yaml +Type: String[] +Parameter Sets: ComputerNameSet +Aliases: CN, ServerName + +Required: False +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Id + +Specifies the identifier (ID) of the CIM session to get. +For one or more IDs, use commas to separate the IDs, or use the range operator (..) to specify a range of IDs. + +An ID is an integer that uniquely identifies the CIM session in the current PowerShell session. +It is easier to remember and type than InstanceId, but it is unique only within the current PowerShell session. + +For more information about the range operator, see [about_Operators](../Microsoft.PowerShell.Core/About/about_Operators.md). + +```yaml +Type: UInt32[] +Parameter Sets: SessionIdSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -InstanceId + +Specifies the instance IDs of the CIM session to get. + +InstanceId is a GUID that uniquely identifies a CIM session. +The InstanceId is unique, even when you have multiple sessions running in PowerShell. + +The InstanceId is stored in the InstanceId property of the object that represents a CIM session. + +```yaml +Type: Guid[] +Parameter Sets: InstanceIdSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Name + +Gets one or more CIM sessions which contain the specified friendly names. +Wildcard characters are permitted. + +```yaml +Type: String[] +Parameter Sets: NameSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +## OUTPUTS + +### Microsoft.Management.Infrastructure.CimSession + +## NOTES + +## RELATED LINKS + +[Format-Table](../microsoft.powershell.utility/format-table.md) + +[New-CimSession](New-CimSession.md) + +[Remove-CimSession](remove-cimsession.md) + +[about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/Import-BinaryMiLog.md b/reference/7/CimCmdlets/Import-BinaryMiLog.md new file mode 100644 index 000000000000..5ff78efd29a1 --- /dev/null +++ b/reference/7/CimCmdlets/Import-BinaryMiLog.md @@ -0,0 +1,65 @@ +--- +ms.date: 02/20/2019 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +online version: http://go.microsoft.com/fwlink/?LinkId=301309 +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +--- + +# Import-BinaryMiLog + +## SYNOPSIS +Used to re-create the saved objects based on the contents of an export file. + +## SYNTAX + +``` +Import-BinaryMiLog [-Path] +``` + +## DESCRIPTION + +Use this cmdlet to re-create saved objects based on the contents of an export file created by +`Export-BinaryMILog`. This cmdlet is similar to `Import-Clixml`, except that `Export-BinaryMILog` +stores the resulting object in a binary encoded file. + +## EXAMPLES + +### Example 1 - Restore objects exported to a file + +```powershell +Import-BinaryMiLog -Path "Processes.bmil" +``` + +## PARAMETERS + +### -Path + +Specifies the path of the file in which to store the binary representation of the object. The +**Path** parameter supports wild cards and relative paths. This cmdlet generates an error if the +path resolves to more than one file. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: True +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object + +## NOTES + +## RELATED LINKS diff --git a/reference/7/CimCmdlets/Invoke-CimMethod.md b/reference/7/CimCmdlets/Invoke-CimMethod.md new file mode 100644 index 000000000000..6ce5377a0e32 --- /dev/null +++ b/reference/7/CimCmdlets/Invoke-CimMethod.md @@ -0,0 +1,486 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- + +# Invoke-CimMethod + +## SYNOPSIS +Invokes a method of a CIM class. + +## SYNTAX + +### ClassNameComputerSet (Default) +``` +Invoke-CimMethod [-ClassName] [-ComputerName ] [[-Arguments] ] + [-MethodName] [-Namespace ] [-OperationTimeoutSec ] [-WhatIf] [-Confirm] + [] +``` + +### ClassNameSessionSet +``` +Invoke-CimMethod [-ClassName] -CimSession [[-Arguments] ] + [-MethodName] [-Namespace ] [-OperationTimeoutSec ] [-WhatIf] [-Confirm] + [] +``` + +### ResourceUriSessionSet +``` +Invoke-CimMethod -ResourceUri -CimSession [[-Arguments] ] + [-MethodName] [-Namespace ] [-OperationTimeoutSec ] [-WhatIf] [-Confirm] + [] +``` + +### ResourceUriComputerSet +``` +Invoke-CimMethod -ResourceUri [-ComputerName ] [[-Arguments] ] + [-MethodName] [-Namespace ] [-OperationTimeoutSec ] [-WhatIf] [-Confirm] + [] +``` + +### CimInstanceComputerSet +``` +Invoke-CimMethod [-ResourceUri ] [-InputObject] [-ComputerName ] + [[-Arguments] ] [-MethodName] [-OperationTimeoutSec ] [-WhatIf] [-Confirm] + [] +``` + +### CimInstanceSessionSet +``` +Invoke-CimMethod [-ResourceUri ] [-InputObject] -CimSession + [[-Arguments] ] [-MethodName] [-OperationTimeoutSec ] [-WhatIf] [-Confirm] + [] +``` + +### CimClassSessionSet +``` +Invoke-CimMethod -ResourceUri -CimSession [[-Arguments] ] + [-MethodName] [-Namespace ] [-OperationTimeoutSec ] [-WhatIf] [-Confirm] + [] +``` + +### CimClassComputerSet +``` +Invoke-CimMethod [-CimClass] [-ComputerName ] [[-Arguments] ] + [-MethodName] [-OperationTimeoutSec ] [-WhatIf] [-Confirm] [] +``` + +### QuerySessionSet +``` +Invoke-CimMethod -Query [-QueryDialect ] -CimSession + [[-Arguments] ] [-MethodName] [-Namespace ] [-OperationTimeoutSec ] + [-WhatIf] [-Confirm] [] +``` + +### QueryComputerSet +``` +Invoke-CimMethod -Query [-QueryDialect ] [-ComputerName ] + [[-Arguments] ] [-MethodName] [-Namespace ] [-OperationTimeoutSec ] + [-WhatIf] [-Confirm] [] +``` + +### QuerySessionSet +``` +Invoke-CimMethod -Query [-QueryDialect ] -CimSession + [[-Arguments] ] [-MethodName] [-Namespace ] [-OperationTimeoutSec ] + [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION + +The Invoke-CimMethod cmdlet invokes a method of a CIM class or CIM instance using the name-value +pairs specified by the Arguments parameter. + +If the InputObject parameter is not specified, the cmdlet works in one of the following ways: + +- If neither the ComputerName parameter nor the CimSession parameter is specified, then this cmdlet + works on local Windows Management Instrumentation (WMI) using a Component Object Model (COM) + session. +- If either the ComputerName parameter or the CimSession parameter is specified, then this cmdlet + works against the CIM server specified by either the ComputerName parameter or the CimSession + parameter. + +If the InputObject parameter is specified, the cmdlet works in one of the following ways: + +- If neither the ComputerName parameter nor the CimSession parameter is specified, then this cmdlet + uses the CIM session or computer name from the input object. +- If the either the ComputerName parameter or the CimSession parameter is specified, then this + cmdlet uses the either the CimSession parameter value or ComputerName parameter value. Note: This + is not very common. + +## EXAMPLES + +### Example 1: Invoke a method + +```powershell +PS C:\>Invoke-CimMethod -Query 'select * from Win32_Process where name like "notepad%"' -MethodName "Terminate" +``` + +This command invokes the method named Terminate on the CIM class named Win32_Process. The CIM class +is retrieved by the query "Select * from Win32_Process where name like 'notepad%'". + +### Example 2: Invoke a method using CIM instance object + +```powershell +PS C:\>$x = Get-CimInstance -Query 'Select * from Win32_Process where name like "notepad%"' +PS C:\>Invoke-CimMethod -InputObject $x -MethodName GetOwner +``` + +This set of commands retrieves the CIM instance object and stores it in a variable named $x using +the Get-CimInstance cmdlet. The contents of the variable are then used as the InputObject for the +Invoke-CimMethod cmdlet, and the GetOwner method is invoked for the CimInstance. + +### Example 3: Invoke a static method + +```powershell +PS C:\>Invoke-CimMethod -ClassName Win32_Process -MethodName "Create" -Arguments @{ Path = "notepad.exe" } +``` + +This command invokes the static method Create on the class named Win32_Process, with the arguments specified by the Arguments parameter. + +### Example 4: Invoke a method using arguments + +```powershell +PS C:\>Invoke-CimMethod -ClassName Win32_Process -MethodName "Create" -Arguments @{ CommandLine = 'notepad.exe'; CurrentDirectory = "C:\windows\system32" } +``` + +This command invokes the method named Create by using the Arguments parameter. + +### Example 5: Client-side validation + +```powershell +PS C:\>$c = Get-CimClass -ClassName Win32_Process +PS C:\>Invoke-CimMethod -CimClass $c -MethodName "xyz" -Arguments @{ CommandLine = 'notepad.exe' } +``` + +This set of commands performs client-side validation for the method named xyz by passing a CimClass +object to the Invoke-CimMethod cmdlet. + +## PARAMETERS + +### -Arguments + +Specifies the parameters to pass to the called method. Specify the values for this parameter as +name-value pairs, stored in a hash table. The order of the values entered is not important. + +```yaml +Type: IDictionary +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -CimClass + +Specifies a CIM class object that represents a CIM class definition on the server. Use this +parameter when invoking a static method of a class. + +You can use the Get-CimClass cmdlet to retrieve a class definition from the server. + +Using this parameter results in better client side schema validations. + +```yaml +Type: CimClass +Parameter Sets: CimClassSessionSet, CimClassComputerSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -CimSession + +Runs the command using the specified CIM session. Enter a variable that contains the CIM session, +or a command that creates or gets the CIM session, such as the New-CimSession or Get-CimSession +cmdlets. For more information, see about_CimSessions. + +```yaml +Type: CimSession[] +Parameter Sets: ClassNameSessionSet, CimInstanceSessionSet, CimClassSessionSet, QuerySessionSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ClassName + +Specifies the name of the CIM class for which to perform the operation. This parameter is only used +for static methods. NOTE: You can use tab completion to browse the list of classes, because Windows +PowerShell gets a list of classes from the local WMI server to provide a list of class names. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, ClassNameSessionSet +Aliases: Class + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ComputerName + +Specifies the name of the computer on which you want to run the CIM operation. +You can specify a fully qualified domain name (FQDN), a NetBIOS name, or an IP address. + +If you specify this parameter, the cmdlet creates a temporary session to the specified computer +using the WsMan protocol. + +If you do not specify this parameter, the cmdlet performs the operation on the local computer using +Component Object Model (COM). + +If multiple operations are being performed on the same computer, connecting using a CIM session +gives better performance. + +```yaml +Type: String[] +Parameter Sets: ClassNameComputerSet, ResourceUriComputerSet, CimClassComputerSet, QueryComputerSet +Aliases: CN, ServerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -InputObject + +Specifies a CIM instance object to use as input to invoke a method. + +This parameter can only be used to invoke instance methods. +To invoke class static methods, use the Class parameter or the CimClass parameter. + +```yaml +Type: CimInstance +Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet +Aliases: CimInstance + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -MethodName + +Specifies the name of the CIM method to invoke. +This parameter is mandatory and cannot be null or empty. + +To invoke static method of a CIM class use the ClassName or the CimClass parameter. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Name + +Required: True +Position: 2 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Namespace + +Specifies the namespace for the CIM operation. + +The default namespace is root/cimv2. You can use tab completion to browse the list of namespaces, +because PowerShell gets a list of namespaces from the local WMI server to provide the list +of namespaces. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, ClassNameSessionSet, ResourceUriSessionSet, ResourceUriComputerSet, QuerySessionSet, QueryComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -OperationTimeoutSec + +Specifies the amount of time that the cmdlet waits for a response from the computer. + +By default, the value is 0, which means that the cmdlet uses the default timeout value for the +server.. + +If the OperationTimeoutSec parameter is set to a value less than the robust connection retry +timeout of 3 minutes, network failures that last more than the value of the OperationTimeoutSec +parameter are not recoverable, because the operation on the server times out before the client can +reconnect. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: OT + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Query + +Specifies a query to run on the CIM server. +A method is invoked on the instances received as a result of the query. + +You can specify the query dialect using the QueryDialect parameter. + +If the value specified contains double quotes ("), single quotes ('), or a backslash (\\), you must +escape those characters by prefixing them with the backslash (\\) character. If the value specified +uses the WQL LIKE operator, then you must escape the following characters by enclosing them in +square brackets (\[\]): percent (%), underscore (_), or opening square bracket (\[). + +```yaml +Type: String +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -QueryDialect + +Specifies the query language used for the Query parameter. +The acceptable values for this parameter are: WQL or CQL. + +The default value is WQL. + +```yaml +Type: String +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ResourceUri + +Specifies the resource uniform resource identifier (URI) of the resource class or instance. +The URI is used to identify a specific type of resource, such as disks or processes, on a computer. + +A URI consists of a prefix and a path to a resource. +For example: + +``` +http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk +http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings +``` + +By default, if you do not specify this parameter, the DMTF standard resource URI `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. + +ResourceURI can only be used with CIM sessions created using the WSMan protocol, or when specifying the ComputerName parameter, which creates a CIM session using WSMan. +If you specify this parameter without specifying the ComputerName parameter, or if you specify a CIM session created using DCOM protocol, you will get an error, because the DCOM protocol does not support the ResourceURI parameter. + +If both the ResourceUri parameter and the Filter parameter are specified, the Filter parameter is ignored. + +```yaml +Type: Uri +Parameter Sets: ResourceUriSessionSet, ResourceUriComputerSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf + +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### CIM class + +This cmdlet accepts a CIM class as an input object. + +### CIM instance + +This cmdlet accepts a CIM instance as an input object. + +## OUTPUTS + +### System.Management.Automation.PSCustomObject + +This cmdlet returns an object. + +## NOTES + +## RELATED LINKS + +[Get-CimClass](get-cimclass.md) + +[Get-CimInstance](get-ciminstance.md) + +[Get-CimSession](Get-CimSession.md) + +[New-CimSession](New-CimSession.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/New-CimInstance.md b/reference/7/CimCmdlets/New-CimInstance.md new file mode 100644 index 000000000000..1d63157ee13e --- /dev/null +++ b/reference/7/CimCmdlets/New-CimInstance.md @@ -0,0 +1,368 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- + +# New-CimInstance + +## SYNOPSIS +Creates a CIM instance. + +## SYNTAX + +### ClassNameComputerSet (Default) +``` +New-CimInstance [-ClassName] [-Key ] [[-Property] ] [-Namespace ] + [-OperationTimeoutSec ] [-ComputerName ] [-ClientOnly] [-WhatIf] [-Confirm] + [] +``` + +### ClassNameSessionSet +``` +New-CimInstance [-ClassName] [-Key ] [[-Property] ] [-Namespace ] + [-OperationTimeoutSec ] -CimSession [-ClientOnly] [-WhatIf] [-Confirm] + [] +``` + +### ResourceUriSessionSet +``` +New-CimInstance -ResourceUri [-Key ] [[-Property] ] [-Namespace ] + [-OperationTimeoutSec ] -CimSession [-WhatIf] [-Confirm] [] +``` + +### ResourceUriComputerSet +``` +New-CimInstance -ResourceUri [-Key ] [[-Property] ] [-Namespace ] + [-OperationTimeoutSec ] [-ComputerName ] [-WhatIf] [-Confirm] [] +``` + +### CimClassSessionSet +``` +New-CimInstance [-CimClass] [[-Property] ] [-OperationTimeoutSec ] + -CimSession [-ClientOnly] [-WhatIf] [-Confirm] [] +``` + +### CimClassComputerSet +``` +New-CimInstance [-CimClass] [[-Property] ] [-OperationTimeoutSec ] + [-ComputerName ] [-ClientOnly] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +The New-CimInstance cmdlet creates an instance of a CIM class based on the class definition on either the local computer or a remote computer. + +Use the Property parameter to set the initial values of the selected properties. + +By default, the New-CimInstance cmdlet creates an instance on the local computer. + +## EXAMPLES + +### Example 1: Create an instance of a CIM class +``` +PS C:\>New-CimInstance -ClassName Win32_Environment -Property @{Name="testvar";VariableValue="testvalue";UserName="domain\user"} +``` + +This command creates an instance of a CIM Class named win32_environment in the root/cimv2 namespace on the computer. + +No client side validation is performed if the class does not exist, the properties are wrong, or if the server rejects the call. + +If the instance is created successfully, then the New-CimInstance cmdlet outputs the newly created instance. + +### Example 2: Create an instance of a CIM class using a class schema +``` +PS C:\>$class = Get-CimClass -ClassName Win32_Environment + + + +PS C:\>New-CimInstance -CimClass $class -Property @{Name="testvar";VariableValue="testvalue";UserName="Contoso\User1"} +``` + +This set of commands retrieves a CIM class object and stores it in a variable named $class using the Get-CimClass cmdlet. +The contents of the variable are then passed to the New-CimInstance cmdlet. + +### Example 3: Create a dynamic instance on the client +``` +PS C:\>$a = New-CimInstance -ClassName Win32_Process -Property @{Handle=0} -Key Handle -ClientOnly + + +PS C:\>Get-CimInstance -CimInstance $a + + +PS C:\>Invoke-CimMethod -CimInstance $a -MethodName GetOwner +``` + +This set of commands creates a dynamic instance of a CIM class named win32_Process on the client computer without getting the instance from the server. +This set of commands retrieves the dynamic instance and stores it in a variable named $a and passes the contents of the variable to the Get-CimInstance cmdlet. +The Get-CimInstance cmdlet then retrieves a particular single instance, and invokes the GetOwner method using the Invoke-CimMethod cmdlet. + +This dynamic instance can be used to perform operations if the instance with this key exists on the server. + +### Example 4: Create an instance for a CIM class of a specific namespace +``` +PS C:\>$class = Get-CimClass -ClassName MSFT_Something -Namespace root/somewhere + + + +PS C:\>New-CimInstance -CimClass $class -Property @{"Prop1"=1;"Prop2"="value"} -ClientOnly +``` + +This set of commands gets an instance of a CIM class named MSFT_Something in the namespace root/somewhere and stores it in a variable named $class using the Get-CimClass cmdlet. +The contents of the variable are then passed to the New-CimInstance cmdlet to create a new CIM instance and perform client side validations on the new instance. + +If you want to validate the instance, for example, to make sure Prop1 and Prop2 actually exist and that the keys are marked correctly, use the CimClass parameter instead of the ClassName parameter. + +You cannot use the ComputerName or CimSession parameter with the ClientOnly parameter. + +## PARAMETERS + +### -CimClass +Specifies a CIM class object that represents the type of the instance. + +You can use the Get-CimClass cmdlet to retrieve the class declaration from a computer. + +Using this parameter results in better client side schema validations. + +```yaml +Type: CimClass +Parameter Sets: CimClassSessionSet, CimClassComputerSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -CimSession +Runs the command using the specified CIM session. +Enter a variable that contains the CIM session, or a command that creates or gets the CIM session, such as the New-CimSession or Get-CimSession cmdlets. +For more information, see about_CimSessions. + +```yaml +Type: CimSession[] +Parameter Sets: ClassNameSessionSet, ResourceUriSessionSet, CimClassSessionSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ClassName +Specifies the name of the CIM class of which the operation creates an instance. +NOTE: You can use tab completion to browse the list of classes, because PowerShell gets a list of classes from the local WMI server to provide a list of class names. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, ClassNameSessionSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ClientOnly +Indicates that the instance is only created in PowerShell without going to the CIM server. +You can use this parameter to create an in-memory CIM instance for use in subsequent PowerShell operations. + +```yaml +Type: SwitchParameter +Parameter Sets: ClassNameComputerSet, ClassNameSessionSet, CimClassSessionSet, CimClassComputerSet +Aliases: Local + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ComputerName +Specifies the name of the computer on which you want to run the CIM operation. +You can specify a fully qualified domain name (FQDN), a NetBIOS name, or an IP address. + +If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the Ws-Man protocol. + +If you do not specify this parameter, the cmdlet performs the operation on the local computer using Component Object Model (COM). + +If multiple operations are being performed on the same computer, connecting using a CIM session gives better performance. + +```yaml +Type: String[] +Parameter Sets: ClassNameComputerSet, ResourceUriComputerSet, CimClassComputerSet +Aliases: CN, ServerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Key +Specifies the properties that are used as keys. +CimSession and ComputerName cannot be used when Key is specified. + +```yaml +Type: String[] +Parameter Sets: ClassNameComputerSet, ClassNameSessionSet, ResourceUriSessionSet, ResourceUriComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Namespace +Specifies the namespace of the class for the new instance. + +The default namespace is root/cimv2. +NOTE: You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, ClassNameSessionSet, ResourceUriSessionSet, ResourceUriComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -OperationTimeoutSec +Specifies the amount of time that the cmdlet waits for a response from the CIM server. + +By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. + +If the OperationTimeoutSec parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the OperationTimeoutSec parameter are not recoverable, because the operation on the server times out before the client can reconnect. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: OT + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Property +Specifies the properties of the CIM instance using a hash table (name-value pairs). + +If you specify the CimClass parameter, then the New-CimInstance cmdlet performs a property validation on the client to make sure that the properties specified are consistent with the class declaration on the server. +If the CimClass parameter is not specified, then the property validation is done on the server. + +```yaml +Type: IDictionary +Parameter Sets: (All) +Aliases: Arguments + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ResourceUri +Specifies the resource uniform resource identifier (URI) of the resource class or instance. +The URI is used to identify a specific type of resource, such as disks or processes, on a computer. + +A URI consists of a prefix and a path to a resource. +For example: + +http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk +http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings + + + +By default, if you do not specify this parameter, the DMTF standard resource URI http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/ is used and the class name is appended to it. + +ResourceURI can only be used with CIM sessions created using the WSMan protocol, or when specifying the ComputerName parameter, which creates a CIM session using WSMan. +If you specify this parameter without specifying the ComputerName parameter, or if you specify a CIM session created using DCOM protocol, you will get an error, because the DCOM protocol does not support the ResourceURI parameter. + +If both the ResourceUri parameter and the Filter parameter are specified, the Filter parameter is ignored. + +```yaml +Type: Uri +Parameter Sets: ResourceUriSessionSet, ResourceUriComputerSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None +This cmdlet accepts no input objects. + +## OUTPUTS + +### System.Object +This cmdlet returns an object that contains the CIM instance information. + +## NOTES + +## RELATED LINKS + +[Get-CimClass](get-cimclass.md) + +[Get-CimInstance](get-ciminstance.md) + +[Remove-CimInstance](remove-ciminstance.md) + +[Set-CimInstance](Set-CimInstance.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/New-CimSession.md b/reference/7/CimCmdlets/New-CimSession.md new file mode 100644 index 000000000000..476be202bae7 --- /dev/null +++ b/reference/7/CimCmdlets/New-CimSession.md @@ -0,0 +1,356 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- +# New-CimSession + +## SYNOPSIS + +Creates a CIM session. + +## SYNTAX + +### CredentialParameterSet (Default) + +``` +New-CimSession [-Authentication ] [[-Credential] ] + [[-ComputerName] ] [-Name ] [-OperationTimeoutSec ] [-SkipTestConnection] + [-Port ] [-SessionOption ] [] +``` + +### CertificateParameterSet + +``` +New-CimSession [-CertificateThumbprint ] [[-ComputerName] ] [-Name ] + [-OperationTimeoutSec ] [-SkipTestConnection] [-Port ] [-SessionOption ] + [] +``` + +## DESCRIPTION + +The `New-CimSession` cmdlet creates a CIM session. +A CIM session is a client-side object representing a connection to a local computer or a remote computer. +The CIM session contains information about the connection, such as ComputerName, the protocol used for the connection, session ID and instance ID. + +This cmdlet returns a CIM session object that can be used by all other CIM cmdlets. + +## EXAMPLES + +### Example 1: Create a CIM session with default options + +```powershell +New-CimSession +``` + +This command creates a local CIM session with default options. +If **ComputerName** is not specified, `New-CimSession` creates a DCOM session to the local computer. + +### Example 2: Create a CIM session to a specific computer + +```powershell +New-CimSession -ComputerName Server01 +``` + +This command creates a CIM session to the computer specified by **ComputerName**. +By default, `New-CimSession` creates a WsMan session when **ComputerName** is specified. + +### Example 3: Create a CIM session to multiple computers + +```powershell +New-CimSession -ComputerName Server01,Server02,Server03 +``` + +This command creates a CIM session to each of the computers specified by **ComputerName**, in the comma separated list. + +### Example 4: Create a CIM session with a friendly name + +You can use the friendly name of a CIM session to easily refer to the session in other CIM cmdlets, for example, [Get-CimSession](Get-CimSession.md). + +```powershell +New-CimSession -ComputerName Server01,Server02 -Name FileServers + +Get-CimSession -Name File* +``` + +This command creates a remote CIM session to each of the computers specified by **ComputerName**, in the comma separated list, and assigns a friendly name to the new sessions, by specifying **Name**. + +### Example 5: Create a CIM session to a computer using a PSCredential object + +```powershell +New-CimSession -ComputerName Server01 -Credential $cred -Authentication Negotiate +``` + +This command creates a CIM session to the computer specified by **ComputerName**, using the PSCredential object specified by **Credential**, and the authentication type specified by **Authentication**. + +You can create a PSCredential object by using the [`Get-Credential`](../Microsoft.PowerShell.Security/Get-Credential.md) cmdlet. + +### Example 6: Create a CIM session to a computer using a specific port + +```powershell +New-CimSession -ComputerName Server01 -Port 1234 +``` + +This command creates a CIM session to the computer specified by ComputerName using the TCP port specified by **Port**. + +### Example 7: Create a CIM session using DCOM + +```powershell +$SessionOption = New-CimSessionOption -Protocol DCOM + +New-CimSession -ComputerName Server1 -SessionOption $SessionOption +``` + +This command creates a CIM session by using the Distributed COM (DCOM) protocol instead of WSMan. + +## PARAMETERS + +### -Authentication + +Specifies the authentication type used for the user's credentials. +The acceptable values for this parameter are: + +- Default +- Digest +- Negotiate +- Basic +- Kerberos +- NtlmDomain +- CredSsp + +You cannot use the NtlmDomain authentication type for connection to the local computer. +CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of Windows. + +Caution: Credential Security Service Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. +This mechanism increases the security risk of the remote operation. +If the remote computer is compromised, the credentials that are passed to it can be used to control the network session. + +```yaml +Type: PasswordAuthenticationMechanism +Parameter Sets: CredentialParameterSet +Aliases: +Accepted values: Default, Digest, Negotiate, Basic, Kerberos, NtlmDomain, CredSsp + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -CertificateThumbprint + +Specifies the digital public key certificate (X.509) of a user account that has permission to perform this action. +Enter the certificate thumbprint of the certificate. + +Certificates are used in client certificate-based authentication. +They can be mapped only to local user accounts; they do not work with domain accounts. + +To get a certificate thumbprint, use the [`Get-Item`](../Microsoft.Powershell.Management/Get-Item.md) or [`Get-ChildItem`](../Microsoft.Powershell.Management/Get-ChildItem.md) cmdlets in the PowerShell Certificate Provider. +For more information about using the PowerShell Certificate provider, type `Get-Help Certificate`, or see [Certificate Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). + +```yaml +Type: String +Parameter Sets: CertificateParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ComputerName + +Specifies the name of the computer to which to create the CIM session. +Specify either a single computer name, or multiple computer names separated by a comma. + +If **ComputerName** is not specified, a CIM session to the local computer is created. + +You can specify the value for computer name in one of the following formats: + +- One or more NetBIOS names +- One or more IP addresses +- One or more fully qualified domain names. + +If the computer is in a different domain than the user, you must specify the fully qualified domain name. + +You can also pass a computer name (in quotes) to `New-CimSession` by using the pipeline. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: CN, ServerName + +Required: False +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Credential + +Specifies a user account that has permission to perform this action. +If **Credential** is not specified, the current user account is used. + +Specify the value for **Credential** by using one of the following formats: + +- A user name: "User01" +- A domain name and a user name: "Domain01\User01" +- A user principal name: "User@Domain.com" +- A PSCredential object, such as one returned by the [`Get-Credential`](../Microsoft.PowerShell.Security/Get-Credential.md) cmdlet. + +When you type a user name, you are prompted for a password. + +```yaml +Type: PSCredential +Parameter Sets: CredentialParameterSet +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name + +Specifies a friendly name for the CIM session. + +You can use the name to refer to the CIM session when using other cmdlets, such as the [`Get-CimSession`](Get-CimSession.md) cmdlet. +The name is not required to be unique to the computer or the current session. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -OperationTimeoutSec + +Duration for which the cmdlet waits for a response from the server. + +By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. + +If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter are not recoverable, because the operation on the server times out before the client can reconnect. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: OT + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Port + +Specifies the network port on the remote computer that is used for this connection. +To connect to a remote computer, the remote computer must be listening on the port that the connection uses. +The default ports are 5985 (the WinRM port for HTTP) and 5986 (the WinRM port for HTTPS). + +Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. +Use the following commands to configure the listener: + +`winrm delete winrm/config/listener?Address=*+Transport=HTTP` + +`winrm create winrm/config/listener?Address=*+Transport=HTTP @{Port="\"}` + +Do not use the **Port** parameter unless you must. +The port setting in the command applies to all computers or sessions on which the command runs. +An alternate port setting might prevent the command from running on all computers. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -SessionOption + +Sets advanced options for the new CIM session. +Enter the name of a CimSessionOption object created by using the [`New-CimSessionOption`](New-CimSessionOption.md) cmdlet. + +```yaml +Type: CimSessionOptions +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -SkipTestConnection + +By default, the `New-CimSession` cmdlet establishes a connection with a remote WS-Management endpoint for two reasons: to verify that the remote server is listening on the port number that is specified by using the **Port** parameter, and to verify the specified account credentials. +The verification is accomplished by using a standard WS-Identity operation. +You can add the **SkipTestConnection** switch parameter if the remote WS-Management endpoint cannot use WS-Identify, or if you want to reduce some data transmission time. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. +For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). + +## INPUTS + +### None + +This cmdlet accepts no inputs. + +## OUTPUTS + +### Microsoft.Management.Infrastructure.CimSession + +## NOTES + +## RELATED LINKS + +[Get-ChildItem](../Microsoft.Powershell.Management/Get-ChildItem.md) + +[Get-Credential](../Microsoft.PowerShell.Security/Get-Credential.md) + +[Get-Item](../Microsoft.Powershell.Management/Get-Item.md) + +[Get-CimSession](Get-CimSession.md) + +[Remove-CimSession](Remove-CimSession.md) + +[New-CimSessionOption](New-CimSessionOption.md) + +[about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/New-CimSessionOption.md b/reference/7/CimCmdlets/New-CimSessionOption.md new file mode 100644 index 000000000000..201d47187142 --- /dev/null +++ b/reference/7/CimCmdlets/New-CimSessionOption.md @@ -0,0 +1,468 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- + +# New-CimSessionOption + +## SYNOPSIS +Specifies advanced options for the New-CimSession cmdlet. + +## SYNTAX + +### ProtocolTypeSet (Default) +``` +New-CimSessionOption [-Protocol] [-UICulture ] [-Culture ] + [] +``` + +### WSManParameterSet +``` +New-CimSessionOption [-NoEncryption] [-SkipCACheck] [-SkipCNCheck] [-SkipRevocationCheck] + [-EncodePortInServicePrincipalName] [-Encoding ] [-HttpPrefix ] + [-MaxEnvelopeSizeKB ] [-ProxyAuthentication ] + [-ProxyCertificateThumbprint ] [-ProxyCredential ] [-ProxyType ] [-UseSsl] + [-UICulture ] [-Culture ] [] +``` + +### DcomParameterSet +``` +New-CimSessionOption [-Impersonation ] [-PacketIntegrity] [-PacketPrivacy] + [-UICulture ] [-Culture ] [] +``` + +## DESCRIPTION +The New-CimSessionOption cmdlet creates an instance of a CIM session options object. +You use a CIM session options object as input to the New-CimSession cmdlet to specify the options for a CIM session. + +This cmdlet has two parameter sets, one for WsMan options and one for Distributed Component Object Model (DCOM) options. +Depending on which parameters you use, the cmdlet returns either an instance of DCOM session options or returns WsMan session options. + +## EXAMPLES + +### Example 1: Create a CIM session options object for DCOM +``` +PS C:\>$so = New-CimSessionOption -Protocol DCOM + + + +PS C:\>New-CimSession -ComputerName Server01 -SessionOption $so +``` + +This set of commands creates a CIM session options object for the DCOM protocol and stores it in a variable named $so. +The contents of the variable are then passed to the New-CimSession cmdlet. +New-CimSession then creates a new CIM session with the remote server named Server01, using the options defined in the variable. + +### Example 2: Create a CIM session options object for WsMan +``` +PS C:\>New-CimSessionOption -ProxyAuthentication Kerberos -ProxyCredential $cred -SkipCACheck -SkipCNCheck -UseSsl +``` + +This command creates a CIM session options object for the WsMan protocol. +The object contains configuration for the authentication mode of Kerberos specified by the ProxyAuthentication parameter, the credentials specified by the ProxyCredential parameter, and specifies that the command is to skip the CA check, skip the CN check, and use SSL. + +### Example 3: Create a CIM session options object with the culture specified +``` +PS C:\>New-CimSessionOption -Culture Fr-Fr -Protocol Wsman +``` + +This command specifies the culture that is used for the CIM session. +By default, the culture of the client is used when performing operations. +However, the default culture can be overridden using the Culture parameter. + +## PARAMETERS + +### -Culture +Specifies the user interface culture to use for the CIM session. +Specify the value for this parameter using one of the following formats: + +Enter a culture name in \-\ format such as "EN-US". + + + +A variable that contains a CultureInfo object. + + + +A command that gets a CultureInfo object, such as Get-Culture. +For more information about Get-Culture, see http://technet.microsoft.com/library/hh849930.aspx. + +```yaml +Type: CultureInfo +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -EncodePortInServicePrincipalName +Indicates that the Kerberos connection is connecting to a service whose service principal name (SPN) includes the service port number. +This type of connection is not common. + +```yaml +Type: SwitchParameter +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Encoding +Specifies the encoding used for the WsMan protocol. + +The acceptable values for this parameter are: Default, Utf8, or Utf16. + +```yaml +Type: PacketEncoding +Parameter Sets: WSManParameterSet +Aliases: +Accepted values: Default, Utf8, Utf16 + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -HttpPrefix +Specifies the part of the HTTP URL after the computer name and port number. +Changing this is not common. + +By default, the value of this parameter is /wsman. + +```yaml +Type: Uri +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Impersonation +Creates a DCOM session to Windows Management Instrumentation (WMI) using impersonation. + +Valid values for this parameter are: + +- Default: DCOM can choose the impersonation level using its normal security negotiation algorithm. +- None: The client is anonymous to the server. + The server process can impersonate the client, but the impersonation token does not contain any information and cannot be used. +- Identify: Allows objects to query the credentials of the caller. +- Impersonate: Allows objects to use the credentials of the caller. +- Delegate: Allows objects to permit other objects to use the credentials of the caller. + +If Impersonation is not specified, the New-CimSession cmdlet uses the value of 3: Impersonate + +```yaml +Type: ImpersonationType +Parameter Sets: DcomParameterSet +Aliases: +Accepted values: Default, None, Identify, Impersonate, Delegate + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaxEnvelopeSizeKB +Specifies the size limit of WsMan XML messages for either direction. + +```yaml +Type: UInt32 +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -NoEncryption +Specifies that data encryption is turned off. + +```yaml +Type: SwitchParameter +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PacketIntegrity +Specifies that the DCOM session created to WMI uses the Component Object Model (COM) PacketIntegrity functionality. +For enhanced security, by default all CIM sessions created using DCOM have the PacketIntegrity parameter set to True. + +```yaml +Type: SwitchParameter +Parameter Sets: DcomParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PacketPrivacy +Creates a DCOM session to WMI using the COM PacketPrivacy. +For enhanced security, by default all CIM sessions created using DCOM have the PacketPrivacy parameter set to true. + +```yaml +Type: SwitchParameter +Parameter Sets: DcomParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Protocol +Specifies the protocol to use. + +The acceptable values for this parameter are: DCOM or WinRM. + +```yaml +Type: ProtocolType +Parameter Sets: ProtocolTypeSet +Aliases: +Accepted values: Default, Dcom, Wsman + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ProxyAuthentication +Specifies the authentication method to use for proxy resolution. + +The acceptable values for this parameter are: Default, Digest, Negotiate, Basic, Kerberos, NtlmDomain, or CredSsp. + +```yaml +Type: PasswordAuthenticationMechanism +Parameter Sets: WSManParameterSet +Aliases: +Accepted values: Default, Digest, Negotiate, Basic, Kerberos, NtlmDomain, CredSsp + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ProxyCertificateThumbprint +Specifies the (x.509) digital public key certificate of a user account for proxy authentication. +Enter the certificate thumbprint of the certificate. + +Certificates are used in client certificate-based authentication. +They can only be mapped to local user accounts and they do not work with domain accounts. + +To get a certificate thumbprint, use the Get-Item or Get-ChildItem cmdlets in the PowerShell Cert: drive. +For more information about the Get-ChildItem cmdlet for the PowerShell Cert: drive, see http://technet.microsoft.com/library/hh847761.aspx. +For more information about Get-Item, see http://technet.microsoft.com/library/hh849788.aspx + +```yaml +Type: String +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ProxyCredential +Specifies the credentials to use for proxy authentication. +Enter one of the following: + +- A variable that contains a PSCredential object. +- A command that gets a PSCredential object, such as Get-Credential + +If this option is not set, then you cannot specify any credentials. + +```yaml +Type: PSCredential +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProxyType +Specifies the host name resolution mechanism to use. + +The acceptable values for this parameter are: None, WinHttp, Auto, or InternetExplorer. + +By default, the value of this parameter is InternetExplorer. + +```yaml +Type: ProxyType +Parameter Sets: WSManParameterSet +Aliases: +Accepted values: None, WinHttp, Auto, InternetExplorer + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -SkipCACheck +Indicates that when connecting over HTTPS, the client does not validate that the server certificate is signed by a trusted certification authority (CA). + +Use this parameter only when the remote computer is trusted using another mechanism, such as when the remote computer is part of a network that is physically secure and isolated, or when the remote computer is listed as a trusted host in a WinRM configuration. + +```yaml +Type: SwitchParameter +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -SkipCNCheck +Indicates that the certificate common name (CN) of the server does not need to match the hostname of the server. + +Use this parameter only for remote operations that use the HTTPS protocol. + +Note: use this parameter only for trusted computers. + +```yaml +Type: SwitchParameter +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -SkipRevocationCheck +Indicates that the revocation check for server certificates is skipped. + +Note: use this parameter only for trusted computers. + +```yaml +Type: SwitchParameter +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -UICulture +Specifies the user interface culture to use for the CIM session. +Specify the value for this parameter using one of the following formats: + +- Enter a culture name in \-\ format such as "EN-US". +- A variable that contains a CultureInfo object. +- A command that gets a CultureInfo object, such as Get-Culture. + For more information about Get-Culture, see http://technet.microsoft.com/library/hh849930.aspx. + +```yaml +Type: CultureInfo +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -UseSsl +Indicates that SSL should be used to establish a connection to the remote computer. +By default, SSL is not used. + +WsMan encrypts all content that is transmitted over the network. +This parameter lets you specify the additional protection of HTTPS instead of HTTP. +If SSL is not available on the port used for the connection and you specify this parameter, then the command fails. + +It is recommended that you use this parameter only when the PacketPrivacy parameter is not specified. + +```yaml +Type: SwitchParameter +Parameter Sets: WSManParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None +This cmdlet accepts no input objects. + +## OUTPUTS + +### CIMSessionOption +This cmdlet returns an object that contains CIM session options information. + +## NOTES + +## RELATED LINKS + +[Get-ChildItem](../microsoft.powershell.management/get-childitem.md) + +[Get-Credential](../microsoft.powershell.security/get-credential.md) + +[Get-Culture](../microsoft.powershell.utility/get-culture.md) + +[Get-Item](../microsoft.powershell.management/get-item.md) + +[New-CimSession](New-CimSession.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/Register-CimIndicationEvent.md b/reference/7/CimCmdlets/Register-CimIndicationEvent.md new file mode 100644 index 000000000000..7d40b8425efb --- /dev/null +++ b/reference/7/CimCmdlets/Register-CimIndicationEvent.md @@ -0,0 +1,396 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 02/20/2019 +schema: 2.0.0 +--- +# Register-CimIndicationEvent + +## SYNOPSIS +Subscribes to indications using a filter expression or a query expression. + +## SYNTAX + +### ClassNameComputerSet (Default) + +``` +Register-CimIndicationEvent [-Namespace ] [-ClassName] [-OperationTimeoutSec ] + [-ComputerName ] [[-SourceIdentifier] ] [[-Action] ] [-MessageData ] + [-SupportEvent] [-Forward] [-MaxTriggerCount ] [] +``` + +### ClassNameSessionSet + +``` +Register-CimIndicationEvent [-Namespace ] [-ClassName] [-OperationTimeoutSec ] + -CimSession [[-SourceIdentifier] ] [[-Action] ] [-MessageData ] + [-SupportEvent] [-Forward] [-MaxTriggerCount ] [] +``` + +### QueryExpressionSessionSet + +``` +Register-CimIndicationEvent [-Namespace ] [-Query] [-QueryDialect ] + [-OperationTimeoutSec ] -CimSession [[-SourceIdentifier] ] + [[-Action] ] [-MessageData ] [-SupportEvent] [-Forward] [-MaxTriggerCount ] + [] +``` + +### QueryExpressionComputerSet + +``` +Register-CimIndicationEvent [-Namespace ] [-Query] [-QueryDialect ] + [-OperationTimeoutSec ] [-ComputerName ] [[-SourceIdentifier] ] + [[-Action] ] [-MessageData ] [-SupportEvent] [-Forward] [-MaxTriggerCount ] + [] +``` + +## DESCRIPTION + +The `Register-CimIndicationEvent` cmdlet subscribes to indications using an indication class name or +a query expression. Use the **SourceIdentifier** parameter give a name to the subscription. + +This cmdlet returns an **EventSubscription** object. You can use this object to cancel the +subscription. + +## EXAMPLES + +### Example 1: Register the events generated by a class + +This set of commands subscribes to the events generated by the class named **Win32_ProcessStartTrace** +which raises an event whenever a process starts, and gets the events with ProcessStarted +subscription using the `Get-Event` cmdlet. For more information, see [Get-Event](../Microsoft.PowerShell.Utility/Get-Event.md). + +```powershell +Register-CimIndicationEvent -ClassName 'Win32_ProcessStartTrace' -SourceIdentifier "ProcessStarted" +Get-Event -SourceIdentifier "ProcessStarted" +``` + +> [!NOTE] +> For this example, you must run PowerShell as an Administrator. + +### Example 2: Register the events using a query + +This set of commands uses a query to subscribe to an event generated whenever there is a change in +the instance of a class named **Win32_LocalTime**. + +```powershell +$query = "SELECT * FROM CIM_InstModification WHERE TargetInstance ISA 'Win32_LocalTime'" +Register-CimIndicationEvent -Query $query -SourceIdentifier "Timer" +``` + +### Example 3: Run a script when the event arrives + +This set of commands shows how to use an action in response to an event. The variable `$action` +holds the script block for **Action**, which uses the `$event` variable to access the event received +from CIM. + +```powershell +$action = { + $name = $event.SourceEventArgs.NewEvent.ProcessName + $id = $event.SourceEventArgs.NewEvent.ProcessId + Write-Host -Object "New Process Started : Name = $name + ID = $id" +} +Register-CimIndicationEvent -ClassName 'Win32_ProcessStartTrace' -SourceIdentifier "ProcessStarted" -Action $action +``` + +For more information, see [Win32_ProcessStartTrace](/previous-versions/windows/desktop/krnlprov/win32-processstarttrace). + +### Example 4: Register the events on a remote computer + +This set of commands subscribes to events on a remote computer named Server01. Events received from +the CIM server are stored in the event queue in the current PowerShell session and then runs a local +`Get-Event` to retrieve the events. + +```powershell +Register-CimIndicationEvent -ClassName 'Win32_ProcessStartTrace' -SourceIdentifier "ProcessStarted" -ComputerName Server01 +Get-Event -SourceIdentifier "ProcessStarted" +``` + +## PARAMETERS + +### -Action + +Specifies the commands that handle the events. + +The commands specified by this parameter run when an event is raised, instead of sending the event +to the event queue. Enclose the commands in braces ( { } ) to create a script block. + +The script block specified with **Action** can include the `$Event`, `$EventSubscriber`, `$Sender`, +`$SourceEventArgs`, and `$SourceArgs` automatic variables, which provide information about the event +to the **Action** script block. For more information, see [About Automatic Variables](../microsoft.powershell.core/about/about_automatic_variables.md). + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CimSession + +Runs the command using the specified CIM session. Enter a variable that contains the CIM session, or +a command that creates or gets the CIM session, such as the `New-CimSession` or `Get-CimSession` +cmdlets. For more information, see [about_CimSessions]. + +```yaml +Type: CimSession +Parameter Sets: ClassNameSessionSet, QueryExpressionSessionSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClassName + +Specifies the indication class to which you are subscribing. You can use tab completion to browse +the list of classes, because PowerShell gets a list of classes from the local WMI server to provide +a list of class names. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, ClassNameSessionSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ComputerName + +Specifies the name of the computer on which you want to run the CIM operation. You can specify a +fully qualified domain name (FQDN), a NetBIOS name, or an IP address. + +If you specify this parameter, the cmdlet creates a temporary session to the specified computer +using the WsMan protocol. If you do not specify this parameter, the cmdlet performs operation on the +local system using Component Object Model (COM). + +If multiple operations are being performed on the same computer, connect using a CIM session for +better performance. + +```yaml +Type: String +Parameter Sets: ClassNameComputerSet, QueryExpressionComputerSet +Aliases: CN, ServerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Forward + +Indicates that events for the subscription are forwarded to the session on the local computer. Use +this parameter when you are registering for events on a remote computer or in a remote session. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaxTriggerCount + +Parameter to indicate that the subscriber should be auto-unregistered after being triggered for +specified times. If the value is equal or less than zero, there is no limit on the number of times +the event can be triggered without being unregistered. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MessageData + +Specifies any additional data to associate with this event subscription. The value of this parameter +appears in the **MessageData** property of all the events associated with this subscription. + +```yaml +Type: PSObject +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Namespace + +Specifies the namespace for the CIM operation. The default namespace is **root/cimv2**. You can use +tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from +the local WMI server to provide the list of namespaces. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OperationTimeoutSec + +Specifies the amount of time that the cmdlet waits for a response from the computer. By default, the +value of this parameter is 0, which means that the cmdlet uses the default timeout value for the +server. + +If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry +timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** +parameter are not recoverable, because the operation on the server times out before the client can +reconnect. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: OT + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Query + +Specifies a query to run on the CIM server. If the value specified contains double quotes `"`, +single quotes `'`, or a backslash `\`, you must escape those characters by prefixing them with the +backslash character. If the value specified uses the WQL LIKE operator, then you must escape +the following characters by enclosing them in square brackets `[]`: percent `%`, underscore `_`, +or opening square bracket `[`. + +```yaml +Type: String +Parameter Sets: QueryExpressionSessionSet, QueryExpressionComputerSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -QueryDialect + +Specifies the query language used for the **Query** parameter. The acceptable values for this +parameter are: **WQL** or **CQL**. The default value is **WQL**. + +```yaml +Type: String +Parameter Sets: QueryExpressionSessionSet, QueryExpressionComputerSet +Aliases: + +Required: False +Position: Named +Default value: WQL +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SourceIdentifier + +Specifies a name for the subscription. The name that you specify must be unique in the current +session. The default value is a GUID that PowerShell assigns. This value appears in the value of the +**SourceIdentifier** property of the subscriber object and of all event objects associated with this +subscription. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SupportEvent + +Indicates that the event subscription is hidden. Use this parameter when the current subscription is +part of a more complex event registration mechanism and it should not be discovered independently. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +This cmdlet accepts no input objects. + +## OUTPUTS + +### System.Object + +This cmdlet outputs an **EventSubscription** object. + +## NOTES + +## RELATED LINKS + +[Get-Event](../microsoft.powershell.utility/get-event.md) + +[Remove-Event](../microsoft.powershell.utility/remove-event.md) + +[Unregister-Event](../microsoft.powershell.utility/unregister-event.md) + +[Write-Host](../microsoft.powershell.utility/write-host.md) + +[Get-CimSession](Get-CimSession.md) + +[New-CimSession](New-CimSession.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/Remove-CimInstance.md b/reference/7/CimCmdlets/Remove-CimInstance.md new file mode 100644 index 000000000000..a6e12519f76a --- /dev/null +++ b/reference/7/CimCmdlets/Remove-CimInstance.md @@ -0,0 +1,302 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- + +# Remove-CimInstance + +## SYNOPSIS +Removes a CIM instance from a computer. + +## SYNTAX + +### CimInstanceComputerSet (Default) +``` +Remove-CimInstance [-ResourceUri ] [-ComputerName ] [-OperationTimeoutSec ] + [-InputObject] [-WhatIf] [-Confirm] [] +``` + +### CimInstanceSessionSet +``` +Remove-CimInstance -CimSession [-ResourceUri ] [-OperationTimeoutSec ] + [-InputObject] [-WhatIf] [-Confirm] [] +``` + +### QuerySessionSet +``` +Remove-CimInstance -CimSession [[-Namespace] ] [-OperationTimeoutSec ] + [-Query] [-QueryDialect ] [-WhatIf] [-Confirm] [] +``` + +### QueryComputerSet +``` +Remove-CimInstance [-ComputerName ] [[-Namespace] ] [-OperationTimeoutSec ] + [-Query] [-QueryDialect ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +The Remove-CimInstance cmdlet removes a CIM instance from a CIM server. + +You can specify the CIM instance to remove by using either a CIM instance object retrieved by the Get-CimInstance cmdlet, or by specifying a query. + +If the InputObject parameter is not specified, the cmdlet works in one of the following ways: + +- If neither the ComputerName parameter nor the CimSession parameter is specified, then this cmdlet works on local Windows Management Instrumentation (WMI) using a Component Object Model (COM) session. +- If either the ComputerName parameter or the CimSession parameter is specified, then this cmdlet works against the CIM server specified by either the ComputerName parameter or the CimSession parameter. + +## EXAMPLES + +### Example 1: Remove the CIM instance +``` +PS C:\>Remove-CimInstance -Query 'Select * from Win32_Environment where name LIKE "testvar%"' +``` + +This command removes the CIM instances that start with the character string testvar from the class named Win32_Environment using the Query parameter. + +### Example 2: Remove the CIM instance using CIM instance object +``` +PS C:\>calc.exe + + + +PS C:\>$var = Get-CimInstance -Query 'Select * from Win32_Process where name LIKE "calc%"' + + + +PS C:\>Remove-CimInstance -InputObject $var +``` + +This set of commands retrieves the CIM instance objects filtered by the Query parameter and stores them in variable named $var using the Get-CimInstance cmdlet. +The contents of the variable are then passed to the Remove-CimInstance cmdlet, which removes the CIM instances. + +## PARAMETERS + +### -CimSession +Runs the command using the specified CIM session. +Enter a variable that contains the CIM session, or a command that creates or gets the CIM session, such as the New-CimSession or Get-CimSession cmdlets. +For more information, see about_CimSessions. + +```yaml +Type: CimSession[] +Parameter Sets: CimInstanceSessionSet, QuerySessionSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ComputerName +Specifies the name of the computer on which you want to run the CIM operation. +You can specify a fully qualified domain name (FQDN) or a NetBIOS name. + +If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the WsMan protocol. + +If you do not specify this parameter, the cmdlet performs the operation on the local computer using Component Object Model (COM). + +If multiple operations are being performed on the same computer, connecting using a CIM session gives better performance. + +```yaml +Type: String[] +Parameter Sets: CimInstanceComputerSet +Aliases: CN, ServerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String[] +Parameter Sets: QueryComputerSet +Aliases: CN, ServerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Specifies a CIM instance object to be removed from the CIM server. +Note: The input object passed to the cmdlet is not changed, only the instance in the CIM server is removed. + +```yaml +Type: CimInstance +Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet +Aliases: CimInstance + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Namespace +Specifies the namespace for the CIM operation. + +The default namespace is root/cimv2. +NOTE: You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. + +```yaml +Type: String +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -OperationTimeoutSec +Specifies the amount of time that the cmdlet waits for a response from the computer. + +By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. + +If the OperationTimeoutSec parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the OperationTimeoutSec parameter are not recoverable, because the operation on the server times out before the client can reconnect. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: OT + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Query +Specifies a query to run on the CIM server. +You can specify the query dialect using the QueryDialect parameter. + +If the value specified contains double quotes ("), single quotes ('), or a backslash (\\), you must escape those characters by prefixing them with the backslash (\\) character. +If the value specified uses the WQL LIKE operator, then you must escape the following characters by enclosing them in square brackets (\[\]): percent (%), underscore (_), or opening square bracket (\[). + +```yaml +Type: String +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -QueryDialect +Specifies the query language used for the Query parameter. + +The acceptable values for this parameter are: WQL or CQL. + +The default value is WQL. + +```yaml +Type: String +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ResourceUri +Specifies the resource uniform resource identifier (URI) of the resource class or instance. +The URI is used to identify a specific type of resource, such as disks or processes, on a computer. + +A URI consists of a prefix and a path to a resource. +For example: + +- `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` +- `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings` + +By default, if you do not specify this parameter, the DMTF standard resource URI http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/ is used and the class name is appended to it. + +ResourceURI can only be used with CIM sessions created using the WSMan protocol, or when specifying the ComputerName parameter, which creates a CIM session using WSMan. +If you specify this parameter without specifying the ComputerName parameter, or if you specify a CIM session created using DCOM protocol, you will get an error, because the DCOM protocol does not support the ResourceURI parameter. + +If both the ResourceUri parameter and the Filter parameter are specified, the Filter parameter is ignored. + +```yaml +Type: Uri +Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. +For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None +This cmdlet accepts no input objects. + +## OUTPUTS + +### None +This cmdlet produces no outputs. + +## NOTES + +## RELATED LINKS + +[New-CimInstance](New-CimInstance.md) + +[Get-CimInstance](get-ciminstance.md) + +[Set-CimInstance](Set-CimInstance.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/Remove-CimSession.md b/reference/7/CimCmdlets/Remove-CimSession.md new file mode 100644 index 000000000000..d3d1d8f85f8c --- /dev/null +++ b/reference/7/CimCmdlets/Remove-CimSession.md @@ -0,0 +1,228 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- + +# Remove-CimSession + +## SYNOPSIS + +Removes one or more CIM sessions. + +## SYNTAX + +### CimSessionSet (Default) +``` +Remove-CimSession [-CimSession] [-WhatIf] [-Confirm] [] +``` + +### ComputerNameSet +``` +Remove-CimSession [-ComputerName] [-WhatIf] [-Confirm] [] +``` + +### SessionIdSet +``` +Remove-CimSession [-Id] [-WhatIf] [-Confirm] [] +``` + +### InstanceIdSet +``` +Remove-CimSession -InstanceId [-WhatIf] [-Confirm] [] +``` + +### NameSet +``` +Remove-CimSession -Name [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION + +The `Remove-CimSession` cmdlet removes one or more CIM session objects from the local PowerShell session. + +## EXAMPLES + +### Example 1: Remove all the CIM sessions + +```powershell +Get-CimSession | Remove-CimSession +``` + +This command retrieves all the available CIM sessions on the local computer using the [`Get-CimSession`](Get-CimSession.md) cmdlet, and then removes them using the `Remove-CimSession`. + +### Example 2: Remove a specific CIM session + +```powershell +Remove-CimSession -Id 5 +``` + +This command removes the CIM session that has an ID value of 5. + +### Example 3: Show the list of CIM sessions to remove by using the WhatIf parameter + +```powershell +Remove-CimSession -Name a* -WhatIf +``` + +This command uses the common parameter **WhatIf** to specify that the removal should not be done, but only output what would happen if it were done. + +## PARAMETERS + +### -CimSession + +Specifies the session objects of the CIM sessions to close. + +Enter a variable that contains the CIM session, or a command that creates or gets the CIM session, such as the [`New-CimSession`](New-CimSession.md) or [`Get-CimSession`](Get-CimSession.md) cmdlets. +For more information, see [about_CimSessions](../Microsoft.PowerShell.Core/About/about_CimSession.md). + +```yaml +Type: CimSession[] +Parameter Sets: CimSessionSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -ComputerName + +Specifies an array of names of computers. +Removes the sessions that connect to the specified computers. + +You can specify a fully qualified domain name (FQDN) or a NetBIOS name. + +```yaml +Type: String[] +Parameter Sets: ComputerNameSet +Aliases: CN, ServerName + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Id + +Specifies the ID of the CIM session to remove. +Specify one or more IDs separated by commas, or use the range operator (..) to specify a range of IDs. + +An ID is an integer that uniquely identifies the CIM session in the current PowerShell session. +It is easier to remember and type than InstanceId, but it is unique only within the current PowerShell session. + +For more information about the range operator, see [about_Operators](../Microsoft.PowerShell.Core/About/about_Operators.md). + +```yaml +Type: UInt32[] +Parameter Sets: SessionIdSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -InstanceId + +Specifies the instance ID of the CIM session to remove. + +InstanceId is a Globally Unique Identifier (GUID) that uniquely identifies a CIM session. +The InstanceId is unique, even when you have multiple sessions running in PowerShell. + +The InstanceId is stored in the **InstanceId** property of the object that represents a CIM session. + +```yaml +Type: Guid[] +Parameter Sets: InstanceIdSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Name + +Specifies the friendly name of the CIM session to remove. +You can use wildcard characters with this parameter. + +```yaml +Type: String[] +Parameter Sets: NameSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf + +Shows what would happen if the cmdlet runs. The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +This cmdlet accepts no input objects. + +## OUTPUTS + +### System.Object + +This cmdlet returns an object that contains CIM session information. + +## NOTES + +## RELATED LINKS + +[Get-CimSession](Get-CimSession.md) + +[New-CimSession](New-CimSession.md) + +[about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md) \ No newline at end of file diff --git a/reference/7/CimCmdlets/Set-CimInstance.md b/reference/7/CimCmdlets/Set-CimInstance.md new file mode 100644 index 000000000000..e0215a1ed69a --- /dev/null +++ b/reference/7/CimCmdlets/Set-CimInstance.md @@ -0,0 +1,435 @@ +--- +external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: CimCmdlets +ms.date: 06/09/2017 +schema: 2.0.0 +--- + +# Set-CimInstance + +## SYNOPSIS + +Modifies a CIM instance on a CIM server by calling the ModifyInstance method of the CIM class. + +## SYNTAX + +### CimInstanceComputerSet (Default) + +``` +Set-CimInstance [-ComputerName ] [-ResourceUri ] [-OperationTimeoutSec ] + [-InputObject] [-Property ] [-PassThru] [-WhatIf] [-Confirm] [] +``` + +### CimInstanceSessionSet + +``` +Set-CimInstance -CimSession [-ResourceUri ] [-OperationTimeoutSec ] + [-InputObject] [-Property ] [-PassThru] [-WhatIf] [-Confirm] [] +``` + +### QuerySessionSet + +``` +Set-CimInstance -CimSession [-Namespace ] [-OperationTimeoutSec ] + [-Query] [-QueryDialect ] -Property [-PassThru] [-WhatIf] [-Confirm] + [] +``` + +### QueryComputerSet + +``` +Set-CimInstance [-ComputerName ] [-Namespace ] [-OperationTimeoutSec ] + [-Query] [-QueryDialect ] -Property [-PassThru] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION + +The Set-CimInstance cmdlet modifies a CIM instance on a CIM server. + +If the InputObject parameter is not specified, the cmdlet works in one of the following ways: + +- If neither the ComputerName parameter nor the CimSession parameter is specified, then this cmdlet + works on local Windows Management Instrumentation (WMI) using a Component Object Model (COM) + session. +- If either the ComputerName parameter or the CimSession parameter is specified, then this cmdlet + works against the CIM server specified by either the ComputerName parameter or the CimSession + parameter. + +If the InputObject parameter is specified, the cmdlet works in one of the following ways: + +- If neither the ComputerName parameter nor the CimSession parameter is specified, then this cmdlet + uses the CIM session or computer name from the input object. +- If the either the ComputerName parameter or the CimSession parameter is specified, then this + cmdlet uses the either the CimSession parameter value or ComputerName parameter value. Note: This + is not very common. + +## EXAMPLES + +### Example 1: Set the CIM instance + +```powershell +PS C:\>Set-CimInstance -Query 'Select * from Win32_Environment where name LIKE "testvar%"' -Property @{VariableValue="abcd"} +``` + +This command sets the value of the VariableValue property to abcd using the Query parameter. +You can modify instances matching a Windows Management Instrumentation Query Language (WQL) query. + +### Example 2: Set the CIM instance property using pipeline + +```powershell +PS C:\>Get-CimInstance -Query 'Select * from Win32_Environment where name LIKE "testvar%"' | Set-CimInstance -Property @{VariableValue="abcd"} +``` + +This command retrieves the CIM instance object filtered by the Query parameter using the +Get-CimInstance cmdlet, and then passes the objects to the Set-CimInstance cmdlet, which modifies +the value of VariableValue property to abcd. + +### Example 3: Set the CIM instance property using input object + +```powershell +PS C:\>$x = Get-CimInstance -Query 'Select * from Win32_Environment where Name="testvar"' +PS C:\>Set-CimInstance -InputObject $x -Property @{VariableValue="somevalue"} -PassThru +``` + +This set of commands retrieves the CIM instance objects filtered by the Query parameter in to a +variable ($x) using Get-CimInstance, and then passes the contents of the variable to the +Set-CimInstance cmdlet. Set-CimInstance then modifies the VariableValue property to somevalue. +Because the Passthru parameter is used, this set of commands returns a modified CIM instance +object. + +### Example 4: Set the CIM instance property + +```powershell +PS C:\>$x = Get-CimInstance -Query 'Select * from Win32_Environment where name="testvar"' +PS C:\>$x.VariableValue = "Change" +PS C:\>Set-CimInstance -CimInstance $x -PassThru +``` + +This set of commands retrieves the CIM instance object that is specified in the Query parameter +into a variable ($x) using the Get-CimInstance cmdlet, and changes the VariableValue property value +of the object to change. The CIM instance object is then saved using the Set-CimInstance cmdlet. +Because the Passthru parameter is used, this set of commands returns a modified CIM instance +object. + +### Example 5: Show the list of CIM instances to modify using WhatIf + +```powershell +PS C:\>Set-CimInstance -Query 'Select * from Win32_Environment where name LIKE "testvar%"' -Property @{VariableValue="abcd"} -WhatIf +``` + +This command uses the common parameter WhatIf to specify that the modification should not be done, +but only output what would happen if it were done. + +### Example 6: Set the CIM instance after confirmation from the user + +```powershell +PS C:\>Set-CimInstance -Query 'Select * from Win32_Environment where name LIKE "testvar%"' -Property @{VariableValue="abcd"} -Confirm +``` + +This command uses the common parameter Confirm to specify that the modification should be done only +after confirmation from the user. + +### Example 7: Set the created CIM instance + +```powershell +PS C:\>$x = New-CimInstance -ClassName Win32_Environment -Property @{Name="testvar";UserName="domain\user"} -Keys Name,UserName -ClientOnly +PS C:\>Set-CimInstance -CimInstance $x -Property @{VariableValue="somevalue"} -PassThru +``` + +This set of commands creates a CIM instance with the specified properties using the New-CimInstance +cmdlet, and retrieves its contents in to a variable ($x). The variable is then passed to the +Set-CimInstance cmdlet, which modifies the value of VariableValue property to some value. Because +the Passthru parameter is used, this set of commands returns a modified CIM instance object. + +## PARAMETERS + +### -CimSession + +Runs the cmdlets on a remote computer. Enter a computer name or a session object, such as the +output of a New-CimSession or Get-CimSession cmdlet. + +```yaml +Type: CimSession[] +Parameter Sets: CimInstanceSessionSet, QuerySessionSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ComputerName + +Specifies the name of the computer on which you want to run the CIM operation. You can specify a +fully qualified domain name (FQDN) or a NetBIOS name. + +If you do not specify this parameter, the cmdlet performs the operation on the local computer using +Component Object Model (COM). + +If you specify this parameter, the cmdlet creates a temporary session to the specified computer +using the WsMan protocol. + +If multiple operations are being performed on the same computer, connecting using a CIM session +gives better performance. + +```yaml +Type: String[] +Parameter Sets: CimInstanceComputerSet, QueryComputerSet +Aliases: CN, ServerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject + +Specifies a CIM instance object to use as input. + +```yaml +Type: CimInstance +Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet +Aliases: CimInstance + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Namespace + +Specifies the namespace for the CIM operation. + +The default namespace is root/cimv2. You can use tab completion to browse the list of namespaces, +because PowerShell gets a list of namespaces from the local WMI server to provide the list of +namespaces. + +```yaml +Type: String +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -OperationTimeoutSec + +Specifies the amount of time that the cmdlet waits for a response from the computer. + +By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout +value for the server. + +If the OperationTimeoutSec parameter is set to a value less than the robust connection retry +timeout of 3 minutes, network failures that last more than the value of the OperationTimeoutSec +parameter are not recoverable, because the operation on the server times out before the client can +reconnect. + +```yaml +Type: UInt32 +Parameter Sets: (All) +Aliases: OT + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru + +Returns an object representing the item with which you are working. By default, this cmdlet does +not generate any output. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Property + +Specifies the properties of the CIM instance as a hash table (using name-value pairs). Only the +properties specified using this parameter are changed. Other properties of the CIM instance are not +changed. + +```yaml +Type: IDictionary +Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet +Aliases: Arguments + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +```yaml +Type: IDictionary +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: Arguments + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Query + +Specifies a query to run on the CIM server to retrieve CIM instances on which to run the cmdlet. +You can specify the query dialect using the QueryDialect parameter. + +If the value specified contains double quotes ("), single quotes ('), or a backslash (\\), you must +escape those characters by prefixing them with the backslash (\\) character. If the value specified +uses the WQL LIKE operator, then you must escape the following characters by enclosing them in +square brackets (\[\]): percent (%), underscore (_), or opening square bracket (\[). + +```yaml +Type: String +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -QueryDialect + +Specifies the query language used for the Query parameter. The acceptable values for this parameter +are: WQL or CQL. + +The default value is WQL. + +```yaml +Type: String +Parameter Sets: QuerySessionSet, QueryComputerSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -ResourceUri + +Specifies the resource uniform resource identifier (URI) of the resource class or instance. The URI +is used to identify a specific type of resource, such as disks or processes, on a computer. + +A URI consists of a prefix and a path to a resource. +For example: + +``` +http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk +http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings +``` + + +By default, if you do not specify this parameter, the DMTF standard resource URI +`http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. + +ResourceURI can only be used with CIM sessions created using the WSMan protocol, or when specifying +the ComputerName parameter, which creates a CIM session using WSMan. If you specify this parameter +without specifying the ComputerName parameter, or if you specify a CIM session created using DCOM +protocol, you will get an error, because the DCOM protocol does not support the ResourceURI +parameter. + +If both the ResourceUri parameter and the Filter parameter are specified, the Filter parameter is +ignored. + +```yaml +Type: Uri +Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf + +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Management.Infrastructure.CimInstance + +## OUTPUTS + +### Microsoft.Management.Infrastructure.CimInstance + +When the Passthru parameter is specified, this cmdlet returns a modified CIM instance object. + +## NOTES + +## RELATED LINKS + +[Get-CimInstance](get-ciminstance.md) + +[New-CimInstance](New-CimInstance.md) + +[Remove-CimInstance](remove-ciminstance.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Archive/Compress-Archive.md b/reference/7/Microsoft.PowerShell.Archive/Compress-Archive.md new file mode 100644 index 000000000000..a7d2238864d9 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Archive/Compress-Archive.md @@ -0,0 +1,325 @@ +--- +external help file: Microsoft.PowerShell.Archive-help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: Microsoft.PowerShell.Archive +ms.date: 02/12/2019 +online version: http://go.microsoft.com/fwlink/?LinkId=821654 +schema: 2.0.0 +title: Compress-Archive +--- + +# Compress-Archive + +## SYNOPSIS +Creates an archive, or zipped file, from specified files and folders. + +## SYNTAX + +### Path (Default) + +``` +Compress-Archive [-Path] [-DestinationPath] [-CompressionLevel ] + [-PassThru] [-WhatIf] [-Confirm] [] +``` + +### PathWithUpdate + +``` +Compress-Archive [-Path] [-DestinationPath] [-CompressionLevel ] -Update + [-PassThru] [-WhatIf] [-Confirm] [] +``` + +### PathWithForce + +``` +Compress-Archive [-Path] [-DestinationPath] [-CompressionLevel ] -Force + [-PassThru] [-WhatIf] [-Confirm] [] +``` + +### LiteralPathWithUpdate + +``` +Compress-Archive -LiteralPath [-DestinationPath] [-CompressionLevel ] + -Update [-PassThru] [-WhatIf] [-Confirm] [] +``` + +### LiteralPathWithForce + +``` +Compress-Archive -LiteralPath [-DestinationPath] [-CompressionLevel ] + -Force [-PassThru] [-WhatIf] [-Confirm] [] +``` + +### LiteralPath + +``` +Compress-Archive -LiteralPath [-DestinationPath] [-CompressionLevel ] + [-PassThru] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION + +The `Compress-Archive` cmdlet creates a zipped (or compressed) archive file from one or more +specified files or folders. An archive file allows multiple files to be packaged, and optionally +compressed, into a single zipped file for easier distribution and storage. An archive file can be +compressed by using the compression algorithm specified by the CompressionLevel parameter. + +The `Compress-Archive` cmdlet relies upon the Microsoft .NET API `System.IO.Compression.ZipArchive` +to compress files. Therefore, the maximum file size that is 2 GB. This is a limitation of the +underlying API. + +## EXAMPLES + +### Example 1: Create an archive file + +This command creates a new archive file, `Draft.zip`, by compressing two files, `Draftdoc.docx` and +`diagram2.vsd`, specified by the **Path** parameter. The compression level specified for this +operation is Optimal. + +```powershell +Compress-Archive -Path C:\Reference\Draftdoc.docx, C:\Reference\Images\diagram2.vsd -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip +``` + +### Example 2: Create an archive file (using LiteralPath) + +This command creates a new archive file, `Draft.zip`, by compressing two files, `Draft doc.docx` and +`Diagram [2].vsd`, specified by the **LiteralPath** parameter. The compression level specified for this +operation is Optimal. + +```powershell +Compress-Archive -LiteralPath 'C:\Reference\Draft Doc.docx', 'C:\Reference\Images\Diagram [2].vsd' -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip +``` + +### Example 3: Create an archive with wildcard characters + +This command creates a new archive file, `Draft.zip`, in the `C:\Archives` folder. The new archive +file contains every file in the `C:\Reference` folder, because a wildcard character was used in +place of specific file names in the **Path** parameter. + +```powershell +Compress-Archive -Path C:\Reference\* -CompressionLevel Fastest -DestinationPath C:\Archives\Draft +``` + +Notice that the file name extension .zip was not added to the value of the **DestinationPath** +parameter. PowerShell appends the .zip extension to the file name automatically. The specified +compression level is **Fastest**, which might result in a larger output file, but compresses a large +number of files faster. + +### Example 4: Update an existing archive file + +This command updates an existing archive file, Draft.Zip, in the C:\Archives folder. + +```powershell +Compress-Archive -Path C:\Reference\* -Update -DestinationPath C:\Archives\Draft.Zip +``` + +The command is run to update `Draft.Zip` with newer versions of existing files that came from the +C:\Reference folder, and also to add new files that have been added to `C:\Reference` since +`Draft.Zip` was initially created. + +### Example 5: Create an archive from an entire folder + +This command creates an archive from an entire folder, C:\Reference. + +```powershell +Compress-Archive -Path C:\Reference -DestinationPath C:\Archives\Draft +``` + +Notice that the file name extension .zip was not added to the value of the **DestinationPath** +parameter. PowerShell appends the .zip extension to the file name automatically. + +## PARAMETERS + +### -CompressionLevel + +Specifies how much compression to apply when you are creating the archive file. Faster compression +requires less time to create the file, but can result in larger file sizes. The acceptable values +for this parameter are: + +- **Fastest**. Use the fastest compression method available to decrease processing time; this can result + in larger file sizes. +- **NoCompression**. Do not compress the source files. +- **Optimal**. Processing time is dependent on file size. + +If this parameter is not specified, the command uses the default value, Optimal. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: +Accepted values: Optimal, NoCompression, Fastest + +Required: False +Position: Named +Default value: Optimal +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DestinationPath + +Specifies the path to the archive output file. This parameter is required. The specified +**DestinationPath** value should include the desired name of the output zipped file; it specifies +either the absolute or relative path to the zipped file. If the file name specified in +**DestinationPath** does not have a .zip file name extension, the cmdlet adds a .zip file name +extension. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Force + +Forces the command to run without asking for user confirmation. + +```yaml +Type: SwitchParameter +Parameter Sets: PathWithForce, LiteralPathWithForce +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LiteralPath + +Specifies the path or paths to the files that you want to add to the archive zipped file. Unlike the +**Path** parameter, the value of **LiteralPath** is used exactly as it is typed. No characters are +interpreted as wildcards. If the path includes escape characters, enclose each escape character in +single quotation marks, to instruct PowerShell not to interpret any characters as escape sequences. +To specify multiple paths, and include files in multiple locations in your output zipped file, use +commas to separate the paths. + +```yaml +Type: String[] +Parameter Sets: LiteralPathWithUpdate, LiteralPathWithForce, LiteralPath +Aliases: PSPath + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -PassThru + +Causes the cmdlet to output a file object representing the archive file created. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Path + +Specifies the path or paths to the files that you want to add to the archive zipped file. This +parameter can accept wildcard characters. Wildcard characters allow you to add all files in a folder +to your zipped archive file. To specify multiple paths, and include files in multiple locations in +your output zipped file, use commas to separate the paths. + +```yaml +Type: String[] +Parameter Sets: Path, PathWithUpdate, PathWithForce +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: True +``` + +### -Update + +Updates the specified archive by replacing older versions of files in the archive with newer +versions of files that have the same names. You can also add this parameter to add files to an +existing archive. + +```yaml +Type: SwitchParameter +Parameter Sets: PathWithUpdate, LiteralPathWithUpdate +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf + +Shows what would happen if the cmdlet runs. The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.String + +You can pipe a string that contains a path to one or more files. + +## OUTPUTS + +### System.IO.FileInfo + +The cmdlet only returns a **FileInfo** object when you use the **PassThru** parameter. + +## NOTES + +## RELATED LINKS + +[Expand-Archive](expand-archive.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Archive/Expand-Archive.md b/reference/7/Microsoft.PowerShell.Archive/Expand-Archive.md new file mode 100644 index 000000000000..664270bff776 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Archive/Expand-Archive.md @@ -0,0 +1,198 @@ +--- +external help file: Microsoft.PowerShell.Archive-help.xml +keywords: powershell,cmdlet +locale: en-us +Module Name: Microsoft.PowerShell.Archive +ms.date: 06/09/2017 +online version: http://go.microsoft.com/fwlink/?LinkId=821655 +schema: 2.0.0 +title: Expand-Archive +--- + +# Expand-Archive + +## SYNOPSIS +Extracts files from a specified archive (zipped) file. + +## SYNTAX + +### Path (Default) + +``` +Expand-Archive [-Path] [[-DestinationPath] ] [-Force] [-PassThru] [-WhatIf] [-Confirm] + [] +``` + +### LiteralPath + +``` +Expand-Archive -LiteralPath [[-DestinationPath] ] [-Force] [-PassThru] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION + +The `Expand-Archive` cmdlet extracts files from a specified zipped archive file to a specified destination folder. +An archive file allows multiple files to be packaged, and optionally compressed, into a single zipped file for easier distribution and storage. + +## EXAMPLES + +### Example 1: Extract the contents of an archive + +```powershell +Expand-Archive -LiteralPath C:\Archives\Draft.Zip -DestinationPath C:\Reference +``` + +This command extracts the contents of an existing archive file, Draft.zip, into the folder specified by the **DestinationPath** parameter, C:\Reference. + +### Example 2: Extract the contents of an archive in the current folder + +```powershell +Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference +``` + +This command extracts the contents of an existing archive file in the current folder, Draft.zip, into the folder specified by the **DestinationPath** parameter, C:\Reference. + +## PARAMETERS + +### -DestinationPath + +Specifies the path to the folder in which you want the command to save extracted files. +Enter the path to a folder, but do not specify a file name or file name extension. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: Current location +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Force + +Forces the command to run without asking for user confirmation. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LiteralPath + +Specifies the path to an archive file. +Unlike the **Path** parameter, the value of **LiteralPath** is used exactly as it is typed. +Wildcard characters are not supported. +If the path includes escape characters, enclose each escape character in single quotation marks, to instruct PowerShell not to interpret any characters as escape sequences. + +```yaml +Type: String +Parameter Sets: LiteralPath +Aliases: PSPath + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -PassThru + +Causes the cmdlet to output a list of the files expanded from the archive. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Path + +Specifies the path to the archive file. + +```yaml +Type: String +Parameter Sets: Path +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf + +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.String + +You can pipe a string that contains a path to an existing archive file. + +## OUTPUTS + +### System.IO.FileSystemInfo + +When the `-PassThru` parameter is used, the cmdlet outputs a list of files that were expanded from +the archive. + +## NOTES + +## RELATED LINKS + +[Compress-Archive](compress-archive.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Archive/Microsoft.PowerShell.Archive.md b/reference/7/Microsoft.PowerShell.Archive/Microsoft.PowerShell.Archive.md new file mode 100644 index 000000000000..00b42e48c743 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Archive/Microsoft.PowerShell.Archive.md @@ -0,0 +1,25 @@ +--- +ms.date: 06/09/2017 +schema: 2.0.0 +locale: en-US +keywords: powershell,cmdlet +Help Version: 6.1.0.1 +Download Help Link: https://go.microsoft.com/fwlink/?linkid=855952 +Module Guid: eb74e8da-9ae2-482a-a648-e96550fb8733 +title: Microsoft.PowerShell.Archive +Module Name: Microsoft.PowerShell.Archive +--- + +# Microsoft.PowerShell.Archive Module + +## Description + +This section contains the help topics for the cmdlets that are installed with the PowerShell Microsoft.PowerShell.Archive module. The Archive module contains cmdlets that let you create and extract archive or ZIP files. + +## Microsoft.PowerShell.Archive Cmdlets + +### [Compress-Archive](Compress-Archive.md) +Creates an archive, or zipped file, from specified files and folders. + +### [Expand-Archive](Expand-Archive.md) +Extracts files from a specified archive (zipped) file. \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/About.md b/reference/7/Microsoft.PowerShell.Core/About/About.md new file mode 100644 index 000000000000..8db22fcdee84 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/About.md @@ -0,0 +1,356 @@ +--- +ms.date: 02/25/2019 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +Help Version: 6.0 +Download Help Link: http://Please-enter-FwLink-manually +Module Guid: 00000000-0000-0000-0000-000000000000 +Module Name: About +--- +# About Module + +## Description + +About topics cover a ranges of concepts about PowerShell. + +## About Topics + +### [about_Alias_Provider](about_Alias_Provider.md) +Describes the features of the Alias provider. + +### [about_Aliases](about_Aliases.md) +Describes how to use alternate names for cmdlets and commands in PowerShell. + +### [about_Arithmetic_Operators](about_Arithmetic_Operators.md) +Describes the operators that perform arithmetic in PowerShell. + +### [about_Arrays](about_Arrays.md) +Describes arrays, which are data structures designed to store collections of items. + +### [about_Assignment_Operators](about_Assignment_Operators.md) +Describes how to use operators to assign values to variables. + +### [about_Automatic_Variables](about_Automatic_Variables.md) +Describes variables that store state information for PowerShell. These variables are created and maintained by PowerShell. + +### [about_Break](about_Break.md) +Describes a statement you can use to immediately exit Foreach, For, While, Do, or Switch statements. + +### [about_CimSession](about_CimSession.md) +Describes a CimSession object and the difference between CIM sessions and PowerShell sessions. + +### [about_Classes](about_Classes.md) +Describes how you can use classes to create your own custom types. + +### [about_Command_Precedence](about_Command_Precedence.md) +Describes how PowerShell determines which command to run. + +### [about_Command_Syntax](about_Command_Syntax.md) +Describes the syntax diagrams that are used in PowerShell. + +### [about_Comment_Based_Help](about_Comment_Based_Help.md) +Describes how to write comment-based help topics for functions and scripts. + +### [about_CommonParameters](about_CommonParameters.md) +Describes the parameters that can be used with any cmdlet. + +### [about_Comparison_Operators](about_Comparison_Operators.md) +Describes the operators that compare values in PowerShell. + +### [about_Continue](about_Continue.md) +Describes how the `Continue` statement immediately returns the program flow to the top of a program loop. + +### [about_Core_Commands](about_Core_Commands.md) +Lists the cmdlets that are designed for use with PowerShell providers. + +### [about_Data_Sections](about_Data_Sections.md) +Explains Data sections, which isolate text strings and other read-only data from script logic. + +### [about_Debuggers](about_Debuggers.md) +Describes the PowerShell debugger. + +### [about_Do](about_Do.md) +Runs a statement list one or more times, subject to a While or Until condition. + +### [about_Enum](about_Enum.md) +The `enum` statement is used to declare an enumeration. An enumeration is a distinct type that consists of a set of named labels called the enumerator list. + +### [about_Environment_Provider](about_Environment_Provider.md) +Describes the features of the Environment provider. + +### [about_Environment_Variables](about_Environment_Variables.md) +Describes how to access Windows environment variables in PowerShell. + +### [about_Execution_Policies](about_Execution_Policies.md) +Describes the PowerShell execution policies and explains how to manage them. + +### [about_Experimental_Features](about_Experimental_Features.md) +Describes how to use the Experimental Features of PowerShell. + +### [about_FileSystem_Provider](about_FileSystem_Provider.md) +Describes the features of the FileSystem provider. + +### [about_For](about_For.md) +Describes a language command you can use to run statements based on a conditional test. + +### [about_Foreach](about_Foreach.md) +Describes a language command you can use to traverse all the items in a collection of items. + +### [about_Format.ps1xml](about_Format.ps1xml.md) +The `Format.ps1xml` files in PowerShell define the default display of objects in the PowerShell console. + +### [about_Function_Provider](about_Function_Provider.md) +Describes the features of the Function provider. + +### [about_Functions](about_Functions.md) +Describes how to create and use functions in PowerShell. + +### [about_Functions_Advanced](about_Functions_Advanced.md) +Introduces advanced functions that act similar to cmdlets. + +### [about_Functions_Advanced_Methods](about_Functions_Advanced_Methods.md) +Describes how functions that specify the `CmdletBinding` attribute can use the methods and properties that are available to compiled cmdlets. + +### [about_Functions_Advanced_Parameters](about_Functions_Advanced_Parameters.md) +Explains how to add parameters to advanced functions. + +### [about_Functions_CmdletBindingAttribute](about_Functions_CmdletBindingAttribute.md) +Describes the attribute that makes a function work like a compiled cmdlet. + +### [about_Functions_OutputTypeAttribute](about_Functions_OutputTypeAttribute.md) +Describes an attribute that reports the type of object that the function returns. + +### [about_Group_Policy_Settings](about_Group_Policy_Settings.md) +Describes the Group Policy settings for PowerShell. + +### [about_Hash_Tables](about_Hash_Tables.md) +Describes how to create, use, and sort hash tables in PowerShell. + +### [about_hidden](about_hidden.md) +Describes the Hidden keyword, which hides class members from default Get-Member results. + +### [about_History](about_History.md) +Describes how to get and run commands in the command history. + +### [about_If](about_If.md) +Describes a language command you can use to run statement lists based on the results of one or more conditional tests. + +### [about_Job_Details](about_Job_Details.md) +Provides details about background jobs on local and remote computers. + +### [about_Jobs](about_Jobs.md) +Provides information about how PowerShell background jobs run a command or expression in the background without interacting with the current session. + +### [about_Join](about_Join.md) +Describes how the join operator (-join) combines multiple strings into a single string. + +### [about_Language_Keywords](about_Language_Keywords.md) +Describes the keywords in the PowerShell scripting language. + +### [about_Language_Modes](about_Language_Modes.md) +Explains language modes and their effect on PowerShell sessions. + +### [about_Line_Editing](about_Line_Editing.md) +Describes how to edit commands at the PowerShell command prompt. + +### [about_locations](about_locations.md) +Describes how to access items from the working location in PowerShell. + +### [about_Logging_Non-Windows](about_Logging_Non-Windows.md) +PowerShell logs internal operations from the engine, providers, and cmdlets. + +### [about_Logging_Windows](about_Logging_Windows.md) +PowerShell logs internal operations from the engine, providers, and cmdlets. + +### [about_logical_operators](about_logical_operators.md) +Describes the operators that connect statements in PowerShell. + +### [about_Methods](about_Methods.md) +Describes how to use methods to perform actions on objects in PowerShell. + +### [about_Modules](about_Modules.md) +Explains how to install, import, and use PowerShell modules. + +### [about_Object_Creation](about_Object_Creation.md) +Explains how to create objects in PowerShell. + +### [about_Objects](about_Objects.md) +Provides essential information about objects in PowerShell. + +### [about_Operator_Precedence](about_Operator_Precedence.md) +Lists the PowerShell operators in precedence order. + +### [about_Operators](about_Operators.md) +Describes the operators that are supported by PowerShell. + +### [about_PackageManagement](about_PackageManagement.md) +PackageManagement is an aggregator for software package managers. + +### [about_Parameters](about_Parameters.md) +Describes how to work with command parameters in PowerShell. + +### [about_Parameters_Default_Values](about_Parameters_Default_Values.md) +Describes how to set custom default values for the parameters of cmdlets and advanced functions. + +### [about_Parsing](about_Parsing.md) +Describes how PowerShell parses commands. + +### [about_Path_Syntax](about_Path_Syntax.md) +Describes the full and relative path name formats in PowerShell. + +### [about_pipelines](about_pipelines.md) +Combining commands into pipelines in the PowerShell. + +### [about_PowerShell_Config](about_PowerShell_Config.md) +Configuration files for PowerShell Core, replacing Registry configuration. + +### [about_PowerShell_Editions](about_PowerShell_Editions.md) +Different editions of PowerShell run on different underlying runtimes. + +### [about_Preference_Variables](about_Preference_Variables.md) +Variables that customize the behavior of PowerShell. + +### [about_Profiles](about_Profiles.md) +Describes how to create and use a PowerShell profile. + +### [about_Prompts](about_Prompts.md) +Describes the Prompt function and demonstrates how to create a custom Prompt function. + +### [about_Properties](about_Properties.md) +Describes how to use object properties in PowerShell. + +### [about_Providers](about_Providers.md) +Describes how PowerShell providers provide access to data and components that would not otherwise be easily accessible at the command line. + +### [about_psconsolehostreadline](about_psconsolehostreadline.md) +Explains how to create a customize how PowerShell reads input at the console prompt. + +### [about_PSSession_Details](about_PSSession_Details.md) +Provides detailed information about PowerShell sessions and the role they play in remote commands. + +### [about_PSSessions](about_PSSessions.md) +Describes PowerShell sessions (PSSessions) and explains how to establish a persistent connection to a remote computer. + +### [about_pwsh](about_pwsh.md) +Explains how to use the pwsh command-line tool. Displays the syntax and describes the command-line switches. pwsh starts a PowerShell session. + +### [about_Quoting_Rules](about_Quoting_Rules.md) +Describes rules for using single and double quotation marks in PowerShell. + +### [about_Redirection](about_Redirection.md) +Explains how to redirect output from PowerShell to text files. + +### [about_Ref](about_Ref.md) +Describes how to create and use a reference type variable. You can use reference type variables to permit a function to change the value of a variable that is passed to it. + +### [about_Registry_Provider](about_Registry_Provider.md) +Describes the features of the Registry provider. + +### [about_Regular_Expressions](about_Regular_Expressions.md) +Describes regular expressions in PowerShell. + +### [about_Remote](about_Remote.md) +Describes how to run remote commands in PowerShell. + +### [about_Remote_Disconnected_Sessions](about_Remote_Disconnected_Sessions.md) +Explains how to disconnect from and reconnect to a PSSession. + +### [about_Remote_FAQ](about_Remote_FAQ.md) +Contains questions and answers about running remote commands in PowerShell. + +### [about_Remote_Jobs](about_Remote_Jobs.md) +Describes how to run background jobs on remote computers. + +### [about_Remote_Output](about_Remote_Output.md) +Describes how to interpret and format the output of remote commands. + +### [about_Remote_Requirements](about_Remote_Requirements.md) +Describes the system requirements and configuration requirements for running remote commands in PowerShell. + +### [about_Remote_Troubleshooting](about_Remote_Troubleshooting.md) +Describes how to troubleshoot remote operations in PowerShell. + +### [about_Remote_Variables](about_Remote_Variables.md) +Explains how to use local and remote variables in remote commands. + +### [about_Requires](about_Requires.md) +Prevents a script from running without the required elements. + +### [about_Reserved_Words](about_Reserved_Words.md) +Lists the reserved words that cannot be used as identifiers because they have a special meaning in PowerShell. + +### [about_Return](about_Return.md) +Exits the current scope, which can be a function, script, or script block. + +### [about_Run_With_PowerShell](about_Run_With_PowerShell.md) +Explains how to use the "Run with PowerShell" feature to run a script from a file system drive. + +### [about_Scopes](about_Scopes.md) +Explains the concept of scope in PowerShell and shows how to set and change the scope of elements. + +### [about_Script_Blocks](about_Script_Blocks.md) +Defines what a script block is and explains how to use script blocks in the PowerShell programming language. + +### [about_Script_Internationalization](about_Script_Internationalization.md) +Describes the script internationalization features that make it easy for scripts to display messages and instructions to users in their user interface (UI) language. + +### [about_Scripts](about_Scripts.md) +Describes how to run and write scripts in PowerShell. + +### [about_Session_Configuration_Files](about_Session_Configuration_Files.md) +Describes session configuration files, which are used in a session configuration (also known as an "endpoint") to define the environment of sessions that use the session configuration. + +### [about_Session_Configurations](about_Session_Configurations.md) +Describes session configurations, which determine the users who can connect to the computer remotely and the commands they can run. + +### [about_Signing](about_Signing.md) +Explains how to sign scripts so that they comply with the PowerShell execution policies. + +### [about_simplified_syntax](about_simplified_syntax.md) +Describes easier, more natural-language ways of scripting filters for collections of objects. + +### [about_Special_Characters](about_Special_Characters.md) +Describes the special characters that you can use to control how PowerShell interprets the next character in a command or parameter. + +### [about_Splatting](about_Splatting.md) +Describes how to use splatting to pass parameters to commands in PowerShell. + +### [about_Split](about_Split.md) +Explains how to use the Split operator to split one or more strings into substrings. + +### [about_Switch](about_Switch.md) +Explains how to use a switch to handle multiple If statements. + +### [about_Throw](about_Throw.md) +Describes the Throw keyword, which generates a terminating error. + +### [about_Trap](about_Trap.md) +Describes a keyword that handles a terminating error. + +### [about_Try_Catch_Finally](about_Try_Catch_Finally.md) +Describes how to use the `Try`, `Catch`, and `Finally` blocks to handle terminating errors. + +### [about_Type_Operators](about_Type_Operators.md) +Describes the operators that work with Microsoft .NET Framework types. + +### [about_Types.ps1xml](about_Types.ps1xml.md) +Explains how to use Types.ps1xml files to extend the types of objects that are used in PowerShell. + +### [about_Updatable_Help](about_Updatable_Help.md) +Describes the updatable help system in PowerShell. + +### [About_Using](About_Using.md) +Allows to indicate which namespaces are used in the session. + +### [about_Variable_Provider](about_Variable_Provider.md) +Describes the features of the Variable provider. + +### [about_Variables](about_Variables.md) +Describes how variables store values that can be used in PowerShell. + +### [about_While](about_While.md) +Describes a language statement that you can use to run a command block based on the results of a conditional test. + +### [about_Wildcards](about_Wildcards.md) +Describes how to use wildcard characters in PowerShell. diff --git a/reference/7/Microsoft.PowerShell.Core/About/About_Using.md b/reference/7/Microsoft.PowerShell.Core/About/About_Using.md new file mode 100644 index 000000000000..394964c196f0 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/About_Using.md @@ -0,0 +1,76 @@ +--- +ms.date: 12/01/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Using +--- +# About Using + +## SHORT DESCRIPTION +Allows to indicate which namespaces are used in the session. + +## LONG DESCRIPTION + +The `using` statement allows to indicate which namespaces are used in the +session. Making easier to mention classes and members, as it requires less +typing to mention them; also, classes from modules can be referenced too. + +The `using` statement needs to be the first statement in the script. + +Syntax #1, to reference .Net Framework namespaces: + +``` +using namespace <.Net-framework-namespace> +``` + +Syntax #2, to reference PowerShell modules: + +``` +using module +``` + +**Note**: The `using` statement, for modules, is intended to surface the +classes in the module. If the module isn't loaded, the `using` fails. + +## Examples + +The following script gets the cryptographic hash for the "Hello World" string. + +Note how the `using namespace System.Text` and `using namespace System.IO` +simplify the references to `[UnicodeEncoding]` in *System.Text*; and, to +`[Stream]` and to `[MemoryStream]` in *System.IO*. + +```powershell +using namespace System.Text +using namespace System.IO + +[string]$string = "Hello World" +## Valid values are "SHA1", "SHA256", "SHA384", "SHA512", "MD5" +[string]$algorithm = "SHA256" + +[byte[]]$stringbytes = [UnicodeEncoding]::Unicode.GetBytes($string) + +[Stream]$memorystream = [MemoryStream]::new($stringbytes) +$hashfromstream = Get-FileHash -InputStream $memorystream ` + -Algorithm $algorithm +$hashfromstream.Hash.ToString() +``` + +The following script assumes a module named 'CardGames' was loaded +automatically. + +The following classes are defined in the module: + +- *Deck* +- *Card* + +```powershell +using module CardGames + +[Deck]$deck = [Deck]::new() +$deck.Shuffle() +[Card[]]$hand1 = $deck.Deal(5) +[Card[]]$hand2 = $deck.Deal(5) +[Card[]]$hand3 = $deck.Deal(5) +``` \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Alias_Provider.md b/reference/7/Microsoft.PowerShell.Core/About/about_Alias_Provider.md new file mode 100644 index 000000000000..01ab779168f7 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Alias_Provider.md @@ -0,0 +1,316 @@ +--- +ms.date: 10/18/2018 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: Alias Provider +online version: http://go.microsoft.com/fwlink/?LinkId=834943 +--- +# Alias provider + +## Provider name +Alias + +## Drives + +`Alias:` + +## Capabilities + +**ShouldProcess** + +## Short description + +Provides access to the PowerShell aliases and the values that they represent. + +## Detailed description + +The PowerShell **Alias** provider lets you get, add, change, clear, and delete +aliases in PowerShell. + +An alias is an alternate name for a cmdlet, function, executable file, +including scripts. PowerShell includes a set of built-in aliases. You can add +your own aliases to the current session and to your PowerShell profile. + +The **Alias** drive is a flat namespace that contains only the alias objects. +The aliases have no child items. + +The **Alias** provider supports the following cmdlets, which are covered +in this article. + +- [Get-Location](../../Microsoft.PowerShell.Management/Get-Location.md) +- [Set-Location](../../Microsoft.PowerShell.Management/Set-Location.md) +- [Get-Item](../../Microsoft.PowerShell.Management/Get-Item.md) +- [New-Item](../../Microsoft.PowerShell.Management/New-Item.md) +- [Remove-Item](../../Microsoft.PowerShell.Management/Remove-Item.md) +- [Clear-Item](../../Microsoft.PowerShell.Management/Clear-Item.md) + +PowerShell includes a set of cmdlets that are designed to view and to change aliases. When you use **Alias** cmdlets, you do not need to specify the `Alias:` drive in the name. This article does not cover working with +**Alias** cmdlets. + +- [Export-Alias](../../Microsoft.PowerShell.Utility/Export-Alias.md) +- [Get-Alias](../../Microsoft.PowerShell.Utility/Get-Alias.md) +- [Import-Alias](../../Microsoft.PowerShell.Utility/Import-Alias.md) +- [New-Alias](../../Microsoft.PowerShell.Utility/New-Alias.md) +- [Set-Alias](../../Microsoft.PowerShell.Utility/Set-Alias.md) + +## Types exposed by this provider + +Each alias is an instance of the +[System.Management.Automation.AliasInfo](/dotnet/api/system.management.automation.aliasinfo) class. + +## Navigating the Alias drive + +The **Alias** provider exposes its data store in the `Alias:` drive. To work +with aliases, you can change your location to the `Alias:` drive by using the +following command: + +```powershell +Set-Location Alias: +``` + +To return to a file system drive, type the drive name. For example, type: + +```powershell +Set-Location C: +``` + +You can also work with the Alias provider from any other PowerShell drive. To +reference an alias from another location, use the `Alias:` drive name in the +path. + +> [!NOTE] +> PowerShell uses aliases to allow you a familiar way to work with provider +> paths. Commands such as `dir` and `ls` are now aliases for +> [Get-ChildItem](../../Microsoft.PowerShell.Management/Get-ChildItem.md), +> `cd` is an alias for [Set-Location](../../Microsoft.PowerShell.Management/Set-Location.md). and `pwd` is +> an alias for [Get-Location](../../Microsoft.PowerShell.Management/Get-Location.md). + +### Displaying the Contents of the Alias: drive + +This command gets the list of all the aliases when the current location is the +`Alias:` drive. It uses a wildcard character `*` to indicate all the contents +of the current location. + +```powershell +PS Alias:\> Get-Item -Path * +``` + +In the `Alias:` drive, a dot `.`, which represents the current location, and a +wildcard character `*`, which represents all items in the current location, +have the same effect. For example, `Get-Item -Path .` or `Get-Item \*` produce +the same result. + +The Alias provider has no containers, so the above command has the +same effect when used with `Get-ChildItem`. + +```powershell +Get-ChildItem -Path Alias: +``` + +### Get a selected alias + +This command gets the `ls` alias. +Because it includes the path, you can use it in any PowerShell drive. + +```powershell +Get-Item -Path Alias:ls +``` + +If you are in the `Alias:` drive, you can omit the drive name from the path. + +### Get all aliases for a specific cmdlet + +This command gets a list of the aliases that are associated with the +`Get-ChildItem` cmdlet. It uses the **Definition** property, which stores +the cmdlet name. + +```powershell +Get-Item -Path Alias:* | Where-Object {$_.Definition -eq "Get-ChildItem"} +``` + +## Creating aliases + +### Create an alias from the Alias: drive + +This command creates the `serv` alias for the `Get-Service` cmdlet. Because the +current location is in the `Alias:` drive, the `-Path` parameter is not +needed. + +This command also uses the `-Options` dynamic parameter to set the **AllScope** +option on the alias. The `-Options` parameter is available in +the `New-Item` cmdlet only when you are in the `Alias:` drive. The dot (`.`) +indicates the current directory, which is the alias drive. + +```powershell +PS Alias:\> New-Item -Path . ` + -Name serv ` + -Value Get-Service ` + -Options "AllScope" +``` + +### Create an alias with an absolute path + +You can create an alias for any item that invokes a command. +This command creates the `np` alias for `Notepad.exe`. + +```powershell +New-Item -Path Alias:np -Value c:\windows\notepad.exe +``` + +### Create an alias to a new function + +You can create an alias for any function. You can use this feature to create an +alias that includes both a cmdlet and its parameters. + +The first command creates the `CD32` function, which changes the current +directory to the `System32` directory. The second command creates the `go` +alias for the `CD32` function. + +When the command is complete, you can use either `CD32` or `go` to invoke the +function. + +```powershell +function CD32 {Set-Location -Path c:\windows\system32} +Set-Item -Path Alias:go -Value CD32 +``` + +## Changing aliases + +### Change the options of an alias + +You can use the `Set-Item` cmdlet with the `-Options` dynamic parameter to +change the value of the `-Options` property of an alias. + +This command sets the **AllScope** and **ReadOnly** options for the `dir` +alias. The command uses the `-Options` dynamic parameter of the `Set-Item` +cmdlet. The `-Options` parameter is available in `Set-Item` when you use it +with the **Alias** or **Function** provider. + +```powershell +Set-Item -Path Alias:dir -Options "AllScope,ReadOnly" +``` + +### Change an aliases referenced command + +This command uses the `Set-Item` cmdlet to change the `gp` alias so that it +represents the `Get-Process` cmdlet instead of the `Get-ItemProperty` cmdlet. +The `-Force` parameter is required because the value of the **Options** +property of the `gp` alias is set to `ReadOnly`. Because the command is +submitted from within the `Alias:` drive, the drive is not specified in the +path. + +```powershell +Set-Item -Path gp -Value Get-Process -Force +``` + +The change affects the four properties that define the association between the +alias and the command. To view the effect of the change, type the following +command: + +```powershell +Get-Item -Path gp | Format-List -Property * +``` + +### Rename an alias + +This command uses the `Rename-Item` cmdlet to change the `popd` alias to `pop`. + +```powershell +Rename-Item -Path Alias:popd -NewName pop +``` + +## Copying an alias + +This command copies the `pushd` alias so that a new `push` alias is created for +the `Push-Location` cmdlet. + +When the new alias is created, its **Description** property has a null value. +And, its **Option** property has a value of `None`. If the command is issued +from within the `Alias:` drive, you can omit the drive name from the value of +the `-Path` parameter. + +```powershell +Copy-Item -Path Alias:pushd -Destination Alias:push +``` + +## Deleting an alias + +This command deletes the `serv` alias from the current session. +You can use this command in any PowerShell drive. + +```powershell +Remove-Item -Path Alias:serv +``` + +This command deletes aliases that begin with "s". +It does not delete read-only aliases. + +```powershell +Clear-Item -Path Alias:s* +``` + +### Delete read-only aliases + +This command deletes all aliases from the current session, except those with a +value of `Constant` for their **Options** property. The `-Force` +parameter allows the command to delete aliases whose **Options** property has a +value of `ReadOnly`. + +```powershell +Remove-Item Alias:* -Force +``` + +## Dynamic parameters + +Dynamic parameters are cmdlet parameters that are added by a PowerShell +provider and are available only when the cmdlet is being used in the +provider-enabled drive. + +### Options [System.Management.Automation.ScopedItemOptions] + +Determines the value of the **Options** property of an alias. + +- `None`: No options. This value is the default. +- `Constant`:The alias cannot be deleted and its properties cannot be changed. + `Constant` is available only when you create an alias. You cannot change the option of an existing alias to `Constant`. +- `Private`:The alias is visible only in the current scope, not in the child + scopes. +- `ReadOnly`:The properties of the alias cannot be changed except by using the + `-Force` parameter. You can use `Remove-Item` to delete the alias. +- `AllScope`:The alias is copied to any new scopes that are created. + +#### Cmdlets supported + +- [New-Item](../../Microsoft.PowerShell.Management/New-Item.md) +- [Set-Item](../../Microsoft.PowerShell.Management/Set-Item.md) + +## Using the pipeline + +Provider cmdlets accept pipeline input. You can use the pipeline to simplify +task by sending provider data from one cmdlet to another provider cmdlet. +To read more about how to use the pipeline with provider cmdlets, see the +cmdlet references provided throughout this article. + +## Getting help + +Beginning in Windows PowerShell 3.0, you can get customized help topics for +provider cmdlets that explain how those cmdlets behave in a file system drive. + +To get the help topics that are customized for the file system drive, run a +[Get-Help](../Get-Help.md) command in a file system drive or use the `-Path` +parameter of [Get-Help](../Get-Help.md) to specify a file system drive. + +```powershell +Get-Help Get-ChildItem +``` + +```powershell +Get-Help Get-ChildItem -Path alias: +``` + +## See also + +[about_Aliases](../About/about_Aliases.md) + +[about_Providers](../About/about_Providers.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Aliases.md b/reference/7/Microsoft.PowerShell.Core/About/about_Aliases.md new file mode 100644 index 000000000000..49491ee906e7 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Aliases.md @@ -0,0 +1,269 @@ +--- +ms.date: 11/27/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Aliases +--- +# About Aliases + +## SHORT DESCRIPTION +Describes how to use alternate names for cmdlets and commands in +PowerShell. + +## LONG DESCRIPTION + +An alias is an alternate name or nickname for a cmdlet or for a command +element, such as a function, script, file, or executable file. You can use the +alias instead of the command name in any PowerShell commands. + +To create an alias, use the New-Alias cmdlet. For example, the following +command creates the "gas" alias for the `Get-AuthenticodeSignature` cmdlet: + +```powershell +New-Alias -Name gas -Value Get-AuthenticodeSignature +``` + +After you create the alias for the cmdlet name, you can use the alias instead +of the cmdlet name. For example, to get the Authenticode signature for the +SqlScript.ps1 file, type: + +```powershell +Get-AuthenticodeSignature SqlScript.ps1 +``` + +Or, type: + +```powershell +gas SqlScript.ps1 +``` + +If you create "word" as the alias for Microsoft Office Word, you can type +"word" instead of the following: + +```powershell +"C:\Program Files\Microsoft Office\Office11\Winword.exe" +``` + +## BUILT-IN ALIASES + +PowerShell includes a set of built-in aliases, including "cd" and "chdir" for +the Set-Location cmdlet, and "ls" and "dir" for the Get-ChildItem cmdlet. + +To get all the aliases on the computer, including the built-in aliases, type: + +```powershell +Get-Alias +``` + +## ALIAS CMDLETS + +PowerShell includes the following cmdlets, which are designed for working with +aliases: + +- `Get-Alias` - Gets all the aliases in the current session. +- `New-Alias` - Creates a new alias. +- `Set-Alias` - Creates or changes an alias. +- `Export-Alias` - Exports one or more aliases to a file. +- `Import-Alias` - Imports an alias file into PowerShell. + +For detailed information about the cmdlets, type: + +```powershell +Get-Help -Detailed +``` + +For example, type: + +```powershell +Get-Help Export-Alias -Detailed +``` + +## CREATING AN ALIAS + +To create a new alias, use the New-Alias cmdlet. For example, to create the +"gh" alias for Get-Help, type: + +```powershell +New-Alias -Name gh -Value Get-Help +``` + +You can use the alias in commands, just as you would use the full cmdlet name, +and you can use the alias with parameters. + +For example, to get detailed Help for the Get-WmiObject cmdlet, type: + +```powershell +Get-Help Get-WmiObject -Detailed +``` + +Or, type: + +```powershell +gh Get-WmiObject -Detailed +``` + +## SAVING ALIASES + +The aliases that you create are saved only in the current session. To use the +aliases in a different session, add the alias to your PowerShell profile. Or, +use the Export-Alias cmdlet to save the aliases to a file. + +For more information, type: + +```powershell +Get-Help about_Profiles +``` + +## GETTING ALIASES + +To get all the aliases in the current session, including the built-in aliases, +the aliases in your PowerShell profiles, and the aliases that you have created +in the current session, type: + +```powershell +Get-Alias +``` + +To get particular aliases, use the Name parameter of the Get-Alias cmdlet. For +example, to get aliases that begin with "p", type: + +```powershell +Get-Alias -Name p* +``` + +To get the aliases for a particular item, use the Definition parameter. For +example, to get the aliases for the Get-ChildItem cmdlet type: + +```powershell +Get-Alias -Definition Get-ChildItem +``` + +### GET-ALIAS OUTPUT + +Get-Alias returns only one type of object, an AliasInfo object +(System.Management.Automation.AliasInfo). The name of aliases that don't +include a hyphen, such as "cd" are displayed in the following format: + +```powershell +PS C:\> Get-Alias ac + +CommandType Name Version Source +----------- ---- ------- ------ +Alias ac -> Add-Content +``` + +This makes it very quick and easy to get the information that you need. + +The arrow-based alias name format is not used for aliases that include a +hyphen. These are likely to be preferred substitute names for cmdlets and +functions, instead of typical abbreviations or nicknames, and the author might +not want them to be as evident. + +## ALTERNATE NAMES FOR COMMANDS WITH PARAMETERS + +You can assign an alias to a cmdlet, script, function, or executable file. You +cannot assign an alias to a command and its parameters. For example, you can +assign an alias to the `Get-Eventlog` cmdlet, but you cannot assign an alias +to the `Get-Eventlog -LogName System` command. + +You can create a function that includes the command. To create a function, +type the word "function" followed by a name for the function. Type the +command, and enclose it in braces ({}). + +For example, the following command creates the syslog function. This function +represents the `Get-Eventlog -LogName System` command: + +```powershell +function Get-SystemEventlog {Get-Eventlog -LogName System} +Set-Alias -Name syslog -Value Get-SystemEventlog +``` + +You can now type "syslog" instead of the command. And, you can create aliases +for the new function. + +For more information about functions, type: + +```powershell +Get-Help about_Functions +``` + +## ALIAS OBJECTS + +PowerShell aliases are represented by objects that are instances of the +System.Management.Automation.AliasInfo class. For more information about this +type of object, see [AliasInfo Class][aliasinfo] in the Microsoft Developer +Network (MSDN) library. + +To view the properties and methods of the alias objects, get the aliases. +Then, pipe them to the Get-Member cmdlet. For example: + +```powershell +Get-Alias | Get-Member +``` + +To view the values of the properties of a specific alias, such as the `dir` +alias, get the alias. Then, pipe it to the Format-List cmdlet. For example, +the following command gets the "dir" alias. Next, the command pipes the alias +to the Format-List cmdlet. Then, the command uses the Property parameter of +Format-List with a wildcard character (\*) to display all the properties of +the `dir` alias. The following command performs these tasks: + +```powershell +Get-Alias -Name dir | Format-List -Property * +``` + +## PowerShell ALIAS PROVIDER + +PowerShell includes the Alias provider. The Alias provider lets you view the +aliases in PowerShell as though they were on a file system drive. + +The Alias provider exposes the Alias: drive. To go into the Alias: drive, +type: + +```powershell +Set-Location Alias: +``` + +To view the contents of the drive, type: + +```powershell +Get-ChildItem +``` + +To view the contents of the drive from another PowerShell drive, begin the +path with the drive name. Include the colon (:). For example: + +```powershell +Get-ChildItem -Path Alias: +``` + +To get information about a particular alias, type the drive name and the alias +name. Or, type a name pattern. For example, to get all the aliases that begin +with "p", type: + +```powershell +Get-ChildItem -Path Alias:p* +``` + +For more information about the PowerShell Alias provider, type: + +```powershell +Get-Help Alias +``` + +## SEE ALSO + +- [New-Alias](../../Microsoft.PowerShell.Utility/New-Alias.md) +- [Get-Alias](../../Microsoft.PowerShell.Utility/Get-Alias.md) +- [Set-Alias](../../Microsoft.PowerShell.Utility/Set-Alias.md) +- [Export-Alias](../../Microsoft.PowerShell.Utility/Export-Alias.md) +- [Import-Alias](../../Microsoft.PowerShell.Utility/Import-Alias.md) +- [Get-PSProvider](../../Microsoft.PowerShell.Management/Get-PSProvider.md) +- [Get-PSDrive](../../Microsoft.PowerShell.Management/Get-PSDrive.md) +- [about_functions](about_functions.md) +- [about_profiles](about_profiles.md) +- [about_providers](about_providers.md) + + +[aliasinfo]: https://go.microsoft.com/fwlink/?LinkId=143644 \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Arithmetic_Operators.md b/reference/7/Microsoft.PowerShell.Core/About/about_Arithmetic_Operators.md new file mode 100644 index 000000000000..d9830777bf27 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Arithmetic_Operators.md @@ -0,0 +1,517 @@ +--- +ms.date: 11/27/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Arithmetic_Operators +--- +# About Arithmetic Operators + +## SHORT DESCRIPTION +Describes the operators that perform arithmetic in PowerShell. + +## LONG DESCRIPTION + +Arithmetic operators calculate numeric values. You can use one or more +arithmetic operators to add, subtract, multiply, and divide values, and to +calculate the remainder (modulus) of a division operation. + +In addition, the addition operator (`+`) and multiplication operator (`*`) +also operate on strings, arrays, and hash tables. The addition operator +concatenates the input. The multiplication operator returns multiple copies +of the input. You can even mix object types in an arithmetic statement. The +method that is used to evaluate the statement is determined by the type of +the leftmost object in the expression. + +Beginning in PowerShell 2.0, all arithmetic operators work on 64-bit +numbers. + +Beginning in PowerShell 3.0, the `-shr` (shift-right) and `-shl` +(shift-left) are added to support bitwise arithmetic in PowerShell. + +PowerShell supports the following arithmetic operators: + +|Operator|Description |Example | +|--------|----------------------------------|-----------------------------| +| + |Adds integers; concatenates |`6 + 2` | +| |strings, arrays, and hash tables. |`"file" + "name"` | +| | |`@(1, "one") + @(2.0, "two")`| +| | |`@{"one" = 1} + @{"two" = 2}`| +| - |Subtracts one value from another |`6 - 2` | +| |value | | +| - |Makes a number a negative number |`-6` | +| | |`(Get-Date).AddDays(-1)` | +| * |Multiply numbers or copy strings |`6 * 2` | +| |and arrays the specified number |`@("!") * 4` | +| |of times. |`"!" * 3` | +| / |Divides two values. |`6 / 2` | +| % |Modulus - returns the remainder of|`7 % 2` | +| |a division operation. | | +|-band |Bitwise AND |`5 -band 3` | +|-bnot |Bitwise NOT |`-bnot 5` | +|-bor |Bitwise OR |`5 -bor 0x03` | +|-bxor |Bitwise XOR |`5 -bxor 3` | +|-shl |Shifts bits to the left the |`102 -shl 2` | +| |specified number of times | | +|-shr |Shifts bits to the right |`102 -shr 2` | + +The bitwise operators only work on integer types. + +## OPERATOR PRECEDENCE + +PowerShell processes arithmetic operators in the following order: + +|Precedence|Operator |Description | +|----------|---------------|---------------------------------------| +|1 | `()` |Parentheses | +|2 | `-` |For a negative number or unary operator| +|3 | `*`, `/`, `%` |For multiplication and division | +|4 | `+`, `-` |For addition and subtraction | + +PowerShell processes the expressions from left to right according to the +precedence rules. The following examples show the effect of the precedence +rules: + +|Expression |Result| +|-----------|------| +|`3+6/3*4` |`11` | +|`3+6/(3*4)`|`3.5` | +|`(3+6)/3*4`|`12` | + +The order in which PowerShell evaluates expressions might differ from other +programming and scripting languages that you have used. The following +example shows a complicated assignment statement. + +```powershell +$a = 0 +$b = @(1,2) +$c = @(-1,-2) + +$b[$a] = $c[$a++] +``` + +In this example, the expression `$a++` is evaluated before `$b[$a]`. +Evaluating `$a++` changes the value of `$a` after it is used in the +statement `$c[$a++]`; but, before it is used in `$b[$a]`. The variable `$a` +in `$b[$a]` equals `1`, not `0`; so, the statement assigns a value to +`$b[1]`, not `$b[0]`. + +The above code is equivalent to: + +```powershell +$a = 0 +$b = @(1,2) +$c = @(-1,-2) + +$tmp = $c[$a] +$a = $a + 1 +$b[$a] = $tmp +``` + +## DIVISION AND ROUNDING + +When the quotient of a division operation is an integer, PowerShell rounds +the value to the nearest integer. When the value is `.5`, it rounds to the +nearest even integer. + +The following example shows the effect of rounding to the nearest even +integer. + +|Expression |Result| +|----------------|------| +|`[int]( 5 / 2 )`|`2` | +|`[int]( 7 / 2 )`|`4` | + +Notice how **_5/2_ = 2.5** gets rounded to **2**. But, **_7/2_ = 3.5** gets +rounded to **4**. + +## ADDING AND MULTIPLYING NON-NUMERIC TYPES + +You can add numbers, strings, arrays, and hash tables. And, you can +multiply numbers, strings, and arrays. However, you cannot multiply hash +tables. + +When you add strings, arrays, or hash tables, the elements are +concatenated. When you concatenate collections, such as arrays or hash +tables, a new object is created that contains the objects from both +collections. If you try to concatenate hash tables that have the same key, +the operation fails. + +For example, the following commands create two arrays and then add them: + +```powershell +$a = 1,2,3 +$b = "A","B","C" +$a + $b +``` + +```output +1 +2 +3 +A +B +C +``` + +You can also perform arithmetic operations on objects of different types. +The operation that PowerShell performs is determined by the Microsoft .NET +Framework type of the leftmost object in the operation. PowerShell tries to +convert all the objects in the operation to the .NET Framework type of the +first object. If it succeeds in converting the objects, it performs the +operation appropriate to the .NET Framework type of the first object. If it +fails to convert any of the objects, the operation fails. + +The following examples demonstrate the use of the addition and +multiplication operators; in operations that include different object +types. Assume `$array = 1,2,3`: + +|Expression |Result | +|-----------------|-----------------------| +|`"file" + 16` |`file16` | +|`$array + 16` |`1`,`2`,`3`,`16` | +|`$array + "file"`|`1`,`2`,`3`,`file` | +|`$array * 2` |`1`,`2`,`3`,`1`,`2`,`3`| +|`"file" * 3` |`filefilefile` | + +Because the method that is used to evaluate statements is determined by the +leftmost object, addition and multiplication in PowerShell are not strictly +commutative. For example, `(a + b)` does not always equal `(b + a)`, and +`(ab)` does not always equal `(ba)`. + +The following examples demonstrate this principle: + +|Expression |Result | +|-------------|-----------------------------------------------------| +|`"file" + 16`|`file16` | +|`16 + "file"`|`Cannot convert value "file" to type "System.Int32".`| +| |`Error: "Input string was not in a correct format."` | +| |`At line:1 char:1` | +| |+ 16 + "file"` | + +Hash tables are a slightly different case. You can add hash tables to +another hash table, as long as, the added hash tables don't have duplicate +keys. + +The following example show how to add hash tables to each other. + +```powershell +$hash1 = @{a=1; b=2; c=3} +$hash2 = @{c1="Server01"; c2="Server02"} +$hash1 + $hash2 +``` + +```output +Name Value +---- ----- +c2 Server02 +a 1 +b 2 +c1 Server01 +c 3 +``` + +The following example throws an error because one of the keys is duplicated +in both hash tables. + +```powershell +$hash1 = @{a=1; b=2; c=3} +$hash2 = @{c1="Server01"; c="Server02"} +$hash1 + $hash2 +``` + +```output +Item has already been added. Key in dictionary: 'c' Key being added: 'c' +At line:3 char:1 ++ $hash1 + $hash2 ++ ~~~~~~~~~~~~~~~ + + CategoryInfo : OperationStopped: (:) [], ArgumentException + + FullyQualifiedErrorId : System.ArgumentException +``` + +Also, you can add a hash table to an array; and, the entire hash table +becomes an item in the array. + +```powershell +$array1 = @(0, "Hello World", [datetime]::Now) +$hash1 = @{a=1; b=2} +$array2 = $array1 + $hash1 +$array2 +``` + +```output +0 +Hello World + +Monday, June 12, 2017 3:05:46 PM + +Key : a +Value : 1 +Name : a + +Key : b +Value : 2 +Name : b +``` + +However, you cannot add any other type to a hash table. + +```powershell +$hash1 + 2 +``` + +```output +A hash table can only be added to another hash table. +At line:3 char:1 ++ $hash1 + 2 +``` + +Although the addition operators are very useful, use the assignment +operators to add elements to hash tables and arrays. For more information +see [about_assignment_operators](about_Assignment_Operators.md). The +following examples use the `+=` assignment operator to add items to an +array: + +```powershell +$array = @() +(0..9).foreach{ $array += $_ } +$array +``` + +```output +0 +1 +2 +``` + +## TYPE CONVERSION TO ACCOMMODATE RESULT + +PowerShell automatically selects the .NET Framework numeric type that best +expresses the result without losing precision. For example: + +```powershell +2 + 3.1 + +(2). GetType().FullName +(2 + 3.1).GetType().FullName +``` + +```output +5.1 +System.Int32 +System.Double +``` + +If the result of an operation is too large for the type, the type of the +result is widened to accommodate the result, as in the following example: + +```powershell +(512MB).GetType().FullName +(512MB * 512MB).GetType().FullName +``` + +```output +System.Int32 +System.Double +``` + +The type of the result will not necessarily be the same as one of the +operands. In the following example, the negative value cannot be cast to an +unsigned integer, and the unsigned integer is too large to be cast to +`Int32`: + +```powershell +([int32]::minvalue + [uint32]::maxvalue).gettype().fullname +``` + +```output +System.Int64 +``` + +In this example, `Int64` can accommodate both types. + +The `System.Decimal` type is an exception. If either operand has the +Decimal type, the result will be of the Decimal type. If the result is too +large for the Decimal type, it will not be cast to Double. Instead, an +error results. + +|Expression |Result | +|-------------------------|-----------------------------------------------| +|`[Decimal]::maxvalue` |`79228162514264337593543950335` | +|`[Decimal]::maxvalue + 1`|`Value was either too large or too small for a`| +| |`Decimal.` | + +## ARITHMETIC OPERATORS AND VARIABLES + +You can also use arithmetic operators with variables. The operators act on +the values of the variables. The following examples demonstrate the use of +arithmetic operators with variables: + +| Expression |Result | +|-----------------------------------------------|------------| +|`$intA = 6`
`$intB = 4`
`$intA + $intB`|`10` | +|`$a = "Power"`
`$b = "Shell"`
`$a + $b`|`PowerShell`| + +## ARITHMETIC OPERATORS AND COMMANDS + +Typically, you use the arithmetic operators in expressions with numbers, +strings, and arrays. However, you can also use arithmetic operators with +the objects that commands return and with the properties of those objects. + +The following examples show how to use the arithmetic operators in +expressions with PowerShell commands: + +```powershell +(get-date) + (new-timespan -day 1) +``` + +The parenthesis operator forces the evaluation of the `get-date` cmdlet and +the evaluation of the `new-timespan -day 1` cmdlet expression, in that +order. Both results are then added using the `+` operator. + +```powershell +Get-Process | Where-Object { ($_.ws * 2) -gt 50mb } +``` + +```output +Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName +------- ------ ----- ----- ----- ------ -- ----------- + 1896 39 50968 30620 264 1,572.55 1104 explorer + 12802 78 188468 81032 753 3,676.39 5676 OUTLOOK + 660 9 36168 26956 143 12.20 988 PowerShell + 561 14 6592 28144 110 1,010.09 496 services + 3476 80 34664 26092 234 ...45.69 876 svchost + 967 30 58804 59496 416 930.97 2508 WINWORD +``` + +In the above expression, each process working space (`$_.ws`) is multiplied +by `2`; and, the result, compared against `50mb` to see if it is greater +than that. + +## Bitwise Operators + +PowerShell supports the standard bitwise operators, including bitwise-AND +(`-bAnd`), the inclusive and exclusive bitwise-OR operators (`-bOr` and +`-bXor`), and bitwise-NOT (`-bNot`). + +Beginning in PowerShell 2.0, all bitwise operators work with 64-bit +integers. + +Beginning in PowerShell 3.0, the `-shr` (shift-right) and `-shl` +(shift-left) are introduced to support bitwise arithmetic in PowerShell. + +PowerShell supports the following bitwise operators. + +| Operator | Description | Expression | Result | +| -------- | ---------------------- | ------------ | ------ | +| `-band` | Bitwise AND | `10 -band 3` | 2 | +| `-bor` | Bitwise OR (inclusive) | `10 -bor 3` | 11 | +| `-bxor` | Bitwise OR (exclusive) | `10 -bxor 3` | 9 | +| `-bnot` | Bitwise NOT | `-bNot 10` | -11 | +| `-shl` | Shift-left | `102 -shl 2` | 408 | +| `-shr` | Shift-right | `102 -shr 1` | 51 | + +Bitwise operators act on the binary format of a value. For example, the bit +structure for the number 10 is 00001010 (based on 1 byte), and the bit +structure for the number 3 is 00000011. When you use a bitwise operator to +compare 10 to 3, the individual bits in each byte are compared. + +In a bitwise AND operation, the resulting bit is set to 1 only when both +input bits are 1. + +``` +1010 (10) +0011 ( 3) +-------------- bAND +0010 ( 2) +``` + +In a bitwise OR (inclusive) operation, the resulting bit is set to 1 when +either or both input bits are 1. The resulting bit is set to 0 only when +both input bits are set to 0. + +``` +1010 (10) +0011 ( 3) +-------------- bOR (inclusive) +1011 (11) +``` + +In a bitwise OR (exclusive) operation, the resulting bit is set to 1 only +when one input bit is 1. + +``` +1010 (10) +0011 ( 3) +-------------- bXOR (exclusive) +1001 ( 9) +``` + +The bitwise NOT operator is a unary operator that produces the binary +complement of the value. A bit of 1 is set to 0 and a bit of 0 is set to 1. + +For example, the binary complement of 0 is -1, the maximum unsigned integer +(0xffffffff), and the binary complement of -1 is 0. + +```powershell +PS C:\> -bNot 10 +-11 +``` + +``` +0000 0000 0000 1010 (10) +------------------------- bNOT +1111 1111 1111 0101 (-11, xfffffff5) +``` + +In a bitwise shift-left operation, all bits are moved "n" places to the +left, where "n" is the value of the right operand. A zero is inserted in +the ones place. + +When the left operand is an Integer (32-bit) value, the lower 5 bits of the +right operand determine how many bits of the left operand are shifted. + +When the left operand is a Long (64-bit) value, the lower 6 bits of the +right operand determine how many bits of the left operand are shifted. + +|Expression |Result|Binary Result| +|-----------|------|-------------| +|`21 -shl 0`|21 |0001 0101 | +|`21 -shl 1`|42 |0010 1010 | +|`21 -shl 2`|84 |0101 0100 | + +In a bitwise shift-right operation, all bits are moved "n" places to the +right, where "n" is specified by the right operand. The shift-right +operator (-shr) inserts a zero in the left-most place when shifting a +positive or unsigned value to the right. + +When the left operand is an Integer (32-bit) value, the lower 5 bits of the +right operand determine how many bits of the left operand are shifted. + +When the left operand is a Long (64-bit) value, the lower 6 bits of the +right operand determine how many bits of the left operand are shifted. + +|Expression |Result |Binary |Hex | +|------------------------|------------|-----------|------------| +|`21 -shr 0` | 21 | 0001 0101 | 0x15 | +|`21 -shr 1` | 10 | 0000 1010 | 0x0A | +|`21 -shr 2` | 5 | 0000 0101 | 0x05 | +|`21 -shr 31` | 0 | 0000 0000 | 0x00 | +|`21 -shr 32` | 21 | 0001 0101 | 0x15 | +|`21 -shr 64` | 21 | 0001 0101 | 0x15 | +|`21 -shr 65` | 10 | 0000 1010 | 0x0A | +|`21 -shr 66` | 5 | 0000 0101 | 0x05 | +|`[int]::MaxValue -shr 1`| 1073741823 | | 0x3FFFFFFF | +|`[int]::MinValue -shr 1`| -1073741824| | 0xC0000000 | +|`-1 -shr 1` | -1 | | 0xFFFFFFFF | + +## SEE ALSO + +* [about_arrays](about_Arrays.md) +* [about_assignment_operators](about_Assignment_Operators.md) +* [about_comparison_operators](about_Comparison_Operators.md) +* [about_hash_tables](about_Hash_Tables.md) +* [about_operators](about_Operators.md) +* [about_variables](about_Variables.md) +* [Get-Date](../../Microsoft.PowerShell.Utility/Get-Date.md) +* [New-TimeSpan](../../Microsoft.PowerShell.Utility/New-TimeSpan.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Arrays.md b/reference/7/Microsoft.PowerShell.Core/About/about_Arrays.md new file mode 100644 index 000000000000..f2e45ff7c219 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Arrays.md @@ -0,0 +1,829 @@ +--- +ms.date: 06/09/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Arrays +--- +# About Arrays + +## Short Description +Describes arrays, which are data structures designed to store +collections of items. + +## Long Description + +An array is a data structure that is designed to store a collection of items. +The items can be the same type or different types. + +Beginning in Windows PowerShell 3.0, a collection of zero or one object has +some properties of arrays. + +## Creating and initializing an array + +To create and initialize an array, assign multiple values to a variable. The +values stored in the array are delimited with a comma and separated from the +variable name by the assignment operator (=). + +For example, to create an array named $A that contains the seven numeric (int) +values of 22, 5, 10, 8, 12, 9, and 80, type: + +```powershell +$A = 22,5,10,8,12,9,80 +``` + +You can also create and initialize an array by using the range operator (..). +For example, to create and initialize an array named "$B" that contains the +values 5 through 8, type: + +```powershell +$B = 5..8 +``` + +As a result, $B contains four values: 5, 6, 7, and 8. + +When no data type is specified, PowerShell creates each array as an +object array (type: System.Object[]). To determine the data type of an array, +use the GetType() method. For example, to determine the data type of the $a +array, type: + +```powershell +$a.GetType() +``` + +To create a strongly typed array, that is, an array that can contain only +values of a particular type, cast the variable as an array type, such as +string[], long[], or int32[]. To cast an array, precede the variable name with +an array type enclosed in brackets. For example, to create a 32-bit integer +array named $ia containing four integers (1500, 2230, 3350, and 4000), type: + +```powershell +[int32[]]$ia = 1500,2230,3350,4000 +``` + +As a result, the $ia array can contain only integers. + +You can create arrays that are cast to any supported type in the Microsoft +.NET Framework. For example, the objects that Get-Process retrieves to +represent processes are of the System.Diagnostics.Process type. To create a +strongly typed array of process objects, enter the following command: + +```powershell +[Diagnostics.Process[]]$zz = Get-Process +``` + +## The array sub-expression operator + +The array sub-expression operator creates an array, even if it contains zero +or one object. + +The syntax of the array operator is as follows: + +```syntax +@( ... ) +``` + +You can use the array operator to create an array of zero or one object. For +example: + +```powershell +PS> $a = @("Hello World") +PS> $a.Count +1 +``` + +```powershell +PS> $b = @() +PS> $b.Count +0 +``` + +The array operator is particularly useful in scripts when you are getting +objects, but do not know how many objects you will get. For example: + +```powershell +$p = @(Get-Process Notepad) +``` + +For more information about the array sub-expression operator, see +about_Operators. + +## Accessing and using array elements + +### Reading an array + +You can refer to an array by using its variable name. To display all the +elements in the array, type the array name. For example, assuming `$a` is an +array containing integers 0, 1, 2, until 9; typing: + +```powershell +$a +``` + +```output +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +``` + +You can refer to the elements in an array by using an index, beginning at +position 0. Enclose the index number in brackets. For example, to display the +first element in the `$a` array, type: + +```powershell +$a[0] +``` + +```output +0 +``` + +To display the third element in the `$a` array, type: + +```powershell +$a[2] +``` + +```output +2 +``` + +You can retrieve part of the array using a range operator for the index. For +example, to retrieve the second to fifth elements of the array, you would +type: + +```powershell +$a[1..4] +``` + +```output +1 +2 +3 +4 +``` + +Negative numbers count from the end of the array. For example, "-1" refers to +the last element of the array. To display the last three elements of the +array, in index ascending order, type: + +```powershell +$a = 0 .. 9 +$a[-3..-1] +``` + +```output +7 +8 +9 +``` + +If you type negative indexes in descending order, your output changes. + +```powershell +$a = 0 .. 9 +$a[-1..-3] +``` + +```output +9 +8 +7 +``` + +However, be cautious when using this notation. The notation cycles from the +end boundary to the beginning of the array. + +```powershell +$a = 0 .. 9 +$a[2..-2] +``` + +```output +2 +1 +0 +9 +8 +``` + +Also, one common mistake is to assume `$a[0..-2]` refers to all the elements +of the array, except for the last one. It refers to the first, last, and +second-to-last elements in the array. + +You can use the plus operator (+) to combine a ranges with a list of elements +in an array. For example, to display the elements at index positions 0, 2, and +4 through 6, type: + +```powershell +$a = 0 .. 9 +$a[0,2+4..6] +``` + +```output +0 +2 +4 +5 +6 +``` + +Also, to list multiple ranges and individual elements you can use the plus +operator. For example, to list elements zero to two, four to six, and the +element at eighth positional type: + +```powershell +$a = 0..9 +$a[+0..2+4..6+8] +``` + +```output +0 +1 +2 +4 +5 +6 +8 +``` + +### Iterations over array elements + +You can also use looping constructs, such as ForEach, For, and While loops, to +refer to the elements in an array. For example, to use a ForEach loop to +display the elements in the `$a` array, type: + +```powershell +$a = 0..9 +foreach ($element in $a) { + $element +} +``` + +```output +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +``` + +The Foreach loop iterates through the array and returns each value in the +array until reaching the end of the array. + +The For loop is useful when you are incrementing counters while examining the +elements in an array. For example, to use a For loop to return every other +value in an array, type: + +```powershell +$a = 0..9 +for ($i = 0; $i -le ($a.length - 1); $i += 2) { + $a[$i] +} +``` + +```output +0 +2 +4 +6 +8 +``` + +You can use a While loop to display the elements in an array until a defined +condition is no longer true. For example, to display the elements in the `$a` +array while the array index is less than 4, type: + +```powershell +$a = 0..9 +$i=0 +while($i -lt 4) { + $a[$i]; + $i++ +} +``` + +```output +0 +1 +2 +3 +``` + +## Properties of arrays + +### Count or Length or LongLength + +To determine how many items are in an array, use the `Length` property or its +`Count` alias. `Longlength` is useful if the array contains more than +2,147,483,647 elements. + +```powershell +$a = 0..9 +$a.Count +$a.Length +``` + +```output +10 +10 +``` + +### Rank + +Returns the number of dimensions in the array. Most arrays in PowerShell have +one dimension, only. Even when you think you are building a multidimensional +array; like the following example: + +```powershell +$a = @( + @(0,1), + @("b", "c"), + @(Get-Process) +) + +[int]$r = $a.Rank +"`$a rank: $r" +``` + +```output +$a rank: 1 +``` + +Building a truly multidimensional array, in PowerShell, requires the +assistance of the *.Net Framework*. Like in the following example: + +```powershell +[int[,]]$rank2 = [int[,]]::new(5,5) +$rank2.rank +``` + +```output +2 +``` + +## Methods of arrays + +### Clear + +Sets all element values to the _default value_ of the array's element type. +The Clear() method does not reset the size of the array. + +In the following example `$a` is an array of objects. + +```powershell +$a = 1, 2, 3 +$a.Clear() +$a | % { $null -eq $_ } +``` + +```output +True +True +True +``` + +In this example, `$intA` is explicitly typed to contain integers. + +```powershell +[int[]] $intA = 1, 2, 3 +$intA.Clear() +$intA +``` + +```output +0 +0 +0 +``` + +### ForEach + +Allows to iterate over all elements in the array and perform a given operation +for each element of the array. + +The ForEach method has several overloads that perform different operations. + +``` +ForEach(scriptblock expression) +ForEach(type convertToType) +ForEach(string propertyName) +ForEach(string propertyName, object[] newValue) +ForEach(string methodName) +ForEach(string methodName, object[] arguments) +ForEach(scriptblock expression, object[] arguments) +``` + +#### ForEach(scriptblock expression) + +#### ForEach(scriptblock expression, object[] arguments) + +> [!NOTE] +> The syntax requires the usage of a script block. Parentheses are optional. + +The following example shows how use the foreach method. In this case the +intent is to generate the square value of the elements in the array. + +Please note this method was added in PowerShell v4 and is not available in versions below this. +For prior versions please use the Pipelining method to the ForEach-Object Cmdlet + +```powershell +$a = @(0 .. 3) +$a.ForEach({ $_ * $_}) +``` + +```output +0 +1 +4 +9 +``` + +Just like the `-ArgumentList` parameter of `ForEach-Object`, the `arguments` +parameter allows the passing of an array of arguments to a script block +configured to accept them. + +#### ForEach(type convertToType) + +The `ForEach` method can be used to swiftly cast the elements to a different +type; the following example shows how to convert a list of string dates to +`[DateTime]` type. + +```powershell +@("1/1/2017", "2/1/2017", "3/1/2017").ForEach([datetime]) +``` + +```output + +Sunday, January 1, 2017 12:00:00 AM +Wednesday, February 1, 2017 12:00:00 AM +Wednesday, March 1, 2017 12:00:00 AM +``` + +#### ForEach(string propertyName) + +#### ForEach(string propertyName, object[] newValue) + +The `ForEach` method can also be used to quickly retrieve, or set property +values for every item in the collection. + +```powershell +# Set all LastAccessTime properties of files to the current date. +(dir 'C:\Temp').ForEach('LastAccessTime', (Get-Date)) +# View the newly set LastAccessTime of all items, and find Unique entries. +(dir 'C:\Temp').ForEach('LastAccessTime') | Get-Unique +``` + +```output +Wednesday, June 20, 2018 9:21:57 AM +``` + +#### ForEach(string methodName) + +#### ForEach(string methodName, object[] arguments) + +Lastly, `ForEach` methods can be used to execute a method on every item in +the collection. + +```powershell +("one", "two", "three").ForEach("ToUpper") +``` + +```output +ONE +TWO +THREE +``` + +Just like the `-ArgumentList` parameter of `ForEach-Object`, the `arguments` +parameter allows the passing of an array of arguments to a script block +configured to accept them. + +> [!NOTE] +> Starting in Windows PowerShell 3.0 retrieving properties and executing +methods for each item in a collection can also be accomplished using +> "Methods of scalar objects and collections" +> You can read more about that here [about_methods](about_methods.md) + +### Where + +Allows to filter or select the elements of the array. The script must evaluate +to anything different than: zero (0), empty string, `$false` or `$null` for +the element to show after the `Where` + +There is one definition for the `Where` method. + +``` +Where(scriptblock expression[, WhereOperatorSelectionMode mode + [, int numberToReturn]]) +``` + +The `Expression` is scriptblock that is required for filtering, the `mode` +optional argument allows additional selection capabilities, and the +`numberToReturn` optional argument allows the ability to limit how many items +are returned from the filter. + +> [!NOTE] +> The syntax requires the usage of a script block. Parentheses are optional. + +The following example shows how to select all odd numbers from the array. + +```powershell +(0..9).Where{ $_ % 2 } +``` + +```output +1 +3 +5 +7 +9 +``` + +The following selection modes are available. + +#### Default + +The `Default` mode filters items using the `Expression` scriptblock. + +If a `numberToReturn` is provided, it specifies the maximum number of items +to return. + +```powershell +# Get the zip files in the current users profile, sorted by LastAccessTime. +$Zips = dir $env:userprofile -Recurse '*.zip' | Sort-Object LastAccessTime +# Get the least accessed file over 100MB +$Zips.Where({$_.Length -gt 100MB}, 'Default', 1) +``` + +> [!NOTE] +> Both the `Default` mode and `First` mode return the first +> (`numberToReturn`) items, and can be used interchangeably. + +#### Last + +```powershell +$h = (Get-Date).AddHours(-1) +$logs = dir 'C:\' -Recurse '*.log' | Sort-Object CreationTime +# Find the last 5 log files created in the past hour. +$logs.Where({$_.CreationTime -gt $h}, 'Last', 5) +``` + +#### SkipUntil + +The `SkipUntil` mode skips all objects in a collection until an object passes +the script block expression filter. It then returns **ALL** remaining collection +items without testing them. *Only one passing item is tested* + +This means the returned collection will contain both *passing* and +*non-passing* items that have NOT been tested. + +The number of items returned can be limited by passing a value to the +`numberToReturn` argument. + +```powershell +$computers = "Server01", "Server02", "Server03", "localhost", "Server04" +# Find the first available online server. +$computers.Where({ Test-Connection $_ }, 'SkipUntil', 1) +``` + +```output +localhost +``` + +### Until + +The `Until` mode inverts the `SkipUntil` mode. It returns **ALL** items in a +collection until an item passes the script block expression. Once an item +*passes* the scriptblock expression, the `Where` method stops processing items. + +This means that you will receive the first set of *non-passing* items from the +`Where` method. *After* one item passes, the rest will NOT be tested nor +returned. + +The number of items returned can be limited by passing a value to the +`numberToReturn` argument. + +```powershell +# Retrieve the first set of numbers less than or equal to 10. +(1..50).Where({$_ -gt 10}, 'Until') +# This would perform the same operation. +(1..50).Where({$_ -le 10}) +``` + +```output +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +``` + +> [!NOTE] +> Both `Until` and `SkipUntil` operate under the premise of NOT testing a batch +> of items. +> +> `Until` returns the items **BEFORE** the first *pass*. +> +> `SkipUntil` returns all the items **AFTER** the first *pass*, including the +> first passing item. + +#### Split + +The `Split` mode splits, or groups collection items into two separate +collections. Those that pass the scriptblock expression, and those that do not. + +If a `numberToReturn` is specified, the first collection, will contain the +*passing* items, not to exceed the value specified. + +The remaining objects, even those that **PASS** the expression filter, will be +returned in the second collection. + +```powershell +$running, $stopped = (Get-Service).Where({$_.Status -eq 'Running'}, 'Split') +$running +``` + +```output +Status Name DisplayName +------ ---- ----------- +Running Appinfo Application Information +Running AudioEndpointBu... Windows Audio Endpoint Builder +Running Audiosrv Windows Audio +... +``` + +```powershell +$stopped +``` + +```output +Status Name DisplayName +------ ---- ----------- +Stopped AJRouter AllJoyn Router Service +Stopped ALG Application Layer Gateway Service +Stopped AppIDSvc Application Identity +... +``` + +## Get the members of an array + +To get the properties and methods of an array, such as the Length property and +the SetValue method, use the InputObject parameter of the Get-Member cmdlet. + +When you pipe an array to `Get-Member`, PowerShell sends the items one +at a time and `Get-Member` returns the type of each item in the array (ignoring +duplicates). + +When you use the *-InputObject* parameter, `Get-Member` returns the members of +the array. + +For example, the following command gets the members of the `$a` array +variable. + +```powershell +Get-Member -InputObject $a +``` + +You can also get the members of an array by typing a comma (,) before the +value that is piped to the Get-Member cmdlet. The comma makes the array the +second item in an array of arrays. Windows PowerShell pipes the arrays one at +a time and Get-Member returns the members of the array. Like the next two +examples. + +```powershell +,$a | Get-Member + +,(1,2,3) | Get-Member +``` + +## Manipulating an array + +You can change the elements in an array, add an element to an array, and +combine the values from two arrays into a third array. + +To change the value of a particular element in an array, specify the array +name and the index of the element that you want to change, and then use the +assignment operator (=) to specify a new value for the element. For example, +to change the value of the second item in the `$a` array (index position 1) to +10, type: + +```powershell +$a[1] = 10 +``` + +You can also use the SetValue method of an array to change a value. The +following example changes the second value (index position 1) of the `$a` array +to 500: + +```powershell +$a.SetValue(500,1) +``` + +You can use the += operator to add an element to an array. The following +example shows how to add an element to the `$a` array. + +```powershell +$a = @(0..4) +$a += 5 +``` + +> [!NOTE] +> When you use the `+=` operator, PowerShell actually creates a new array +> with the values of the original array and the added value. This might +> cause performance issues if the operation is repeated several times or +> the size of the array is too big. + +It is not easy to delete elements from an array, but you can create a new +array that contains only selected elements of an existing array. For example, +to create the `$t` array with all the elements in the `$a` array except for the +value at index position 2, type: + +```powershell +$t = $a[0,1 + 3..($a.length - 1)] +``` + +To combine two arrays into a single array, use the plus operator (+). The +following example creates two arrays, combines them, and then displays the +resulting combined array. + +```powershell +$x = 1,3 +$y = 5,9 +$z = $x + $y +``` + +As a result, the `$z` array contains 1, 3, 5, and 9. + +To delete an array, assign a value of $null to the array. The following +command deletes the array in the `$a` variable. + +`$a = $null` + +You can also use the `Remove-Item` cmdlet, but assigning a value of `$null` is +faster, especially for large arrays. + +## Arrays of zero or one + +Beginning in Windows PowerShell 3.0, a collection of zero or one object has +the Count and Length property. Also, you can index into an array of one +object. This feature helps you to avoid scripting errors that occur when a +command that expects a collection gets fewer than two items. + +The following examples demonstrate this feature. + +## Zero objects + +```powershell +$a = $null +$a.Count +$a.Length +``` + +```output +0 +0 +``` + +## One object + +```powershell +$a = 4 +$a.Count +$a.Length +$a[0] +$a[-1] +``` + +```output +1 +1 +4 +4 +``` + +## See also + +- [about_Assignment_Operators](about_Assignment_Operators.md) +- [about_Hash_Tables](about_Hash_Tables.md) +- [about_Operators](about_Operators.md) +- [about_For](about_For.md) +- [about_Foreach](about_Foreach.md) +- [about_While](about_While.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Assignment_Operators.md b/reference/7/Microsoft.PowerShell.Core/About/about_Assignment_Operators.md new file mode 100644 index 000000000000..f3bfa3d8fcc6 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Assignment_Operators.md @@ -0,0 +1,872 @@ +--- +ms.date: 11/27/2017 +schema: 2.0.0 +keywords: powershell,cmdlet +title: about_Assignment_Operators +--- +# About Assignment Operators + +## SHORT DESCRIPTION +Describes how to use operators to assign values to variables. + +## LONG DESCRIPTION + +Assignment operators assign one or more values to a variable. They can +perform numeric operations on the values before the assignment. + +PowerShell supports the following assignment operators. + +|Operator|Description | +|--------|-------------------------------------------------------------| +|= |Sets the value of a variable to the specified value. | +|+= |Increases the value of a variable by the specified value, or | +| |appends the specified value to the existing value. | +|-= |Decreases the value of a variable by the specified value. | +|*= |Multiplies the value of a variable by the specified value, or| +| |appends the specified value to the existing value. | +|/= |Divides the value of a variable by the specified value. | +|%= |Divides the value of a variable by the specified value and | +| |then assigns the remainder (modulus) to the variable. | +|++ |Increases the value of a variable, assignable property, or | +| |array element by 1. | +|-- |Decreases the value of a variable, assignable property, or | +| |array element by 1. | + +## SYNTAX + +The syntax of the assignment operators is as follows: + +`` `` `` + +Assignable expressions include variables and properties. The value can be a +single value, an array of values, or a command, expression, or statement. + +The increment and decrement operators are unary operators. Each has prefix +and postfix versions. + +`` +`` + +The assignable expression must be a number or it must be convertible to a +number. + +## ASSIGNING VALUES + +Variables are named memory spaces that store values. You store the values +in variables by using the assignment operator `=`. The new value can +replace the existing value of the variable, or you can append a new value +to the existing value. + +The basic assignment operator is the equal sign `=` `(ASCII 61)`. For +example, the following statement assigns the value PowerShell to +the $MyShell variable: + +```powershell +$MyShell = "PowerShell" +``` + +When you assign a value to a variable in PowerShell, the variable +is created if it did not already exist. For example, the first of the +following two assignement statements creates the $a variable and assigns a +value of 6 to $a. The second assignment statement assigns a value of 12 to +$a. The first statement creates a new variable. The second statement +changes only its value: + +```powershell +$a = 6 +$a = 12 +``` + +Variables in PowerShell do not have a specific data type unless you +cast them. When a variable contains only one object, the variable takes the +data type of that object. When a variable contains a collection of objects, +the variable has the System.Object data type. Therefore, you can assign any +type of object to the collection. The following example shows that you can +add process objects, service objects, strings, and integers to a variable +without generating an error: + +```powershell +$a = Get-Process +$a += Get-Service +$a += "string" +$a += 12 +``` + +Because the assignment operator `=` has a lower precedence than the +pipeline operator `|`, parentheses are not required to assign the result of +a command pipeline to a variable. For example, the following command sorts +the services on the computer and then assigns the sorted services to the $a +variable: + +```powershell +$a = Get-Service | Sort-Object -Property name +``` + +You can also assign the value created by a statement to a variable, as in +the following example: + +```powershell +$a = if ($b -lt 0) { 0 } else { $b } +``` + +This example assigns zero to the $a variable if the value of $b is less than +zero. It assigns the value of $b to $a if the value of $b is not less than +zero. + +### THE ASSIGNMENT OPERATOR + +The assignment operator `=` assigns values to variables. If the variable +already has a value, the assignment operator `=` replaces the value without +warning. + +The following statement assigns the integer value 6 to the $a variable: + +```powershell +$a = 6 +``` + +To assign a string value to a variable, enclose the string value in +quotation marks, as follows: + +```powershell +$a = "baseball" +``` + +To assign an array (multiple values) to a variable, separate the values +with commas, as follows: + +```powershell +$a = "apple", "orange", "lemon", "grape" +``` + +To assign a hash table to a variable, use the standard hash table notation +in PowerShell. Type an at sign `@` followed by key/value pairs that +are separated by semicolons `;` and enclosed in braces `{ }`. For example, +to assign a hash table to the $a variable, type: + +```powershell +$a = @{one=1; two=2; three=3} +``` + +To assign hexadecimal values to a variable, precede the value with `0x`. +PowerShell converts the hexadecimal value (0x10) to a decimal value +(in this case, 16) and assigns that value to the $a variable. For example, +to assign a value of 0x10 to the $a variable, type: + +```powershell +$a = 0x10 +``` + +To assign an exponential value to a variable, type the root number, the +letter `e`, and a number that represents a multiple of 10. For example, to +assign a value of 3.1415 to the power of 1,000 to the $a variable, type: + +```powershell +$a = 3.1415e3 +``` + +PowerShell can also convert kilobytes `KB`, megabytes `MB`, and +gigabytes `GB` into bytes. For example, to assign a value of 10 kilobytes +to the $a variable, type: + +```powershell +$a = 10kb +``` + +### THE ASSIGNMENT BY ADDITION OPERATOR + +The assignment by addition operator `+=` either increments the value of a +variable or appends the specified value to the existing value. The action +depends on whether the variable has a numeric or string type and whether +the variable contains a single value (a scalar) or multiple values (a +collection). + +The `+=` operator combines two operations. First, it adds, and then it +assigns. Therefore, the following statements are equivalent: + +```powershell +$a += 2 +$a = ($a + 2) +``` + +When the variable contains a single numeric value, the `+=` operator +increments the existing value by the amount on the right side of the +operator. Then, the operator assigns the resulting value to the variable. +The following example shows how to use the `+=` operator to increase the +value of a variable: + +```powershell +$a = 4 +$a += 2 +$a +``` + +``` +6 +``` + +When the value of the variable is a string, the value on the right side of +the operator is appended to the string, as follows: + +```powershell +$a = "Windows" +$a += " PowerShell" +$a +``` + +``` +Windows PowerShell +``` + +When the value of the variable is an array, the `+=` operator appends the +values on the right side of the operator to the array. Unless the array is +explicitly typed by casting, you can append any type of value to the array, +as follows: + +```powershell +$a = 1,2,3 +$a += 2 +$a +``` + +``` +1 +2 +3 +2 +``` + +and + +```powershell +$a += "String" +$a +``` + +``` +1 +2 +3 +2 +String +``` + +When the value of a variable is a hash table, the `+=` operator appends the +value on the right side of the operator to the hash table. However, because +the only type that you can add to a hash table is another hash table, all +other assignments fail. + +For example, the following command assigns a hash table to the $a variable. +Then, it uses the `+=` operator to append another hash table to the +existing hash table, effectively adding a new key/value pair to the +existing hash table. This command succeeds, as shown in the output: + +```powershell +$a = @{a = 1; b = 2; c = 3} +$a += @{mode = "write"} +$a +``` + +``` +Name Value +---- ----- +a 1 +b 2 +mode write +c 3 +``` + +The following command attempts to append an integer "1" to the hash table +in the $a variable. This command fails: + +```powershell +$a = @{a = 1; b = 2; c = 3} +$a += 1 +``` + +``` +You can add another hash table only to a hash table. +At line:1 char:6 ++ $a += <<<< 1 +``` + +### THE ASSIGNMENT BY SUBTRACTION OPERATOR + +The assignment by subtraction operator `-=` decrements the value of a +variable by the value that is specified on the right side of the operator. +This operator cannot be used with string variables, and it cannot be used +to remove an element from a collection. + +The `-=` operator combines two operations. First, it subtracts, and then it +assigns. Therefore, the following statements are equivalent: + +```powershell +$a -= 2 +$a = ($a - 2) +``` + +The following example shows how to use of the `-=` operator to decrease the +value of a variable: + +```powershell +$a = 8 +$a -= 2 +$a +``` + +``` +6 +``` + +You can also use the `-=` assignment operator to decrease the value of a +member of a numeric array. To do this, specify the index of the array +element that you want to change. In the following example, the value of the +third element of an array (element 2) is decreased by 1: + +```powershell +$a = 1,2,3 +$a[2] -= 1 +$a +``` + +``` +1 +2 +2 +``` + +You cannot use the `-=` operator to delete the values of a variable. To +delete all the values that are assigned to a variable, use the +[Clear-Item](../../Microsoft.PowerShell.Management/Clear-Item.md) or +[Clear-Variable](../../Microsoft.PowerShell.Utility/Clear-Variable.md) +cmdlets to assign a value of `$null` or `""` to the variable. + +```powershell +$a = $null +``` + +To delete a particular value from an array, use array notation to assign a +value of `$null` to the particular item. For example, the following +statement deletes the second value (index position 1) from an array: + +```powershell +$a = 1,2,3 +$a +``` + +``` +1 +2 +3 +``` + +```powershell +$a[1] = $null +$a +``` + +``` +1 +3 +``` + +To delete a variable, use the +[Remove-Variable](../../Microsoft.PowerShell.Utility/Remove-Variable.md) +cmdlet. This method is useful when the variable is explicitly cast to a +particular data type, and you want an untyped variable. The following +command deletes the $a variable: + +```powershell +Remove-Variable -Name a +``` + +### THE ASSIGNMENT BY MULTIPLICATION OPERATOR + +The assignment by multiplication operator `*=` multiplies a numeric value +or appends the specified number of copies of the string value of a +variable. + +When a variable contains a single numeric value, that value is multiplied +by the value on the right side of the operator. For example, the following +example shows how to use the `*=` operator to multiply the value of a +variable: + +```powershell +$a = 3 +$a *= 4 +$a +``` + +``` +12 +``` + +In this case, the `*=` operator combines two operations. First, it +multiplies, and then it assigns. Therefore, the following statements are +equivalent: + +```powershell +$a *= 2 +$a = ($a * 2) +``` + +When a variable contains a string value, PowerShell appends the +specified number of strings to the value, as follows: + +```powershell +$a = "file" +$a *= 4 +$a +``` + +``` +filefilefilefile +``` + +To multiply an element of an array, use an index to identify the element +that you want to multiply. For example, the following command multiplies +the first element in the array (index position 0) by 2: + +```powershell +$a[0] *= 2 +``` + +### THE ASSIGNMENT BY DIVISION OPERATOR + +The assignment by division operator `/=` divides a numeric value by the +value that is specified on the right side of the operator. The operator +cannot be used with string variables. + +The `/=` operator combines two operations. First, it divides, and then it +assigns. Therefore, the following two statements are equivalent: + +```powershell +$a /= 2 +$a = ($a / 2) +``` + +For example, the following command uses the `/=` operator to divide the +value of a variable: + +```powershell +$a = 8 +$a /=2 +$a +``` + +``` +4 +``` + +To divide an element of an array, use an index to identify the element that +you want to change. For example, the following command divides the second +element in the array (index position 1) by 2: + +```powershell +$a[1] /= 2 +``` + +### THE ASSIGNMENT BY MODULUS OPERATOR + +The assignment by modulus operator `%=` divides the value of a variable by +the value on the right side of the operator. Then, the `%=` operator +assigns the remainder (known as the modulus) to the variable. You can use +this operator only when a variable contains a single numeric value. You +cannot use this operator when a variable contains a string variable or an +array. + +The `%=` operator combines two operations. First, it divides and determines +the remainder, and then it assigns the remainder to the variable. +Therefore, the following statements are equivalent: + +```powershell +$a %= 2 +$a = ($a % 2) +``` + +The following example shows how to use the `%=` operator to save the +modulus of a quotient: + +```powershell +$a = 7 +$a %= 4 +$a +``` + +``` +3 +``` + +## THE INCREMENT AND DECREMENT OPERATORS + +The increment operator `++` increases the value of a variable by 1. When +you use the increment operator in a simple statement, no value is returned. +To view the result, display the value of the variable, as follows: + +```powershell +$a = 7 +++$a +$a +``` + +``` +8 +``` + +To force a value to be returned, enclose the variable and the operator in +parentheses, as follows: + +```powershell +$a = 7 +(++$a) +``` + +``` +8 +``` + +The increment operator can be placed before (prefix) or after (postfix) a +variable. The prefix version of the operator increments a variable before +its value is used in the statement, as follows: + +```powershell +$a = 7 +$c = ++$a +$a +``` + +``` +8 +``` + +```powershell +$c +``` + +``` +8 +``` + +The postfix version of the operator increments a variable after its value +is used in the statement. In the following example, the $c and $a variables +have different values because the value is assigned to $c before $a +changes: + +```powershell +$a = 7 +$c = $a++ +$a +``` + +``` +8 +``` + +```powershell +$c +``` + +``` +7 +``` + +The decrement operator `--` decreases the value of a variable by 1. As with +the increment operator, no value is returned when you use the operator in a +simple statement. Use parentheses to return a value, as follows: + +```powershell +$a = 7 +--$a +$a +``` + +``` +6 +``` + +```powershell +(--$a) +``` + +``` +5 +``` + +The prefix version of the operator decrements a variable before its value +is used in the statement, as follows: + +```powershell +$a = 7 +$c = --$a +$a +``` + +``` +6 +``` + +```powershell +$c +``` + +``` +6 +``` + +The postfix version of the operator decrements a variable after its value +is used in the statement. In the following example, the $d and $a variables +have different values because the value is assigned to $d before $a +changes: + +```powershell +$a = 7 +$d = $a-- +$a +``` + +``` +6 +``` + +```powershell +$d +``` + +``` +7 +``` + +## MICROSOFT .NET FRAMEWORK TYPES + +By default, when a variable has only one value, the value that is assigned +to the variable determines the data type of the variable. For example, the +following command creates a variable that has the "Integer" (System.Int32) +type: + +```powershell +$a = 6 +``` + +To find the .NET Framework type of a variable, use the **GetType** method +and its **FullName** property, as follows. Be sure to include the +parentheses after the **GetType** method name, even though the method call +has no arguments: + +```powershell +$a = 6 +$a.GetType().FullName +``` + +``` +System.Int32 +``` + +To create a variable that contains a string, assign a string value to the +variable. To indicate that the value is a string, enclose it in quotation +marks, as follows: + +```powershell +$a = "6" +$a.GetType().FullName +``` + +``` +System.String +``` + +If the first value that is assigned to the variable is a string, Windows +PowerShell treats all operations as string operations and casts new values +to strings. This occurs in the following example: + +```powershell +$a = "file" +$a += 3 +$a +``` + +``` +file3 +``` + +If the first value is an integer, PowerShell treats all operations +as integer operations and casts new values to integers. This occurs in the +following example: + +```powershell +$a = 6 +$a += "3" +$a +``` + +``` +9 +``` + +You can cast a new scalar variable as any .NET Framework type by placing +the type name in brackets that precede either the variable name or the +first assignment value. When you cast a variable, you can determine the +types of data that can be stored in the variable. And, you can determine +how the variable behaves when you manipulate it. + +For example, the following command casts the variable as a string type: + +```powershell +[string]$a = 27 +$a += 3 +$a +``` + +``` +273 +``` + +The following example casts the first value, instead of casting the +variable: + +```powershell +$a = [string]27 +``` + +When you cast a variable to a specific type, the common convention is to +cast the variable, not the value. However, you cannot recast the data type +of an existing variable if its value cannot be converted to the new data +type. To change the data type, you must replace its value, as follows: + +```powershell +$a = "string" +[int]$a +``` + +``` +Cannot convert value "string" to type "System.Int32". Error: "Input +string was not in a correct format." +At line:1 char:8 ++ [int]$a <<<< +``` + +```powershell +[int]$a = 3 +``` + +In addition, when you precede a variable name with a data type, the type of +that variable is locked unless you explicitly override the type by +specifying another data type. If you try to assign a value that is +incompatible with the existing type, and you do not explicitly override the +type, PowerShell displays an error, as shown in the following +example: + +```powershell +$a = 3 +$a = "string" +[int]$a = 3 +$a = "string" +``` + +``` +Cannot convert value "string" to type "System.Int32". Error: "Input +string was not in a correct format." +At line:1 char:3 ++ $a <<<< = "string" +``` + +```powershell +[string]$a = "string" +``` + +In PowerShell, the data types of variables that contain multiple +items in an array are handled differently from the data types of variables +that contain a single item. Unless a data type is specifically assigned to +an array variable, the data type is always `System.Object []`. This data +type is specific to arrays. + +Sometimes, you can override the default type by specifying another type. +For example, the following command casts the variable as a `string []` +array type: + +```powershell +[string []] $a = "one", "two", "three" +``` + +PowerShell variables can be any .NET Framework data type. In +addition, you can assign any fully qualified .NET Framework data type that +is available in the current process. For example, the following command +specifies a `System.DateTime` data type: + +```powershell +[System.DateTime]$a = "5/31/2005" +``` + +The variable will be assigned a value that conforms to the +`System.DateTime` data type. The value of the $a variable would be the +following: + +``` +Tuesday, May 31, 2005 12:00:00 AM +``` + +## ASSIGNING MULTIPLE VARIABLES + +In PowerShell, you can assign values to multiple variables by using +a single command. The first element of the assignment value is assigned to +the first variable, the second element is assigned to the second variable, +the third element to the third variable, and so on. For example, the +following command assigns the value 1 to the $a variable, the value 2 to +the $b variable, and the value 3 to the $c variable: + +```powershell +$a, $b, $c = 1, 2, 3 +``` + +If the assignment value contains more elements than variables, all the +remaining values are assigned to the last variable. For example, the +following command contains three variables and five values: + +```powershell +$a, $b, $c = 1, 2, 3, 4, 5 +``` + +Therefore, PowerShell assigns the value 1 to the $a variable and +the value 2 to the $b variable. It assigns the values 3, 4, and 5 to the $c +variable. To assign the values in the $c variable to three other variables, +use the following format: + +```powershell +$d, $e, $f = $c +``` + +This command assigns the value 3 to the $d variable, the value 4 to the $e +variable, and the value 5 to the $f variable. + +You can also assign a single value to multiple variables by chaining the +variables. For example, the following command assigns a value of "three" to +all four variables: + +```powershell +$a = $b = $c = $d = "three" +``` + +## VARIABLE-RELATED CMDLETS + +In addition to using an assignment operation to set a variable value, you +can also use the +[Set-Variable](../../Microsoft.PowerShell.Utility/Set-Variable.md) cmdlet. For +example, the following command uses `Set-Variable` to assign an array of 1, +2, 3 to the $a variable. + +```powershell +Set-Variable -Name a -Value 1, 2, 3 +``` + +## SEE ALSO + +[about_Arrays](about_Arrays.md) + +[about_Hash_Tables](about_Hash_Tables.md) + +[about_Variables](about_Variables.md) + +[Clear-Variable](../../Microsoft.PowerShell.Utility/Clear-Variable.md) + +[Remove-Variable](../../Microsoft.PowerShell.Utility/Remove-Variable.md) + +[Set-Variable](../../Microsoft.PowerShell.Utility/Set-Variable.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Automatic_Variables.md b/reference/7/Microsoft.PowerShell.Core/About/about_Automatic_Variables.md new file mode 100644 index 000000000000..ac3155110a3e --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Automatic_Variables.md @@ -0,0 +1,868 @@ +--- +md.date: 2/27/2019 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Automatic_Variables +--- +# About Automatic Variables + +## Short description +Describes variables that store state information for PowerShell. These +variables are created and maintained by PowerShell. + +## Long description + +Conceptually, these variables are considered to be read-only. Even though they +**can** be written to, for backward compatibility they **should not** be +written to. + +Here is a list of the automatic variables in PowerShell: + +### $$ + +Contains the last token in the last line received by the session. + +### $? + +Contains the execution status of the last operation. It contains TRUE if +the last operation succeeded and FALSE if it failed. + +### $^ + +Contains the first token in the last line received by the session. + +### $_ + +Same as `$PSItem`. Contains the current object in the pipeline object. You +can use this variable in commands that perform an action on every object or +on selected objects in a pipeline. + +### $args + +Contains an array of values for undeclared parameters that are passed to a +function, script, or script block. When you create a function, you can declare +the parameters by using the `param` keyword or by adding a comma-separated list +of parameters in parentheses after the function name. + +In an event action, the `$Args` variable contains objects that represent the +event arguments of the event that is being processed. This variable is +populated only within the `Action` block of an event registration command. +The value of this variable can also be found in the **SourceArgs** property of +the **PSEventArgs** object that `Get-Event` returns. + +### $ConsoleFileName + +Contains the path of the console file (`.psc1`) that was most recently used +in the session. This variable is populated when you start PowerShell with +the **PSConsoleFile** parameter or when you use the `Export-Console` cmdlet to +export snap-in names to a console file. + +When you use the `Export-Console` cmdlet without parameters, it automatically +updates the console file that was most recently used in the session. You +can use this automatic variable to determine which file will be updated. + +### $Error + +Contains an array of error objects that represent the most recent errors. +The most recent error is the first error object in the array `$Error[0]`. + +To prevent an error from being added to the `$Error` array, use the +**ErrorAction** common parameter with a value of **Ignore**. For more +information, see [about_CommonParameters](about_CommonParameters.md). + +### $Event + +Contains a **PSEventArgs** object that represents the event that is being +processed. This variable is populated only within the `Action` block of an +event registration command, such as `Register-ObjectEvent`. The value of this +variable is the same object that the `Get-Event` cmdlet returns. Therefore, +you can use the properties of the `Event` variable, such as +`$Event.TimeGenerated`, in an `Action` script block. + +### $EventArgs + +Contains an object that represents the first event argument that derives +from **EventArgs** of the event that is being processed. This variable is +populated only within the `Action` block of an event registration command. +The value of this variable can also be found in the **SourceEventArgs** +property of the **PSEventArgs** object that `Get-Event` returns. + +### $EventSubscriber + +Contains a **PSEventSubscriber** object that represents the event subscriber of +the event that is being processed. This variable is populated only within +the `Action` block of an event registration command. The value of this +variable is the same object that the `Get-EventSubscriber` cmdlet returns. + +### $ExecutionContext + +Contains an **EngineIntrinsics** object that represents the execution context +of the PowerShell host. You can use this variable to find the execution +objects that are available to cmdlets. + +### $false + +Contains **FALSE**. You can use this variable to represent **FALSE** in commands +and scripts instead of using the string "false". The string can be +interpreted as **TRUE** if it is converted to a non-empty string or to a +non-zero integer. + +### $foreach + +Contains the enumerator (not the resulting values) of a +[ForEach](about_ForEach.md) loop. The `$ForEach` variable exists only while +the `ForEach` loop is running; it is deleted after the loop is completed. + +Enumerators contain properties and methods you can use to retrieve loop values +and change the current loop iteration. For more information, see +[Using Enumerators](#using-enumerators). + +### $HOME + +Contains the full path of the user's home directory. This variable is the +equivalent of the `"$env:homedrive$env:homepath"` Windows environment variables, +typically `C:\Users\`. + +### $Host + +Contains an object that represents the current host application for +PowerShell. You can use this variable to represent the current host in +commands or to display or change the properties of the host, such as +`$Host.version` or `$Host.CurrentCulture`, or +`$host.ui.rawui.setbackgroundcolor("Red")`. + +### $input + +Contains an enumerator that enumerates all input that is passed to a +function. The `$input` variable is available only to functions and script +blocks (which are unnamed functions). + +- In a function without a `Begin`, `Process`, or `End` block, the `$input` + variable enumerates the collection of all input to the function. + +- In the `Begin` block, the `$input` variable contains no data. + +- In the `Process` block, the `$input` variable contains the + object that is currently in the pipeline. + +- In the `End` block, the `$input` variable enumerates the collection of all + input to the function. + + > [!NOTE] + > You cannot use the `$input` variable inside both the Process block and the + > End block in the same function or script block. + +Enumerators contain properties and methods you can use to retrieve loop values +and change the current loop iteration. For more information, see +[Using Enumerators](#using-enumerators). + +### $IsCoreCLR + +Contains `$True` if the current session is running on the .NET Core Runtime +(CoreCLR). Otherwise contains `$False`. + +### $IsLinux + +Contains `$True` if the current session is running on a Linux operating system. +Otherwise contains `$False`. + +### $IsMacOS + +Contains `$True` if the current session is running on a MacOS operating system. +Otherwise contains `$False`. + +### $IsWindows + +Contains `$TRUE` if the current session is running on a Windows operating +system. Otherwise contains `$FALSE`. + +### $LastExitCode + +Contains the exit code of the last Windows-based program that was run. + +### $Matches + +The `Matches` variable works with the `-match` and `-notmatch` operators. +When you submit scalar input to the `-match` or `-notmatch` operator, and +either one detects a match, they return a Boolean value and populate the +`$Matches` automatic variable with a hash table of any string values that +were matched. The `$Matches` hash table can also be populated with captures +when you use regular expressions with the `-match` operator. + +For more information about the `-match` operator, see +[about_comparison_operators](about_comparison_operators.md). For more +information on regular expressions, see [about_Regular_Expressions](about_Regular_Expressions.md). + +### $MyInvocation + +Contains an information about the current command, such as the name, +parameters, parameter values, and information about how the command was +started, called, or "invoked," such as the name of the script that called +the current command. + +`$MyInvocation` is populated only for scripts, function, and script blocks. You +can use the information in the **System.Management.Automation.InvocationInfo** +object that `$MyInvocation` returns in the current script, such as the path and +file name of the script (`$MyInvocation.MyCommand.Path`) or the name of a +function (`$MyInvocation.MyCommand.Name`) to identify the current command. This +is particularly useful for finding the name of the current script. + +Beginning in PowerShell 3.0, `MyInvocation` has the following new +properties. + +| Property | Description | +| ------------- | --------------------------------------------------- | +| **PSScriptRoot** | Contains the full path to the script that invoked | +| | the current command. The value of this property is | +| | populated only when the caller is a script. | +| **PSCommandPath** | Contains the full path and file name of the script | +| | that invoked the current command. The value of this | +| | property is populated only when the caller is a | +| | script. | + +Unlike the `$PSScriptRoot` and `$PSCommandPath` automatic variables, the +**PSScriptRoot** and **PSCommandPath** properties of the `$MyInvocation` +automatic variable contain information about the invoker or calling script, +not the current script. + +### $NestedPromptLevel + +Contains the current prompt level. A value of 0 indicates the original +prompt level. The value is incremented when you enter a nested level and +decremented when you exit it. + +For example, PowerShell presents a nested command prompt when you use the +`$Host.EnterNestedPrompt` method. PowerShell also presents a nested command +prompt when you reach a breakpoint in the PowerShell debugger. + +When you enter a nested prompt, PowerShell pauses the current command, +saves the execution context, and increments the value of the +`$NestedPromptLevel` variable. To create additional nested command prompts +(up to 128 levels) or to return to the original command prompt, complete +the command, or type `exit`. + +The `$NestedPromptLevel` variable helps you track the prompt level. You can +create an alternative PowerShell command prompt that includes this value so +that it is always visible. + +### $NULL + +`$null` is an automatic variable that contains a **NULL** or empty value. You +can use this variable to represent an absent or undefined value in commands and +scripts. + +PowerShell treats `$null` as an object with a value, that is, as an explicit +placeholder, so you can use `$null` to represent an empty value in a series +of values. + +For example, when `$null` is included in a collection, it is counted as one +of the objects. + +```powershell +$a = "one", $null, "three" +$a.count +``` + +```output +3 +``` + +If you pipe the `$null` variable to the `ForEach-Object` cmdlet, it generates a +value for `$null`, just as it does for the other objects + +```powershell +"one", $null, "three" | ForEach-Object { "Hello " + $_} +``` + +```output +Hello one +Hello +Hello three +``` + +As a result, you cannot use `$null` to mean "no parameter value." A parameter +value of `$null` overrides the default parameter value. + +However, because PowerShell treats the `$null` variable as a placeholder, you +can use it in scripts like the following one, which would not work if `$null` +were ignored. + +```powershell +$calendar = @($null, $null, "Meeting", $null, $null, "Team Lunch", $null) +$days = "Sunday","Monday","Tuesday","Wednesday","Thursday", + "Friday","Saturday" +$currentDay = 0 +foreach($day in $calendar) +{ + if($day -ne $null) + { + "Appointment on $($days[$currentDay]): $day" + } + + $currentDay++ +} +``` + +```output +Appointment on Tuesday: Meeting +Appointment on Friday: Team lunch +``` + +### $PID + +Contains the process identifier (PID) of the process that is hosting the +current PowerShell session. + +### $PROFILE + +Contains the full path of the PowerShell profile for the current user and +the current host application. You can use this variable to represent the +profile in commands. For example, you can use it in a command to determine +whether a profile has been created: + +```powershell +Test-Path $PROFILE +``` + +Or, you can use it in a command to create a profile: + +```powershell +New-Item -ItemType file -Path $PSHOME -Force +``` + +You can also use it in a command to open the profile in Notepad: + +```powershell +notepad $profile +``` + +### $PSBoundParameterValues + +Contains a dictionary of the parameters that are passed to a script or +function and their current values. This variable has a value only in a +scope where parameters are declared, such as a script or function. You can +use it to display or change the current values of parameters or to pass +parameter values to another script or function. + +For example: + +```powershell +function Test { + param($a, $b) + + # Display the parameters in dictionary format. + $PSBoundParameters + + # Call the Test1 function with $a and $b. + test1 @PSBoundParameters +} +``` + +### $PSCmdlet + +Contains an object that represents the cmdlet or advanced function that is +being run. + +You can use the properties and methods of the object in your cmdlet or +function code to respond to the conditions of use. For example, the +**ParameterSetName** property contains the name of the parameter set that is +being used, and the **ShouldProcess** method adds the **WhatIf** and +**Confirm** parameters to the cmdlet dynamically. + +For more information about the `$PSCmdlet` automatic variable, see +[about_Functions_Advanced](about_Functions_Advanced.md). + +### $PSCommandPath + +Contains the full path and file name of the script that is being run. This +variable is valid in all scripts. + +### $PSCulture + +Contains the name of the culture currently in use in the operating system. +The culture determines the display format of items such as numbers, +currency, and dates. This is the value of the +**System.Globalization.CultureInfo.CurrentCulture.Name** property of the +system. To get the **System.Globalization.CultureInfo** object for the system, +use the `Get-Culture` cmdlet. + +### $PSDebugContext + +While debugging, this variable contains information about the debugging +environment. Otherwise, it contains a NULL value. As a result, you can use it +to indicate whether the debugger has control. When populated, it contains a +**PsDebugContext** object that has **Breakpoints** and **InvocationInfo** +properties. The **InvocationInfo** property has several useful properties, +including the **Location** property. The **Location** property indicates the +path of the script that is being debugged. + +### $PSHOME + +Contains the full path of the installation directory for PowerShell, +typically, `$env:windir\System32\PowerShell\v1.0` in Windows systems. You can +use this variable in the paths of PowerShell files. For example, the +following command searches the conceptual Help topics for the word +"variable": + +```powershell +Select-String -Pattern Variable -Path $pshome\*.txt +``` + +### $PSItem + +Same as `$_`. Contains the current object in the pipeline object. You can use +this variable in commands that perform an action on every object or on +selected objects in a pipeline. + +### $PSScriptRoot + +Contains the directory from which a script is being run. + +In PowerShell 2.0, this variable is valid only in script modules (.psm1). +Beginning in PowerShell 3.0, it is valid in all scripts. + +### $PSSenderInfo + +Contains information about the user who started the PSSession, including +the user identity and the time zone of the originating computer. This +variable is available only in PSSessions. + +The `$PSSenderInfo` variable includes a user-configurable property, +**ApplicationArguments**, which, by default, contains only the +`$PSVersionTable` from the originating session. To add data to the +**ApplicationArguments** property, use the **ApplicationArguments** parameter +of the `New-PSSessionOption` cmdlet. + +### $PSUICulture + +Contains the name of the user interface (UI) culture that is currently in use +in the operating system. The UI culture determines which text strings are used +for user interface elements, such as menus and messages. This is the value of +the **System.Globalization.CultureInfo.CurrentUICulture.Name** property of the +system. To get the **System.Globalization.CultureInfo** object for the system, +use the `Get-UICulture` cmdlet. + +### $PSVersionTable + +Contains a read-only hash table that displays details about the version of +PowerShell that is running in the current session. The table includes the +following items: + +| Property | Description | +| ------------------------- | --------------------------------------------- | +| **PSVersion** | The PowerShell version number | +| **PSEdition** | This property has the value of 'Desktop', for | +| | Windows Server and Windows client versions. | +| | This property has the value of 'Core' for | +| | PowerShell running under Nano Server or | +| | Windows IOT. | +| **GitCommitId** | The commit Id of the source files, in GitHub, | +| **OS** | Description of the operating system that | +| | PowerShell is running on. | +| **Platform** | Platform that the operating system is running | +| | on. The value on Linux and macOS is **Unix**. | +| | See `$IsMacOs` and `$IsLinux`. | +| **PSCompatibleVersions** | Versions of PowerShell that are compatible | +| | with the current version | +| **PSRemotingProtocolVersion** | The version of the PowerShell remote | +| | management protocol. | +| **SerializationVersion** | The version of the serialization method | +| **WSManStackVersion** | The version number of the WS-Management stack | + +### $PWD + +Contains a path object that represents the full path of the current directory. + +### REPORTERRORSHOW VARIABLES + +The **ReportErrorShow** variables are defined in PowerShell, but they are not +implemented. `Get-Variable` gets them, but they do not contain valid data. + +- `$REPORTERRORSHOWEXCEPTIONCLASS` +- `$REPORTERRORSHOWINNEREXCEPTION` +- `$REPORTERRORSHOWSOURCE` +- `$REPORTERRORSHOWSTACKTRACE` + +### $SENDER + +Contains the object that generated this event. This variable is populated +only within the `Action` block of an event registration command. The value of +this variable can also be found in the **Sender** property of the **PSEventArgs** +object that `Get-Event` returns. + +### $ShellId + +Contains the identifier of the current shell. + +### $StackTrace + +Contains a stack trace for the most recent error. + +### $switch + +Contains the enumerator (not the resulting values) of a [Switch](about_Switch.md) +statement. The `$Switch` variable exists only while the `switch` statement is +running; it is deleted when the `switch` statement +completes execution. + +Enumerators contain properties and methods you can use to retrieve loop values +and change the current loop iteration. For more information, see +[Using Enumerators](#using-enumerators). + +### $this + +In a script block that defines a script property or script method, the +`$This` variable refers to the object that is being extended. + +### $true + +Contains **TRUE**. You can use this variable to represent **TRUE** in commands +and scripts. + +## Using Enumerators + +The `$input`, `$foreach`, and `$switch` variables are all enumerators used +to iterate through the values processed by their containing code block. + +An enumerator contains properties and methods you can use to advance or reset +iteration, or retrieve iteration values. Directly manipulating enumerators is not +considered best practice. + +- Within loops, flow control keywords [break](about_Break.md) and [continue](about_Continue.md) + should be preferred. +- Within functions that accepts pipeline input, it is best practice to + use Parameters with the **ValueFromPipeline** or + **ValueFromPipelineByPropertyName** attributes. + + For more information, see [about_Functions_Advanced_Parameters](about_Functions_Advanced_Parameters.md). + +### MoveNext + +The [MoveNext](/dotnet/api/system.collections.ienumerator.movenext) method +advances the enumerator to the next element of the collection. **MoveNext** +returns **True** if the enumerator was successfully advanced, **false** if +the enumerator has passed the end of the collection. + +> [!NOTE] +> The **Boolean** value returned my **MoveNext** is sent to the output stream. +> You can suppress the output by typecasting it to `[void]` or piping it to +> [Out-Null](../Out-Null.md). +> +> ```powershell +> $input.MoveNext() | Out-Null +> ``` +> +> ```powershell +> [void]$input.MoveNext() +> ``` + +### Reset + +The [Reset](/dotnet/api/system.collections.ienumerator.reset) method sets +the enumerator to its initial position, which is **before** the first element +in the collection. + +### Current + +The [Current](/dotnet/api/system.collections.ienumerator.current) property +gets the element in the collection, or pipeline, at the current position of +the enumerator. + +The **Current** property continues to return the same property until +**MoveNext** is called. + +### Examples + +#### Example 1: Using the Input variable + +In the following example, accessing the `$input` variable clears the variable +until the next time the process block executes. Using the **Reset** method +resets the `$input` variable to the current pipeline value. + +```powershell +function Test +{ + begin + { + $i = 0 + } + + process + { + "Iteration: $i" + $i++ + "`tInput: $input" + "`tAccess Again: $input" + $input.Reset() + "`tAfter Reset: $input" + } +} + +"one","two" | Test +``` + +```Output +Iteration: 0 + Input: one + Access Again: + After Reset: one +Iteration: 1 + Input: two + Access Again: + After Reset: two +``` + +The process block automatically advances the `$input` variable even if you +do not access it. + +```powershell +$skip = $true +function Skip +{ + begin + { + $i = 0 + } + + process + { + "Iteration: $i" + $i++ + if ($skip) + { + "`tSkipping" + $skip = $false + } + else + { + "`tInput: $input" + } + } +} + +"one","two" | Skip +``` + +```Output +Iteration: 0 + Skipping +Iteration: 1 + Input: two +``` + +### Example 2: Using $input outside the Process block + +Outside of the process block the `$input` variable represents all the values +piped into the function. + +- Accessing the `$input` variable clears all values. +- The **Reset** method resets the entire collection. +- The **Current** property is never populated. +- The **MoveNext** method returns false because the collection cannot be + advanced. + - Calling **MoveNext** clears out the `$input` variable. + +```powershell +Function All +{ + "All Values: $input" + "Access Again: $input" + $input.Reset() + "After Reset: $input" + $input.MoveNext() | Out-Null + "After MoveNext: $input" +} + +"one","two","three" | All +``` + +```Output +All Values: one two three +Access Again: +After Reset: one two three +After MoveNext: +``` + +### Example 3: Using the $input.Current property + +By using the **Current** property, the current pipeline value can be accessed +multiple times without using the **Reset** method. The Process block does not +automatically call the **MoveNext** method. + +The **Current** property will never be populated unless you explicitly call +**MoveNext**. The **Current** property can be accessed multiple times inside +the process block without clearing its value. + +```powershell +function Current +{ + begin + { + $i = 0 + } + + process + { + "Iteration: $i" + $i++ + "`tBefore MoveNext: $($input.Current)" + $input.MoveNext() | Out-Null + "`tAfter MoveNext: $($input.Current)" + "`tAccess Again: $($input.Current)" + } +} + +"one","two" | Current +``` + +```Output +Iteration: 0 + Before MoveNext: + After MoveNext: one + Access Again: one +Iteration: 1 + Before MoveNext: + After MoveNext: two + Access Again: two +``` + +### Example 4: Using the $foreach variable + +Unlike the `$input` variable, the `$foreach` variable always represents all +items in the collection when accessed directly. Use the **Current** property +to access the current collection element, and the **Reset** and **MoveNext** +methods to change its value. + +> [!NOTE] +> Each iteration of the `foreach` loop will automatically call the **MoveNext** +> method. + +The following loop only executes twice. In the second iteration, the collection +is moved to the 3rd element before the iteration is complete. After the second +iteration, there are now no more values to iterate, and the loop terminates. + +The **MoveNext** property does not affect the variable chosen to iterate through +the collection (`$Num`). + +```powershell +$i = 0 +foreach ($num in ("one","two","three")) +{ + "Iteration: $i" + $i++ + "`tNum: $num" + "`tCurrent: $($foreach.Current)" + + if ($foreach.Current -eq "two") + { + "Before MoveNext (Current): $($foreach.Current)" + $foreach.MoveNext() | Out-Null + "After MoveNext (Current): $($foreach.Current)" + "Num has not changed: $num" + } +} +``` + +```Output +Iteration: 0 + Num: one + Current: one +Iteration: 1 + Num: two + Current: two +Before MoveNext (Current): two +After MoveNext (Current): three +Num has not changed: two +``` + +Using the **Reset** method resets the current element in the collection. The +following example loops through the first two elements **twice** because the +**Reset** method is called. After the first two loops, the `If` statement +fails and the loop iterates through all three elements normally. + +> [!IMPORTANT] +> This could result in an infinite loop. + +```powershell +$stopLoop = 0 +foreach ($num in ("one","two", "three")) +{ + ("`t" * $stopLoop) + "Current: $($foreach.Current)" + + if ($num -eq "two" -and $stopLoop -lt 2) + { + $foreach.Reset() | Out-Null + ("`t" * $stopLoop) + "Reset Loop: $stopLoop" + $stopLoop++ + } +} +``` + +```Output +Current: one +Current: two +Reset Loop: 0 + Current: one + Current: two + Reset Loop: 1 + Current: one + Current: two + Current: three +``` + +### Example 5: Using the $switch variable + +The `$switch` variable has the exact same rules as the `$foreach` variable. +The following example demonstrates all of the enumerator concepts. + +> [!NOTE] +> Note how the **NotEvaluated** case is never executed, even though there is +> no `break` statement after the **MoveNext** method. + +```powershell +$values = "Start", "MoveNext", "NotEvaluated", "Reset", "End" +$stopInfinite = $false +switch ($values) +{ + "MoveNext" { + "`tMoveNext" + $switch.MoveNext() | Out-Null + "`tAfter MoveNext: $($switch.Current)" + } + # This case is never evaluated. + "NotEvaluated" { + "`tAfterMoveNext: $($switch.Current)" + } + + "Reset" { + if (!$stopInfinite) + { + "`tReset" + $switch.Reset() + $stopInfinite = $true + } + } + + default { + "Default (Current): $($switch.Current)" + } +} +``` + +```Output +Default (Current): Start + MoveNext + After MoveNext: NotEvaluated + Reset +Default (Current): Start + MoveNext + After MoveNext: NotEvaluated +Default (Current): End +``` + +## SEE ALSO + +- [about_Hash_Tables](about_Hash_Tables.md) +- [about_Preference_Variables](about_Preference_Variables.md) +- [about_Variables](about_Variables.md) diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Break.md b/reference/7/Microsoft.PowerShell.Core/About/about_Break.md new file mode 100644 index 000000000000..90745c405388 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Break.md @@ -0,0 +1,200 @@ +--- +ms.date: 06/09/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Break +--- +# About Break + +## SHORT DESCRIPTION +Describes a statement you can use to immediately exit Foreach, For, While, +Do, or Switch statements. + +## LONG DESCRIPTION + +When a Break statement appears in a loop, such as a Foreach, For, or While +loop, the Break statement causes PowerShell to immediately exit the loop. +In a Switch construct, Break causes PowerShell to exit the Switch code +block. + +A Break statement can include a label that lets you exit embedded loops. A +label can specify any loop keyword, such as Foreach, For, or While, in a +script. + +The following example shows how to use a Break statement to exit a For +statement: + +```powershell +for($i=1; $i -le 10; $i++) { + Write-Host $i + break +} +``` + +In this example, the Break statement exits the For loop when the $i +variable equals 1. Even though the For statement evaluates to True until $i +is greater than 10, PowerShell reaches the break statement the first time +the For loop is run. + +It is more common to use the Break statement in a loop where an inner +condition must be met. Consider the following Foreach statement example: + +```powershell +$i=0 +$varB = 10,20,30,40 +foreach ($val in $varB) { + $i++ + if ($val -eq 30) { + break + } +} +Write-Host "30 was found in array position $i" +``` + +In this example, the Foreach statement iterates the $varB array. Each time +the code block is run, the $i variable is incremented by 1. The If +statement evaluates to False the first two times the loop is run. The third +time the loop is run, $i equals 3, and the $val variable equals 30. At this +point, the Break statement runs, and the Foreach loop exits. + +You break out of the other looping statements in the same way you break out +of the Foreach loop. In the following example, the Break statement exits a +While statement when a DivideByZeroException exception is trapped using the +Trap statement. + +```powershell +$i = 3 +while ($true) { + trap [DivideByZeroException] { + Write-Host 'divide by zero trapped' + break + } + 1 / $i-- +} + +``` + +A Break statement can include a label. If you use the Break keyword with a +label, PowerShell exits the labeled loop instead of exiting the current +loop. The syntax for a label is as follows (this example shows a label in a +While loop): + +:myLabel while (``) { ``} + +The label is a colon followed by a name that you assign. The label must be +the first token in a statement, and it must be followed by the looping +keyword, such as While. + +In PowerShell, only loop keywords, such as Foreach, For, and While can have +a label. + +Break moves execution out of the labeled loop. In embedded loops, this has +a different result than the Break keyword has when it is used by itself. +This schematic example has a While statement with a For statement: + +```powershell +:myLabel while () { + for ($item in $items) { + if () { + break myLabel + } + $item = $x # A statement inside the For-loop + } +} +$a = $c # A statement after the labeled While-loop +``` + +If condition 2 evaluates to True, the execution of the script skips down to +the statement after the labeled loop. In the example, execution starts +again with the statement "$a = $c". + +You can nest many labeled loops, as shown in the following schematic +example. + +```powershell +:red while () { + :yellow while () { + while () { + if ($a) {break} + if ($b) {break red} + if ($c) {break yellow} + } + Write-Host "After innermost loop" + } + Write-Host "After yellow loop" +} +Write-Host "After red loop" +``` + +If the $b variable evaluates to True, execution of the script resumes after +the loop that is labeled "red". If the $c variable evaluates to True, +execution of the script control resumes after the loop that is labeled +"yellow". + +If the $a variable evaluates to True, execution resumes after the innermost +loop. No label is needed. + +PowerShell does not limit how far labels can resume execution. The label +can even pass control across script and function call boundaries. + +The Break keyword is used to leave the Switch construct. For example, the +following Switch statement uses Break statements to test for the most +specific condition: + +```powershell +$var = "word2" +switch -regex ($var) { + "word2" { + Write-Host "Exact" $_ + break + } + + "word.*" { + Write-Host "Match on the prefix" $_ + break + } + + "w.*" { + Write-Host "Match on at least the first letter" $_ + break + } + + default { + Write-Host "No match" $_ + break + } +} +``` + +In this example, the $var variable is created and initialized to a string +value of "word2". The Switch statement uses the Regex class to match the +variable value first with the term "word2". (The Regex class is a regular +expression Microsoft .NET Framework class.) Because the variable value and +the first test in the Switch statement match, the first code block in the +Switch statement runs. + +When PowerShell reaches the first Break statement, the Switch statement +exits. If the four Break statements are removed from the example, all four +conditions are met. This example uses the break statement to display +results when the most specific condition is met. + +## SEE ALSO + +[about_Comparison_Operators](about_Comparison_Operators.md) + +[about_Continue](about_Continue.md) + +[about_For](about_For.md) + +[about_Foreach](about_Foreach.md) + +[about_Switch](about_Switch.md) + +[about_Throw](about_Throw.md) + +[about_Trap](about_Trap.md) + +[about_Try_Catch_Finally](about_Try_Catch_Finally.md) + +[about_While](about_While.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_CimSession.md b/reference/7/Microsoft.PowerShell.Core/About/about_CimSession.md new file mode 100644 index 000000000000..4714d7eb46c5 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_CimSession.md @@ -0,0 +1,62 @@ +--- +ms.date: 04/28/2018 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_CimSession +--- +# About CimSession + +## SHORT DESCRIPTION +Describes a CimSession object and the difference between CIM sessions and +PowerShell sessions. + +## LONG DESCRIPTION + +A Common Information Model (CIM) session is a client-side object that +represents a connection to a local computer or a remote computer. You can +use CIM sessions as an alternative to PowerShell sessions +(PSSessions). Both approaches have advantages. + +You can use the [New-CimSession](../../CimCmdlets/New-CimSession.md) cmdlet to create a CIM session that contains +information about a connection, such as computer name, the protocol used +for the connection, session ID, and instance ID. + +After you create a CimSession object that specifies information required to +establish a connection, PowerShell does not establish the +connection immediately. When a cmdlet uses the CIM session, +PowerShell connects to the specified computer, and then, when the +cmdlet finishes, PowerShell terminates the connection. + +If you create a PSSession instead of using a CIM session, +PowerShell validates connection settings, and then establishes and +maintains the connection. If you use CIM sessions, PowerShell +does not open a network connection until needed. For more information about +PowerShell sessions, see [about_PSSessions](about_PSSessions.md). + +### When to Use a CIM Session + +Only cmdlets that work with a Windows Management Instrumentation (WMI) +provider or CIM over WS-Man accept CIM sessions. +For other cmdlets, use PSSessions. + +When you use a CIM session, PowerShell runs the cmdlet on the +local client. It connects to the WMI provider by using the CIM session. +The target computer does not require PowerShell, or even any +version of the Windows operating system. + +In contrast, a cmdlet run by using a PSSession runs on the target +computer. It requires PowerShell on the target system. +Furthermore, the cmdlet sends data back to the local computer. +PowerShell manages the data sent over the connection, and keeps +the size within the limits set by Windows Remote Management (WinRM). CIM +sessions do not impose the WinRM limits. + +CIM-based Cmdlet Definition XML (CDXML) cmdlets can be written to use any +WMI Provider. All WMI providers use CimSession objects. + +## SEE ALSO + +[New-CimSession](../../CimCmdlets/New-CimSession.md) + +[about_PSSessions](about_PSSessions.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Classes.md b/reference/7/Microsoft.PowerShell.Core/About/about_Classes.md new file mode 100644 index 000000000000..1f70bd724ce5 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Classes.md @@ -0,0 +1,840 @@ +--- +ms.date: 08/31/2018 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Classes +description: Describes how you can use classes to create your own custom types. +--- +# About Classes + +## SHORT DESCRIPTION +Describes how you can use classes to create your own custom types. + +## LONG DESCRIPTION + +PowerShell 5.0 adds a formal syntax to define classes and other user-defined +types. The addition of classes enables developers and IT professionals to +embrace PowerShell for a wider range of use cases. It simplifies development +of PowerShell artifacts and accelerates coverage of management surfaces. + +A class declaration is like a blueprint used to create instances of objects at +run time. When you define a class, the class name is the name of the type. For +example, if you declare a class named **Device** and initialize a variable +`$dev` to a new instance of **Device**, `$dev` is an object or instance of type +**Device**. Each instance of **Device** can have different values in its +properties. + +## SUPPORTED SCENARIOS + +- Define custom types in PowerShell using familiar object-oriented + programming semantics like classes, properties, methods, inheritance, + etc. +- Debug types using the PowerShell language. +- Generate and handle exceptions using formal mechanisms. +- Define DSC resources and their associated types by using the PowerShell + language. + +## SYNTAX + +Classes are declared using the following syntax: + +```syntax +class [: [][,] [hidden] [static] ...] + [([]) + {} ...] + [[] [hidden] [static] ...] +} +``` + +Classes are instantiated using either of the following syntaxes: + +```syntax +[$ =] New-Object -TypeName [ + [-ArgumentList] ] +``` + +```syntax +[$ =] []::new([]) +``` + +> [!NOTE] +> When using the `[]::new(` syntax, +> brackets around the class name are mandatory! +> The brackets signal a type definition for PowerShell. + +### Example syntax and usage + +This example shows the minimum syntax needed to create a usable class. + +```powershell +class Device { + [string]$Brand +} + +$dev = [Device]::new() +$dev.Brand = "Microsoft" +$dev +``` + +```output +Brand +----- +Microsoft +``` + +## CLASS PROPERTIES + +Properties are variables declared at class scope. +A property may be of any built-in type or an instance of another class. +Classes have no restriction in the number of properties they have. + +### Example class with simple properties + +```powershell +class Device { + [string]$Brand + [string]$Model + [string]$VendorSku +} + +$device = [Device]::new() +$device.Brand = "Microsoft" +$device.Model = "Surface Pro 4" +$device.VendorSku = "5072641000" + +$device +``` + +```output + + +Brand Model VendorSku +----- ----- --------- +Microsoft Surface Pro 4 5072641000 + +``` + +### Example complex types in class properties + +This example defines an empty **Rack** class using the **Device** class. +The examples, following this one, show how to add devices to the rack +and how to start with a pre-loaded rack. + +```powershell +class Device { + [string]$Brand + [string]$Model + [string]$VendorSku +} + +class Rack { + [string]$Brand + [string]$Model + [string]$VendorSku + [string]$AssetId + [Device[]]$Devices = [Device[]]::new(8) + +} + +$rack = [Rack]::new() + +$rack +``` + +```output + +Brand : +Model : +VendorSku : +AssetId : +Devices : {$null, $null, $null, $null...} + + +``` + +## CLASS METHODS + +Methods define the actions that a class can perform. +Methods may take parameters that provide input data. +Methods can return output. +Data returned by a method can be any defined data type. + +### Example simple class with properties and methods + +Extending the **Rack** class to add and remove devices +to or from it. + +```powershell +class Device { + [string]$Brand + [string]$Model + [string]$VendorSku + + [string]ToString(){ + return ("{0}|{1}|{2}" -f $this.Brand, $this.Model, $this.VendorSku) + } +} + +class Rack { + [int]$Slots = 8 + [string]$Brand + [string]$Model + [string]$VendorSku + [string]$AssetId + [Device[]]$Devices = [Device[]]::new($this.Slots) + + [void] AddDevice([Device]$dev, [int]$slot){ + ## Add argument validation logic here + $this.Devices[$slot] = $dev + } + + [void]RemoveDevice([int]$slot){ + ## Add argument validation logic here + $this.Devices[$slot] = $null + } + + [int[]] GetAvailableSlots(){ + [int]$i = 0 + return @($this.Devices.foreach{ if($_ -eq $null){$i}; $i++}) + } +} + +$rack = [Rack]::new() + +$surface = [Device]::new() +$surface.Brand = "Microsoft" +$surface.Model = "Surface Pro 4" +$surface.VendorSku = "5072641000" + +$rack.AddDevice($surface, 2) + +$rack +$rack.GetAvailableSlots() +``` + +```output + +Slots : 8 +Brand : +Model : +VendorSku : +AssetId : +Devices : {$null, $null, Microsoft|Surface Pro 4|5072641000, $null...} + +0 +1 +3 +4 +5 +6 +7 + +``` + +## OUTPUT IN CLASS METHODS + +Methods should have a return type defined. If a method does not +return output, then the output type should be `[void]`. + +In class methods, no objects get sent to the pipeline except those mentioned +in the `return` statement. There's no accidental output to the pipeline +from the code. + +> [!NOTE] +> This is fundamentally different from how PowerShell functions +> handle output, where everything goes to the pipeline. + +### Method output + +This example demonstrates no accidental output to the pipeline from +class methods, except on the `return` statement. + +```powershell +class FunWithIntegers +{ + [int[]]$Integers = 0..10 + + [int[]]GetOddIntegers(){ + return $this.Integers.Where({ ($_ % 2) }) + } + + [void] GetEvenIntegers(){ + # this following line doesn't go to the pipeline + $this.Integers.Where({ ($_ % 2) -eq 0}) + } + + [string]SayHello(){ + # this following line doesn't go to the pipeline + "Good Morning" + + # this line goes to the pipeline + return "Hello World" + } +} + +$ints = [FunWithIntegers]::new() + +$ints.GetOddIntegers() + +$ints.GetEvenIntegers() + +$ints.SayHello() +``` + +```output +1 +3 +5 +7 +9 +Hello World + +``` + +## CONSTRUCTOR + +Constructors enable you to set default values and validate object logic at the +moment of creating the instance of the class. Constructors have the same name +as the class. Constructors might have arguments, to initialize the data +members of the new object. + +The class can have zero or more constructors defined. If no constructor is +defined, the class is given a default parameterless constructor. This +constructor initializes all members to their default values. Object types and +strings are given null values. When you define constructor, no default +parameterless constructor is created. Create a parameterless constructor if +one is needed. + +### Constructor basic syntax + +In this example, the Device class is defined with properties and a +constructor. To use this class, the user is required to provide values for the +parameters listed in the constructor. + +```powershell +class Device { + [string]$Brand + [string]$Model + [string]$VendorSku + + Device( + [string]$b, + [string]$m, + [string]$vsk + ){ + $this.Brand = $b + $this.Model = $m + $this.VendorSku = $vsk + } +} + +[Device]$surface = [Device]::new("Microsoft", "Surface Pro 4", "5072641000") + +$surface +``` + +```output +Brand Model VendorSku +----- ----- --------- +Microsoft Surface Pro 4 5072641000 + +``` + +### Example with multiple constructors + +In this example, the **Device** class is defined with properties, a default +constructor, and a constructor to initialize the instance. + +The default constructor sets the **brand** to *Undefined*, +and leaves **model** and **vendor-sku** with null values. + +```powershell +class Device { + [string]$Brand + [string]$Model + [string]$VendorSku + + Device(){ + $this.Brand = 'Undefined' + } + + Device( + [string]$b, + [string]$m, + [string]$vsk + ){ + $this.Brand = $b + $this.Model = $m + $this.VendorSku = $vsk + } +} + +[Device]$somedevice = [Device]::new() +[Device]$surface = [Device]::new("Microsoft", "Surface Pro 4", "5072641000") + +$somedevice +$surface +``` + +```output +Brand Model VendorSku +----- ----- --------- +Undefined +Microsoft Surface Pro 4 5072641000 +``` + +## HIDDEN ATTRIBUTE + +The `hidden` attribute makes a property or method less visible. The property +or method is still accessible to the user and is available in all scopes in +which the object is available. Hidden members are hidden from the `Get-Member` +cmdlet and can't be displayed using tab completion or IntelliSense outside of +the class definition. + +### Example using hidden attributes + +When a **Rack** object is created, the number of slots for devices is a +fixed value that should not be changed at any time. This value is known at +creation time. + +Using the hidden attribute allows the developer to keep the number of slots +hidden and prevents unintentional changes the size of the rack. + +```powershell +class Device { + [string]$Brand + [string]$Model +} + +class Rack { + [int] hidden $Slots = 8 + [string]$Brand + [string]$Model + [Device[]]$Devices = [Device[]]::new($this.Slots) + + Rack ([string]$b, [string]$m, [int]$capacity){ + ## argument validation here + + $this.Brand = $b + $this.Model = $m + $this.Slots = $capacity + + ## reset rack size to new capacity + $this.Devices = [Device[]]::new($this.Slots) + } +} + +[Rack]$r1 = [Rack]::new("Microsoft", "Surface Pro 4", 16) + +$r1 +$r1.Devices.Length +$r1.Slots +``` + +```output + +Brand Model Devices +----- ----- ------- +Microsoft Surface Pro 4 {$null, $null, $null, $null...} +16 +16 + +``` + +Notice **Slots** property isn't shown in `$r1` output. However, the size +was changed by the constructor. + +## STATIC ATTRIBUTE + +The `static` attribute defines a property or a method that exists in the class +and needs no instance. + +A static property is always available, independent of class instantiation. +A static property is shared across all instances of the class. +A static method is available always. +All static properties live for the entire session span. + +### Example using static attributes and methods + +Assume the racks instantiated here exist in your data center. +So, you would like to keep track of the racks in your code. + +```powershell +class Device { + [string]$Brand + [string]$Model +} + +class Rack { + hidden [int] $Slots = 8 + static [Rack[]]$InstalledRacks = @() + [string]$Brand + [string]$Model + [string]$AssetId + [Device[]]$Devices = [Device[]]::new($this.Slots) + + Rack ([string]$b, [string]$m, [string]$id, [int]$capacity){ + ## argument validation here + + $this.Brand = $b + $this.Model = $m + $this.AssetId = $id + $this.Slots = $capacity + + ## reset rack size to new capacity + $this.Devices = [Device[]]::new($this.Slots) + + ## add rack to installed racks + [Rack]::InstalledRacks += $this + } + + static [void]PowerOffRacks(){ + foreach ($rack in [Rack]::InstalledRacks) { + Write-Warning ("Turning off rack: " + ($rack.AssetId)) + } + } +} +``` + +#### Testing static property and method exist + +``` +PS> [Rack]::InstalledRacks.Length +0 + +PS> [Rack]::PowerOffRacks() + +PS> (1..10) | ForEach-Object { +>> [Rack]::new("Adatum Corporation", "Standard-16", +>> $_.ToString("Std0000"), 16) +>> } > $null + +PS> [Rack]::InstalledRacks.Length +10 + +PS> [Rack]::InstalledRacks[3] +Brand Model AssetId Devices +----- ----- ------- ------- +Adatum Corporation Standard-16 Std0004 {$null, $null, $null, $null...} + +PS> [Rack]::PowerOffRacks() +WARNING: Turning off rack: Std0001 +WARNING: Turning off rack: Std0002 +WARNING: Turning off rack: Std0003 +WARNING: Turning off rack: Std0004 +WARNING: Turning off rack: Std0005 +WARNING: Turning off rack: Std0006 +WARNING: Turning off rack: Std0007 +WARNING: Turning off rack: Std0008 +WARNING: Turning off rack: Std0009 +WARNING: Turning off rack: Std0010 +``` + +Notice that the number of racks increases each time you run this example. + +## PROPERTY VALIDATION ATTRIBUTES + +Validation attributes allow you to test that values given to properties meet +defined requirements. Validation is triggered the moment that the value is +assigned. See [about_functions_advanced_parameters](about_functions_advanced_parameters.md). + +### Example using validation attributes + +```powershell +class Device { + [ValidateNotNullOrEmpty()][string]$Brand + [ValidateNotNullOrEmpty()][string]$Model +} + +[Device]$dev = [Device]::new() + +Write-Output "Testing dev" +$dev + +$dev.Brand = "" + +``` + +```output +Testing dev + +Brand Model +----- ----- + +Exception setting "Brand": "The argument is null or empty. Provide an +argument that is not null or empty, and then try the command again." +At C:\tmp\Untitled-5.ps1:11 char:1 ++ $dev.Brand = "" ++ ~~~~~~~~~~~~~~~ + + CategoryInfo : NotSpecified: (:) [], SetValueInvocationExcep +tion + + FullyQualifiedErrorId : ExceptionWhenSetting +``` + +## INHERITANCE IN POWERSHELL CLASSES + +You can extend a class by creating a new class that derives from an existing +class. The derived class inherits the properties of the base class. You can +add or override methods and properties as required. + +PowerShell does not support multiple inheritance. +Classes cannot inherit from more than one class. +However, you can use interfaces for that purpose. + +Inheritance implementation is defined by the `:` operator; +which means to extend this class or implements these interfaces. +The derived class should always be leftmost in the class declaration. + +### Example using simple inheritance syntax + +This example shows the simple PowerShell class inheritance syntax. + +```powershell +Class Derived : Base {...} +``` + +This example shows inheritance with an interface declaration coming after the +base class. + +```powershell +Class Derived : Base.Interface {...} +``` + +### Example of simple inheritance in PowerShell classes + +In this example the _Rack_ and _Device_ classes used in the previous examples +are better defined to: avoid property repetitions, better align common +properties, and reuse common business logic. + +Most objects in the data center are company assets, which makes sense to +start tracking them as assets. +Device types are defined by the `DeviceType` enumeration, see +[about_Enum](about_Enum.md) for details on enumerations. + +In our example, we're only defining `Rack` and `ComputeServer`; both +extensions to the `Device` class. + + +```powershell +enum DeviceType { + Undefined = 0 + Compute = 1 + Storage = 2 + Networking = 4 + Communications = 8 + Power = 16 + Rack = 32 +} + +class Asset { + [string]$Brand + [string]$Model +} + +class Device : Asset { + hidden [DeviceType]$devtype = [DeviceType]::Undefined + [string]$Status + + [DeviceType] GetDeviceType(){ + return $this.devtype + } +} + +class ComputeServer : Device { + hidden [DeviceType]$devtype = [DeviceType]::Compute + [string]$ProcessorIdentifier + [string]$Hostname +} + +class Rack : Device { + hidden [DeviceType]$devtype = [DeviceType]::Rack + hidden [int]$Slots = 8 + + [string]$Datacenter + [string]$Location + [Device[]]$Devices = [Device[]]::new($this.Slots) + + Rack (){ + ## Just create the default rack with 8 slots + } + + Rack ([int]$s){ + ## Add argument validation logic here + $this.Devices = [Device[]]::new($s) + } + + [void] AddDevice([Device]$dev, [int]$slot){ + ## Add argument validation logic here + $this.Devices[$slot] = $dev + } + + [void] RemoveDevice([int]$slot){ + ## Add argument validation logic here + $this.Devices[$slot] = $null + } +} + +$FirstRack = [Rack]::new(16) +$FirstRack.Status = "Operational" +$FirstRack.Datacenter = "PNW" +$FirstRack.Location = "F03R02.J10" + +(0..15).ForEach({ + $ComputeServer = [ComputeServer]::new() + $ComputeServer.Brand = "Fabrikam, Inc." ## Inherited from Asset + $ComputeServer.Model = "Fbk5040" ## Inherited from Asset + $ComputeServer.Status = "Installed" ## Inherited from Device + $ComputeServer.ProcessorIdentifier = "x64" ## ComputeServer + $ComputeServer.Hostname = ("r1s" + $_.ToString("000")) ## ComputeServer + $FirstRack.AddDevice($ComputeServer, $_) + }) + +$FirstRack + +$FirstRack.Devices +``` + +```output + +Datacenter : PNW +Location : F03R02.J10 +Devices : {r1s000, r1s001, r1s002, r1s003...} +Status : Operational +Brand : +Model : + +ProcessorIdentifier : x64 +Hostname : r1s000 +Status : Installed +Brand : Fabrikam, Inc. +Model : Fbk5040 + +ProcessorIdentifier : x64 +Hostname : r1s001 +Status : Installed +Brand : Fabrikam, Inc. +Model : Fbk5040 + +<... content truncated here for brevity ...> + +ProcessorIdentifier : x64 +Hostname : r1s015 +Status : Installed +Brand : Fabrikam, Inc. +Model : Fbk5040 + +``` + +## CALLING BASE CLASS CONSTRUCTORS + +To invoke a base class constructor from a subclass, add the "base" keyword. + +### Example using the base class constructor + +```powershell +class Person { + [int]$Age + + Person([int]$a) + { + $this.Age = $a + } +} + +class Child : Person +{ + [string]$School + + Child([int]$a, [string]$s ) : base($a) { + $this.School = $s + } +} + +[Child]$littleone = [Child]::new(10, "Silver Fir Elementary School") + +$littleone.Age +``` + +```output + +10 +``` + +## INVOKE BASE CLASS METHODS + +To override existing methods in subclasses, declare methods by using the same +name and signature. + +```powershell +class BaseClass +{ + [int]days() {return 1} +} +class ChildClass1 : BaseClass +{ + [int]days () {return 2} +} + +[ChildClass1]::new().days() +``` + +```output + +2 +``` + +To call base class methods from overridden implementations, cast to the +base class ([baseclass]$this) on invocation. + +```powershell +class BaseClass +{ + [int]days() {return 1} +} +class ChildClass1 : BaseClass +{ + [int]days () {return 2} + [int]basedays() {return ([BaseClass]$this).days()} +} + +[ChildClass1]::new().days() +[ChildClass1]::new().basedays() +``` + +```output + +2 +1 +``` + +## INTERFACES + +The syntax for declaring interfaces is similar to C#. +You can declare interfaces after base types or immediately after a colon (:) +when there is no base type specified. Separate all type names with commas. + +```powershell +class MyComparable : system.IComparable +{ + [int] CompareTo([object] $obj) + { + return 0; + } +} + +class MyComparableBar : bar, system.IComparable +{ + [int] CompareTo([object] $obj) + { + return 0; + } +} +``` + +## SEE ALSO + +- [about_Enum](about_Enum.md) +- [about_Language_Keywords](about_language_keywords.md) +- [about_Methods](about_methods.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Command_Precedence.md b/reference/7/Microsoft.PowerShell.Core/About/about_Command_Precedence.md new file mode 100644 index 000000000000..d8cab1f0a5f2 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Command_Precedence.md @@ -0,0 +1,261 @@ +--- +ms.date: 08/28/2018 +schema: 2.0.0 +keywords: powershell,cmdlet +title: about_Command_Precedence +--- +# About Command Precedence + +## Short description +Describes how PowerShell determines which command to run. + +## Long description + +Command precedence describes how PowerShell determines which command to +run when a session contains more than one command with the same name. Commands +within a session can be hidden or replaced by commands with the same +name. This article shows you how to run hidden commands and how to avoid +command-name conflicts. + +## Command precedence + +When a PowerShell session includes more than one command that has the +same name, PowerShell determines which command to run by using the +following rules. + +- If you specify the path to a command, PowerShell runs the command at the + location specified by the path. + + For example, the following command runs the FindDocs.ps1 script in the + "C:\\TechDocs" directory: + + ``` + C:\TechDocs\FindDocs.ps1 + ``` + + As a security feature, PowerShell does not run executable (native) commands, + including PowerShell scripts, unless the command is located in a path that is + listed in the Path environment variable `$env:path` or unless you specify the + path to the script file. + + To run a script that is in the current directory, specify the full path, or + type a dot `.` to represent the current directory. + + For example, to run the FindDocs.ps1 file in the current directory, type: + + ``` + .\FindDocs.ps1 + ``` + +- If you do not specify a path, PowerShell uses the following precedence order + when it runs commands: + + 1. Alias + 2. Function + 3. Cmdlet + 4. Native Windows commands + + Therefore, if you type "help", PowerShell first looks for an alias named + `help`, then a function named `Help`, and finally a cmdlet named `Help`. It + runs the first `help` item that it finds. + + For example, if your session contains a cmdlet and a function, both named + `Get-Map`, when you type `Get-Map`, PowerShell runs the function. + + When the session contains items of the same type that have the same name, + PowerShell runs the newer item. + + For example, if you import another `Get-Date` cmdlet from a module, when you + type `Get-Date`, PowerShell runs the imported version over the native one. + +## Hidden and replaced items + +As a result of these rules, items can be replaced or hidden by items with the +same name. + +Items are "hidden" or "shadowed" if you can still access the original item, +such as by qualifying the item name with a module or snap-in name. + +For example, if you import a function that has the same name as a cmdlet in +the session, the cmdlet is hidden (but not replaced) because it was imported +from a snap-in or module. + +Items are "replaced" or "overwritten" if you can no longer access the original +item. + +For example, if you import a variable that has the same name as a variable +in the session, the original variable is replaced and is no longer accessible. +You cannot qualify a variable with a module name. + +Also, if you type a function at the command line and then import a function +with the same name, the original function is replaced and is no longer +accessible. + +### Finding hidden commands + +The **All** parameter of the [Get-Command](../../Microsoft.PowerShell.Core/Get-Command.md) +cmdlet gets all commands with the specified name, even if they are hidden +or replaced. Beginning in PowerShell 3.0, by default, `Get-Command` +gets only the commands that run when you type the command name. + +In the following examples, the session includes a `Get-Date` function and a +[Get-Date](../../Microsoft.PowerShell.Utility/Get-Date.md) cmdlet. + +The following command gets the `Get-Date` command that runs when you type +`Get-Date`. + +```powershell +Get-Command Get-Date +``` + +```output +CommandType Name ModuleName +----------- ---- ---------- +Function Get-Date +``` + +The following command uses the **All** parameter to get all `Get-Date` +commands. + +```powershell +Get-Command Get-Date -All +``` + +```output +CommandType Name ModuleName +----------- ---- ---------- +Function Get-Date +Cmdlet Get-Date Microsoft.PowerShell.Utility +``` + +### Running hidden commands + +You can run particular commands by specifying item properties that distinguish +the command from other commands that might have the same name. You can use this +method to run any command, but it is especially useful for running hidden +commands. + +#### Qualified names + +Using the module-qualified name of a cmdlet allows you to run commands hidden +by an item with the same name. For example, you can run the `Get-Date` cmdlet +by qualifying it with its module name **Microsoft.PowerShell.Utility**. + +Use this preferred method when writing scripts that you intend to +distribute. You cannot predict which commands might be present in +the session in which the script runs. + +```powershell +New-Alias -Name "Get-Date" -Value "Get-ChildItem" +Microsoft.PowerShell.Utility\Get-Date +``` + +```output +Tuesday, September 4, 2018 8:17:25 AM +``` + +To run a `New-Map` command that was added by the `MapFunctions` module, use +its module-qualified name: + +```powershell +MapFunctions\New-Map +``` + +To find the module from which a command was imported, use the **ModuleName** +property of commands. + +``` +(Get-Command ).ModuleName +``` + +For example, to find the source of the `Get-Date` cmdlet, type: + +```powershell +(Get-Command Get-Date).ModuleName +``` + +```output +Microsoft.PowerShell.Utility +``` + +> [!NOTE] +> You cannot qualify variables or aliases. + +#### Call operator + +You can also use the `Call` operator `&` to run hidden commands by combining +it with a call to [Get-ChildItem](../../Microsoft.PowerShell.Management/Get-ChildItem.md) +(the alias is "dir"), `Get-Command` or +[Get-Module](../../Microsoft.PowerShell.Core/Get-Module.md). + +The call operator executes strings and script blocks in a child scope. For more information, see [about_Operators](about_Operators.md). + +For example, if you have a function named `Map` that is hidden by an alias +named `Map`, use the following command to run the function. + +```powershell +&(Get-Command -Name Map -CommandType Function) +``` + +or + +```powershell +&(dir Function:\map) +``` + +You can also save your hidden command in a variable to make it easier to run. + +For example, the following command saves the `Map` function in the `$myMap` +variable and then uses the `Call` operator to run it. + +```powershell +$myMap = (Get-Command -Name map -CommandType function) +&($myMap) +``` + +### Replaced items + +A "replaced" item is one that you can no longer access. You can replace items +by importing items of the same name from a module or snap-in. + +For example, if you type a `Get-Map` function in your session, and you import +a function called `Get-Map`, it replaces the original function. You cannot +retrieve it in the current session. + +Variables and aliases cannot be hidden because you cannot use a call operator +or a qualified name to run them. When you import variables and aliases from a +module or snap-in, they replace variables in the session with the same name. + +### Avoiding name conflicts + +The best way to manage command name conflicts is to prevent them. When you name +your commands, use a unique name. For example, add your initials or company +name acronym to the nouns in your commands. + +Also, when you import commands into your session from a PowerShell +module or from another session, use the `Prefix` parameter of the +[Import-Module](../../Microsoft.PowerShell.Core/Import-Module.md) or + +[Import-PSSession](../../Microsoft.PowerShell.Utility/Import-PSSession.md) +cmdlet to add a prefix to the nouns in the names of commands. + +For example, the following command avoids any conflict with the `Get-Date` +and `Set-Date` cmdlets that come with PowerShell when you import the +`DateFunctions` module. + +```powershell +Import-Module -Name DateFunctions -Prefix ZZ +``` + +For more information, see `Import-Module` and `Import-PSSession` below. + +## See also + +- [about_Path_Syntax](about_Path_Syntax.md) +- [about_Aliases](about_Aliases.md) +- [about_Functions](about_Functions.md) +- [Alias-Provider](../../Microsoft.PowerShell.Core/About/about_Alias_Provider.md) +- [Function-Provider](../../Microsoft.PowerShell.Core/About/about_Function_Provider.md) +- [Get-Command](../../Microsoft.PowerShell.Core/Get-Command.md) +- [Import-Module](../../Microsoft.PowerShell.Core/Import-Module.md) +- [Import-PSSession](../../Microsoft.PowerShell.Utility/Import-PSSession.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Command_Syntax.md b/reference/7/Microsoft.PowerShell.Core/About/about_Command_Syntax.md new file mode 100644 index 000000000000..06b7d6c5c6b9 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Command_Syntax.md @@ -0,0 +1,315 @@ +--- +ms.date: 06/27/2017 +schema: 2.0.0 +keywords: powershell,cmdlet +title: about_Command_Syntax +--- +# About Command Syntax + +## SHORT DESCRIPTION +Describes the syntax diagrams that are used in PowerShell. + +## LONG DESCRIPTION + +The [Get-Help](../../Microsoft.PowerShell.Core/Get-Help.md) and +[Get-Command](../../Microsoft.PowerShell.Core/Get-Command.md) cmdlets display +syntax diagrams to help you construct commands correctly. This topic +explains how to interpret the syntax diagrams. + +## SYNTAX DIAGRAMS + +Each paragraph in a command syntax diagram represents a valid form of the +command. + +To construct a command, follow the syntax diagram from left to right. Select +from among the optional parameters and provide values for the placeholders. + +PowerShell uses the following notation for syntax diagrams. + +```powershell + - +[- ] +[-] +[-] +``` + +The following is the syntax for the [New-Alias](../../Microsoft.PowerShell.Utility/New-Alias.md) +cmdlet. + +```powershell +New-Alias [-Name] [-Value] [-Description ] +[-Force] [-Option {None | ReadOnly | Constant | Private | AllScope}] +[-PassThru] [-Scope ] [-Confirm] [-WhatIf] [] +``` + +The syntax is capitalized for readability, but PowerShell is +case-insensitive. + +The syntax diagram has the following elements. + +## Command name + +Commands always begin with a command name, such as `New-Alias`. Type the +command name or its alias, such a "gcm" for `Get-Command`. + +## Parameters + +The parameters of a command are options that determine what the command does. +Some parameters take a "value" which is user input to the command. + +For example, the `Get-Help` command has a **Name** parameter that lets you +specify the name of the topic for which help is displayed. The topic name is +the value of the **Name** parameter. + +In a PowerShell command, parameter names always begin with a hyphen. +The hyphen tells PowerShell that the item in the command is a +parameter name. + +For example, to use the Name parameter of `New-Alias`, you type the following: + +```powershell +-Name +``` + +Parameters can be mandatory or optional. In a syntax diagram, optional items +are enclosed in brackets `[ ]`. + +For more information about parameters, see +[about_Parameters](about_Parameters.md). + +## Parameter Values + +A parameter value is the input that the parameter takes. Because Windows +PowerShell is based on the Microsoft .NET Framework, parameter values are +represented in the syntax diagram by their .NET type. + +For example, the Name parameter of `Get-Help` takes a "String" value, which is +a text string, such as a single word or multiple words enclosed in quotation +marks. + +```powershell +[-Name] +``` + +The .NET type of a parameter value is enclosed in angle brackets `< >` to +indicate that it is placeholder for a value and not a literal that you type in +a command. + +To use the parameter, replace the .NET type placeholder with an object that +has the specified .NET type. + +For example, to use the **Name** parameter, type "-Name" followed by a string, +such as the following: + +```powershell +-Name MyAlias +``` + +## Parameters with no values + +Some parameters do not accept input, so they do not have a parameter value. +Parameters without values are called "switch parameters" because they work +like on/off switches. You include them (on) or you omit them (off) from a +command. + +To use a switch parameter, just type the parameter name, preceded by a hyphen. + +For example, to use the **WhatIf** parameter of the `New-Alias` cmdlet, type +the following: + +```powershell +-WhatIf +``` + +## Parameter Sets + +The parameters of a command are listed in parameter sets. Parameter sets look +like the paragraphs of a syntax diagram. + +The `New-Alias` cmdlet has one parameter set, but many cmdlets have multiple +parameter sets. Some of the cmdlet parameters are unique to a parameter set, +and others appear in multiple parameter sets. Each parameter set represents +the format of a valid command. A parameter set includes only parameters that +can be used together in a command. If parameters cannot be used in the same +command, they appear in separate parameter sets. + +For example, the [Get-Random](../../Microsoft.PowerShell.Utility/Get-Random.md) +cmdlet has the following parameter sets: + +```powershell +Get-Random [[-Maximum] ] [-Minimum ] [-SetSeed ] +[] + +Get-Random [-InputObject] [-Count ] [-SetSeed ] +[] +``` + +The first parameter set, which returns a random number, has the **Minimum** +and **Maximum** parameters. The second parameter set, which returns a randomly +selected object from a set of objects, includes the **InputObject** and +**Count** parameters. Both parameter sets have the **SetSeed** parameter and +the common parameters. + +These parameter sets indicate that you can use the **InputObject** and +**Count** parameters in the same command, but you cannot use the **Maximum** +and **Count** parameters in the same command. + +You indicate which parameter set you want to use by using the parameters in +that parameter set. + +However, every cmdlet also has a default parameter set. The default parameter +set is used when you do not specify parameters that are unique to a parameter +set. For example, if you use `Get-Random` without parameters, Windows +PowerShell assumes that you are using the **Number** parameter set and it +returns a random number. + +In each parameter set, the parameters appear in position order. The order of +parameters in a command matters only when you omit the optional parameter +names. When parameter names are omitted, PowerShell assigns values to +parameters by position and type. For more information about parameter +position, see `about_Parameters`. + +## Symbols in Syntax Diagrams + +The syntax diagram lists the command name, the command parameters, and the +parameter values. It also uses symbols to show how to construct a valid +command. + +The syntax diagrams use the following symbols: + +- A hyphen `-` indicates a parameter name. In a command, type the hyphen + immediately before the parameter name with no intervening spaces, as shown + in the syntax diagram. + + For example, to use the **Name** parameter of `New-Alias`, type: + + ```powershell + -Name + ``` + +- Angle brackets `<>` indicate placeholder text. You do not type the angle + brackets or the placeholder text in a command. Instead, you replace it + with the item that it describes. + + Angle brackets are used to identify the .NET type of the value that a + parameter takes. For example, to use the **Name** parameter of the + `New-Alias` cmdlet, you replace the `` with a string, which is a + single word or a group of words that are enclosed in quotation marks. + +- Brackets `[ ]` indicate optional items. A parameter and its value can be + optional, or the name of a required parameter can be optional. + + For example, the **Description** parameter of `New-Alias` and its value are + enclosed in brackets because they are both optional. + + ```powershell + [-Description ] + ``` + + The brackets also indicate that the Name parameter value `` is + required, but the parameter name, "Name", is optional. + + ```powershell + [-Name] + ``` + +- A right and left bracket `[]` appended to a .NET type indicates that the + parameter can accept one or multiple values of that type. Enter the values + in a comma-separated list. + + For example, the **Name** parameter of the `New-Alias` cmdlet takes only + one string, but the **Name** parameter of + [Get-Process](../../Microsoft.PowerShell.Management/Get-Process.md) can take + one or many strings. + + ```powershell + New-Alias [-Name] + + New-Alias -Name MyAlias + ``` + + ```powershell + Get-Process [-Name] + + Get-Process -Name Explorer, Winlogon, Services + ``` + +- Braces `{}` indicate an "enumeration," which is a set of valid values for + a parameter. + + The values in the braces are separated by vertical bars `|`. These bars + indicate an "exclusive OR" choice, meaning that you can choose only one + value from the set of values that are listed inside the braces. + + For example, the syntax for the `New-Alias` cmdlet includes the following + value enumeration for the **Option** parameter: + + ```powershell + -Option {None | ReadOnly | Constant | Private | AllScope} + ``` + + The braces and vertical bars indicate that you can choose any one of the + listed values for the **Option** parameter, such as "ReadOnly" or + "AllScope". + + ```powershell + -Option ReadOnly + ``` + +## Optional Items + +Brackets `[]` surround optional items. For example, in the `New-Alias` cmdlet +syntax description, the **Scope** parameter is optional. This is indicated in +the syntax by the brackets around the parameter name and type: + +```powershell +[-Scope ] +``` + +Both the following examples are correct uses of the `New-Alias` cmdlet: + +```powershell +New-Alias -Name utd -Value Update-TypeData +New-Alias -Name utd -Value Update-TypeData -Scope Global +``` + +A parameter name can be optional even if the value for that parameter is +required. This is indicated in the syntax by the brackets around the parameter +name but not the parameter type, as in this example from the `New-Alias` +cmdlet: + +```powershell +[-Name] [-Value] +``` + +The following commands correctly use the `New-Alias` cmdlet. The commands +produce the same result. + +```powershell +New-Alias -Name utd -Value Update-TypeData +New-Alias -Name utd Update-TypeData +New-Alias utd -Value Update-TypeData +New-Alias utd Update-TypeData +``` + +If the parameter name is not included in the statement as typed, Windows +PowerShell tries to use the position of the arguments to assign the values to +parameters. + +The following example is not complete: + +```powershell +New-Alias utd +``` + +This cmdlet requires values for both the **Name** and **Value** parameters. + +In syntax examples, brackets are also used in naming and casting to .NET +Framework types. In this context, brackets do not indicate an element is +optional. + +## SEE ALSO + +- [about_Parameters](about_Parameters.md) +- [Get-Command](../../Microsoft.PowerShell.Core/Get-Command.md) +- [Get-Help](../../Microsoft.PowerShell.Core/Get-Help.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Comment_Based_Help.md b/reference/7/Microsoft.PowerShell.Core/About/about_Comment_Based_Help.md new file mode 100644 index 000000000000..518db3b4891a --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Comment_Based_Help.md @@ -0,0 +1,856 @@ +--- +ms.date: 06/09/2017 +schema: 2.0.0 +keywords: powershell,cmdlet +title: about_Comment_Based_Help +--- +# About Comment Based Help + +## SHORT DESCRIPTION +Describes how to write comment-based help topics for functions and scripts. + +## LONG DESCRIPTION + +You can write comment-based help topics for functions and scripts by using +special help comment keywords. + +The [Get-Help](../Get-Help.md) cmdlet displays comment-based help in the same +format in which it displays the cmdlet help topics that are generated from XML +files. Users can use all of the parameters of `Get-Help`, such as +**Detailed**, **Full**, **Examples**, and **Online**, to display the contents +of comment-based help. + +You can also write XML-based help files for functions and scripts. To +enable the `Get-Help` cmdlet to find the XML-based help file for a function +or script, use the "ExternalHelp" keyword. Without this keyword, `Get-Help` +cannot find XML-based help topics for functions or scripts. + +This topic explains how to write help topics for functions and scripts. For +information about how to display help topics for functions and scripts, see +[Get-Help](../Get-Help.md). + +The [Update-Help](../Update-Help.md) and [Save-Help](../Save-Help.md) cmdlets +work only on XML files. Updatable Help does not support comment-based help +topics. + +## SYNTAX FOR COMMENT-BASED HELP + +The syntax for comment-based help is as follows: + +``` +. + +``` + +or + +``` +<# +. + +#> +``` + +Comment-based help is written as a series of comments. You can type a comment +symbol `#` before each line of comments, or you can use the `<#` and `#>` +symbols to create a comment block. All the lines within the comment block are +interpreted as comments. + +All of the lines in a comment-based help topic must be contiguous. If a +comment-based help topic follows a comment that is not part of the help +topic, there must be at least one blank line between the last non-help +comment line and the beginning of the comment-based help. + +Keywords define each section of comment-based help. Each comment-based help +keyword is preceded by a dot `.`. The keywords can appear in any order. The +keyword names are not case-sensitive. + +For example, the "Description" keyword precedes a description of a function or +script. + +``` +<# +.Description +Get-Function displays the name and syntax of all functions in the session. +#> +``` + +The comment block must contain at least one keyword. Some of the keywords, +such as "EXAMPLE", can appear many times in the same comment block. The help +content for each keyword begins on the line after the keyword and can span +multiple lines. + +## SYNTAX FOR COMMENT-BASED HELP IN FUNCTIONS + +Comment-based help for a function can appear in one of three locations: + +- At the beginning of the function body. +- At the end of the function body. +- Before the Function keyword. There cannot be more than one blank line + between the last line of the function help and the Function keyword. + +For example: + +```powershell +function Get-Function +{ +<# +. + +#> + + # function logic +} +``` + +or + +```powershell +function Get-Function +{ + # function logic + +<# +. + +#> +} +``` + +or + +```powershell +<# +. + +#> +function Get-Function { } +``` + +## SYNTAX FOR COMMENT-BASED HELP IN SCRIPTS + +Comment-based help for a script can appear in one of the following two +locations in the script. + +- At the beginning of the script file. Script help can be preceded in the + script only by comments and blank lines. + + If the first item in the script body (after the help) is a function + declaration, there must be at least two blank lines between the end of the + script help and the function declaration. Otherwise, the help is interpreted + as being help for the function, not help for the script. + +- At the end of the script file. However, if the script is signed, place + Comment-based help at the beginning of the script file. The end of the script + is occupied by the signature block. + +For example: + +```powershell +<# +. + +#> + + +function Get-Function { } +``` + +or + +```powershell +function Get-Function { } + +<# +. + +#> +``` + +## SYNTAX FOR COMMENT-BASED HELP IN SCRIPT MODULES + +In a script module `.psm1`, comment-based help uses the syntax for functions, +not the syntax for scripts. You cannot use the script syntax to provide help +for all functions defined in a script module. + +For example, if you are using the "ExternalHelp" keyword to identify the +XML-based help files for the functions in a script module, you must add an +"ExternalHelp" comment to each function. + +```powershell +# .ExternalHelp +function +{ + ... +} +``` + +## COMMENT-BASED HELP KEYWORDS + +The following are valid comment-based help keywords. They are listed in the +order in which they typically appear in a help topic along with their intended +use. These keywords can appear in any order in the comment-based help, and +they are not case-sensitive. + +### .SYNOPSIS + +A brief description of the function or script. This keyword can be used +only once in each topic. + +### .DESCRIPTION + +A detailed description of the function or script. This keyword can be +used only once in each topic. + +### .PARAMETER + +The description of a parameter. Add a ".PARAMETER" keyword for each parameter +in the function or script syntax. + +Type the parameter name on the same line as the ".PARAMETER" keyword. Type the +parameter description on the lines following the ".PARAMETER" keyword. Windows +PowerShell interprets all text between the ".PARAMETER" line and the next +keyword or the end of the comment block as part of the parameter description. +The description can include paragraph breaks. + +``` +.PARAMETER +``` + +The Parameter keywords can appear in any order in the comment block, but the +function or script syntax determines the order in which the parameters (and +their descriptions) appear in help topic. To change the order, change the +syntax. + +You can also specify a parameter description by placing a comment in the +function or script syntax immediately before the parameter variable name. If +you use both a syntax comment and a Parameter keyword, the description +associated with the Parameter keyword is used, and the syntax comment is +ignored. + +### .EXAMPLE + +A sample command that uses the function or script, optionally followed by +sample output and a description. Repeat this keyword for each example. + +### .INPUTS + +The Microsoft .NET Framework types of objects that can be piped to the +function or script. You can also include a description of the input objects. + +### .OUTPUTS + +The .NET Framework type of the objects that the cmdlet returns. You can also +include a description of the returned objects. + +### .NOTES + +Additional information about the function or script. + +### .LINK + +The name of a related topic. The value appears on the line below the ".LINK" +keyword and must be preceded by a comment symbol `#` or included in the +comment block. + +Repeat the ".LINK" keyword for each related topic. + +This content appears in the Related Links section of the help topic. + +The "Link" keyword content can also include a Uniform Resource Identifier +(URI) to an online version of the same help topic. The online version opens +when you use the **Online** parameter of `Get-Help`. The URI must begin with +"http" or "https". + +### .COMPONENT + +The technology or feature that the function or script uses, or to which it is +related. This content appears when the `Get-Help` command includes the +**Component** parameter of `Get-Help`. + +### .ROLE + +The user role for the help topic. This content appears when the `Get-Help` +command includes the **Role** parameter of `Get-Help`. + +### .FUNCTIONALITY + +The intended use of the function. This content appears when the `Get-Help` +command includes the **Functionality** parameter of `Get-Help`. + +### .FORWARDHELPTARGETNAME + +Redirects to the help topic for the specified command. You can redirect users +to any help topic, including help topics for a function, script, cmdlet, or +provider. + +```powershell +# .FORWARDHELPTARGETNAME +``` + +### .FORWARDHELPCATEGORY + +Specifies the help category of the item in "ForwardHelpTargetName". Valid +values are "Alias", "Cmdlet", "HelpFile", "Function", "Provider", "General", +"FAQ", "Glossary", "ScriptCommand", "ExternalScript", "Filter", or "All". Use +this keyword to avoid conflicts when there are commands with the same name. + +```powershell +# .FORWARDHELPCATEGORY +``` + +### .REMOTEHELPRUNSPACE + +Specifies a session that contains the help topic. Enter a variable that +contains a "PSSession". This keyword is used by the +[Export-PSSession](../../Microsoft.PowerShell.Utility/Export-PSSession.md) +cmdlet to find the help topics for the exported commands. + +```powershell +# .REMOTEHELPRUNSPACE +``` + +### .EXTERNALHELP + +Specifies an XML-based help file for the script or function. + +```powershell +# .EXTERNALHELP +``` + +The "ExternalHelp" keyword is required when a function or script is documented +in XML files. Without this keyword, `Get-Help` cannot find the XML-based help +file for the function or script. + +The "ExternalHelp" keyword takes precedence over other comment-based help +keywords. If "ExternalHelp" is present, `Get-Help` does not display +comment-based help, even if it cannot find a help topic that matches the value +of the "ExternalHelp" keyword. + +If the function is exported by a module, set the value of the "ExternalHelp" +keyword to a file name without a path. `Get-Help` looks for the specified file +name in a language-specific subdirectory of the module directory. There are no +requirements for the name of the XML-based help file for a function, but a +best practice is to use the following format: + +``` +-help.xml +``` + +If the function is not included in a module, include a path to the XML-based +help file. If the value includes a path and the path contains +UI-culture-specific subdirectories, `Get-Help` searches the subdirectories +recursively for an XML file with the name of the script or function in +accordance with the language fallback standards established for Windows, just +as it does in a module directory. + +For more information about the cmdlet help XML-based help file format, see +[How to Write Cmdlet Help](https://go.microsoft.com/fwlink/?LinkID=123415) in +the MSDN library. + +## AUTOGENERATED CONTENT + +The name, syntax, parameter list, parameter attribute table, common +parameters, and remarks are automatically generated by the `Get-Help` cmdlet. + +### Name + +The "Name" section of a function help topic is taken from the function name in +the function syntax. The "Name" of a script help topic is taken from the +script file name. To change the name or its capitalization, change the +function syntax or the script file name. + +### Syntax + +The "Syntax" section of the help topic is generated from the function or +script syntax. To add detail to the help topic syntax, such as the .NET +Framework type of a parameter, add the detail to the syntax. If you do not +specify a parameter type, the "Object" type is inserted as the default value. + +### Parameter List + +The "Parameter list" in the help topic is generated from the function or +script syntax and from the descriptions that you add by using the "Parameters" +keyword. The function parameters appear in the "Parameters" section of the +help topic in the same order that they appear in the function or script +syntax. The spelling and capitalization of parameter names is also taken from +the syntax; it is not affected by the parameter name specified by the +"Parameter" keyword. + +### Common Parameters + +The "Common parameters" are added to the syntax and parameter list of the help +topic, even if they have no effect. For more information about the common +parameters, see [about_CommonParameters](about_CommonParameters.md). + +### Parameter Attribute Table + +`Get-Help` generates the table of parameter attributes that appears when you +use the **Full** or **Parameter** parameter of `Get-Help`. The value of the +"Required", "Position", and "Default" value attributes is taken from the +function or script syntax. + +Default values and a value for "Accept Wildcard characters" do not appear in +the "Parameter attribute table" even when they are defined in the function or +script. To help users, provide this information in the parameter description. + +### Remarks + +The "Remarks" section of the help topic is automatically generated from the +function or script name. You cannot change or affect its content. + +## EXAMPLES + +### Comment-based Help for a Function + +The following sample function includes comment-based help: + +```powershell +function Add-Extension +{ +param ([string]$Name,[string]$Extension = "txt") +$name = $name + "." + $extension +$name + +<# +.SYNOPSIS + +Adds a file name extension to a supplied name. + +.DESCRIPTION + +Adds a file name extension to a supplied name. +Takes any strings for the file name or extension. + +.PARAMETER Name +Specifies the file name. + +.PARAMETER Extension +Specifies the extension. "Txt" is the default. + +.INPUTS + +None. You cannot pipe objects to Add-Extension. + +.OUTPUTS + +System.String. Add-Extension returns a string with the extension +or file name. + +.EXAMPLE + +PS> extension -name "File" +File.txt + +.EXAMPLE + +PS> extension -name "File" -extension "doc" +File.doc + +.EXAMPLE + +PS> extension "File" "doc" +File.doc + +.LINK + +http://www.fabrikam.com/extension.html + +.LINK + +Set-Item +#> +} +``` + +The results are as follows: + +```powershell +Get-Help -Name "Add-Extension" -Full +``` + +```Output +NAME + +Add-Extension + +SYNOPSIS + +Adds a file name extension to a supplied name. + +SYNTAX + +Add-Extension [[-Name] ] [[-Extension] ] +[] + +DESCRIPTION + +Adds a file name extension to a supplied name. Takes any strings for the +file name or extension. + +PARAMETERS + +-Name +Specifies the file name. + +Required? false +Position? 0 +Default value +Accept pipeline input? false +Accept wildcard characters? + +-Extension +Specifies the extension. "Txt" is the default. + +Required? false +Position? 1 +Default value +Accept pipeline input? false +Accept wildcard characters? + + +This cmdlet supports the common parameters: -Verbose, -Debug, +-ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable, +-OutBuffer and -OutVariable. For more information, type +"get-help about_commonparameters". + +INPUTS +None. You cannot pipe objects to Add-Extension. + +OUTPUTS + +System.String. Add-Extension returns a string with the extension or +file name. + +Example 1 + +PS> extension -name "File" +File.txt + +Example 2 + +PS> extension -name "File" -extension "doc" +File.doc + +Example 3 + +PS> extension "File" "doc" +File.doc + +RELATED LINKS + +http://www.fabrikam.com/extension.html +Set-Item +``` + +### Parameter Descriptions in Function Syntax + +This example is the same as the previous one, except that the parameter +descriptions are inserted in the function syntax. This format is most useful +when the descriptions are brief. + +```powershell +function Add-Extension +{ +param +( + +[string] +#Specifies the file name. +$name, + +[string] +#Specifies the file name extension. "Txt" is the default. +$extension = "txt" +) + +$name = $name + "." + $extension +$name + +<# +.SYNOPSIS + +Adds a file name extension to a supplied name. + +.DESCRIPTION + +Adds a file name extension to a supplied name. Takes any strings for the +file name or extension. + +.INPUTS + +None. You cannot pipe objects to Add-Extension. + +.OUTPUTS + +System.String. Add-Extension returns a string with the extension or +file name. + +.EXAMPLE + +PS> extension -name "File" +File.txt + +.EXAMPLE + +PS> extension -name "File" -extension "doc" +File.doc + +.EXAMPLE + +PS> extension "File" "doc" +File.doc + +.LINK + +http://www.fabrikam.com/extension.html + +.LINK + +Set-Item +#> +} +``` + +### Comment-based Help for a Script + +The following sample script includes comment-based help. Notice the blank +lines between the closing `#>` and the `Param` statement. In a script that +does not have a `Param` statement, there must be at least two blank lines +between the final comment in the help topic and the first function +declaration. Without these blank lines, `Get-Help` associates the help topic +with the function, not the script. + +```powershell +<# +.SYNOPSIS + +Performs monthly data updates. + +.DESCRIPTION + +The Update-Month.ps1 script updates the registry with new data generated +during the past month and generates a report. + +.PARAMETER InputPath +Specifies the path to the CSV-based input file. + +.PARAMETER OutputPath +Specifies the name and path for the CSV-based output file. By default, +MonthlyUpdates.ps1 generates a name from the date and time it runs, and +saves the output in the local directory. + +.INPUTS + +None. You cannot pipe objects to Update-Month.ps1. + +.OUTPUTS + +None. Update-Month.ps1 does not generate any output. + +.EXAMPLE + +PS> .\Update-Month.ps1 + +.EXAMPLE + +PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv + +.EXAMPLE + +PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -outputPath ` +C:\Reports\2009\January.csv +#> + +param ([string]$InputPath, [string]$OutPutPath) + +function Get-Data { } +... +``` + +The following command gets the script help. Because the script is not in a +directory that is listed in the "Path" environment variable, the `Get-Help` +command that gets the script help must specify the script path. + +```powershell +Get-Help -Path .\update-month.ps1 -Full +``` + +```Output +# NAME + +C:\ps-test\Update-Month.ps1 + +# SYNOPSIS + +Performs monthly data updates. + +# SYNTAX + +C:\ps-test\Update-Month.ps1 [-InputPath] [[-OutputPath] +] [] + +# DESCRIPTION + +The Update-Month.ps1 script updates the registry with new data +generated during the past month and generates a report. + +# PARAMETERS + +-InputPath +Specifies the path to the CSV-based input file. + +Required? true +Position? 0 +Default value +Accept pipeline input? false +Accept wildcard characters? + +-OutputPath +Specifies the name and path for the CSV-based output file. By +default, MonthlyUpdates.ps1 generates a name from the date +and time it runs, and saves the output in the local directory. + +Required? false +Position? 1 +Default value +Accept pipeline input? false +Accept wildcard characters? + + +This cmdlet supports the common parameters: -Verbose, -Debug, +-ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable, +-OutBuffer and -OutVariable. For more information, type, +"get-help about_commonparameters". + +# INPUTS + +None. You cannot pipe objects to Update-Month.ps1. + +# OUTPUTS + +None. Update-Month.ps1 does not generate any output. + +Example 1 + +PS> .\Update-Month.ps1 + +Example 2 + +PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv + +Example 3 + +PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -outputPath +C:\Reports\2009\January.csv + +# RELATED LINKS +``` + +### Redirecting to an XML File + +You can write XML-based help topics for functions and scripts. Although +comment-based help is easier to implement, XML-based help is required for +Updatable Help and to provide help topics in multiple languages. + +The following example shows the first few lines of the Update-Month.ps1 +script. The script uses the "ExternalHelp" keyword to specify the path to an +XML-based help topic for the script. + +Note that the value of the "ExternalHelp" keyword appears on the same +line as the keyword. Any other placement is ineffective. + +```powershell +# .ExternalHelp C:\MyScripts\Update-Month-Help.xml + +param ([string]$InputPath, [string]$OutPutPath) +function Get-Data { } +... +``` + +The following examples show three valid placements of the "ExternalHelp" +keyword in a function. + +```powershell +function Add-Extension +{ +# .ExternalHelp C:\ps-test\Add-Extension.xml + +param ([string] $name, [string]$extension = "txt") +$name = $name + "." + $extension +$name +} +``` + +```powershell +function Add-Extension +{ +param ([string] $name, [string]$extension = "txt") +$name = $name + "." + $extension +$name + +# .ExternalHelp C:\ps-test\Add-Extension.xml +} +``` + +```powershell +# .ExternalHelp C:\ps-test\Add-Extension.xml +function Add-Extension +{ +param ([string] $name, [string]$extension = "txt") +$name = $name + "." + $extension +$name +} +``` + +### Redirecting to a Different Help Topic + +The following code is an excerpt from the beginning of the built-in help +function in PowerShell, which displays one screen of help text at a time. +Because the help topic for the `Get-Help` cmdlet describes the help +function, the help function uses the "ForwardHelpTargetName" and +"ForwardHelpCategory" keywords to redirect the user to the `Get-Help` cmdlet +help topic. + +```powershell +function help +{ + +<# +.FORWARDHELPTARGETNAME Get-Help +.FORWARDHELPCATEGORY Cmdlet +#> +[CmdletBinding(DefaultParameterSetName='AllUsersView')] +param( +[Parameter(Position=0, ValueFromPipelineByPropertyName=$true)] +[System.String] +${Name}, +... +``` + +The following command uses this feature: + +```powershell +Get-Help -Name help +``` + +```Output +NAME + +Get-Help + +SYNOPSIS + +Displays information about PowerShell cmdlets and concepts. +... +``` + +## SEE ALSO + +[about_Functions](about_Functions.md) + +[about_Functions_Advanced_Parameters](about_Functions_Advanced_Parameters.md) + +[about_Scripts](about_Scripts.md) + +[How to Write Cmdlet Help](https://go.microsoft.com/fwlink/?LinkID=123415) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_CommonParameters.md b/reference/7/Microsoft.PowerShell.Core/About/about_CommonParameters.md new file mode 100644 index 000000000000..f397de4bb797 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_CommonParameters.md @@ -0,0 +1,531 @@ +--- +ms.date: 03/22/2019 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_CommonParameters +--- +# About CommonParameters + +## SHORT DESCRIPTION + +Describes the parameters that can be used with any cmdlet. + +## LONG DESCRIPTION + +The common parameters are a set of cmdlet parameters that you can use with any +cmdlet. They're implemented by PowerShell, not by the cmdlet developer, and +they're automatically available to any cmdlet. + +You can use the common parameters with any cmdlet, but they might not have an +effect on all cmdlets. For example, if a cmdlet doesn't generate any verbose +output, using the **Verbose** common parameter has no effect. + +The common parameters are also available on advanced functions that use the +**CmdletBinding** attribute or the **Parameter** attribute. + +Several common parameters override system defaults or preferences that you set +by using the PowerShell preference variables. Unlike the preference variables, +the common parameters affect only the commands in which they're used. + +In addition to the common parameters, many cmdlets offer the WhatIf and Confirm +risk mitigation parameters. Cmdlets that involve risk to the system or to user +data usually offer these parameters. + +The following list displays the common parameters. Their aliases are listed in +parentheses. + +- Debug (db) +- ErrorAction (ea) +- ErrorVariable (ev) +- InformationAction (infa) +- InformationVariable (iv) +- OutVariable (ov) +- OutBuffer (ob) +- PipelineVariable (pv) +- Verbose (vb) +- WarningAction (wa) +- WarningVariable (wv) + +The risk mitigation parameters are: + +- WhatIf (wi) +- Confirm (cf) + +For more information about preference variables, type: help [about_Preference_Variables](./about_Preference_Variables) + +### COMMON PARAMETER DESCRIPTIONS + +#### Debug + +The alias for **Debug** is **db**. + +Displays programmer-level detail about the operation done by the command. This +parameter works only when the command generates a debugging message. For +example, this parameter works when a command contains the **Write-Debug** +cmdlet. + +The **Debug** parameter overrides the value of the `$DebugPreference` variable +for the current command, setting the value of `$DebugPreference` to +**Continue**. Because the default value of the `$DebugPreference` variable is +**SilentlyContinue**, debugging messages aren't displayed by default. + +`-Debug:$true` has the same effect as **-Debug**. Use `-Debug:$false` to +suppress the display of debugging messages when `$DebugPreference` isn't +**SilentlyContinue**, which is the default. + +#### ErrorAction + +The alias for **ErrorAction** is **ea**. + +Determines how the cmdlet responds to a non-terminating error from the command. +This parameter works only when the command generates a non-terminating error, +such as those from the `Write-Error` cmdlet. + +The **ErrorAction** parameter overrides the value of the `$ErrorActionPreference` +variable for the current command. Because the default value of the +`$ErrorActionPreference` variable is **Continue**, error messages are displayed +and execution continues unless you use the **ErrorAction** parameter. + +The **ErrorAction** parameter has no effect on terminating errors (such as +missing data, parameters that aren't valid, or insufficient permissions) that +prevent a command from completing successfully. + +`-ErrorAction:Continue` display the error message and continues executing the +command. `Continue` is the default. + +`-ErrorAction:Ignore` suppresses the error message and continues executing the +command. Unlike **SilentlyContinue**, **Ignore** doesn't add the error message +to the `$Error` automatic variable. The **Ignore** value is introduced in +PowerShell 3.0. + +`-ErrorAction:Inquire` displays the error message and prompts you for +confirmation before continuing execution. This value is rarely used. + +`-ErrorAction:SilentlyContinue` suppresses the error message and continues +executing the command. + +`-ErrorAction:Stop` displays the error message and stops executing the command. + +`-ErrorAction:Suspend` isn't supported on PowerShell Core as it is only +available for workflows. + +#### ErrorVariable + +The alias for **ErrorVariable** is **ev**. + +**ErrorVariable** stores error messages about the command in the specified +variable and in the `$Error` automatic variable. For more information, type +the following command: + +```powershell +get-help about_Automatic_Variables +``` + +By default, new error messages overwrite error messages that are already stored +in the variable. To append the error message to the variable content, type a +plus sign (+) before the variable name. + +For example, the following command creates the `$a` variable and then stores any +errors in it: + +```powershell +Get-Process -Id 6 -ErrorVariable a +``` + +The following command adds any error messages to the $a variable: + +```powershell +Get-Process -Id 2 -ErrorVariable +a +``` + +The following command displays the contents of $a: + +```powershell +$a +``` + +You can use this parameter to create a variable that contains only error +messages from specific commands. The `$Error` automatic variable contains error +messages from all the commands in the session. You can use array notation, such +as `$a[0]` or `$error[1,2]` to refer to specific errors stored in the variables. + +#### InformationAction + +The alias for **InformationAction** is **ia**. + +Introduced in PowerShell 5.0. Within the command or script in which it's used, +the **InformationAction** common parameter overrides the value of the +`$InformationPreference` preference variable, which by default is set to +**SilentlyContinue**. When you use `Write-Information` in a script with +**InformationAction**, `Write-Information` values are shown depending on the +value of the **InformationAction** parameter. For more information about +`$InformationPreference`, see [about_Preference_Variables](./about_Preference_Variables.md). + +`-InformationAction:Stop` stops a command or script at an occurrence of the +`Write-Information` command. + +`-InformationAction:Ignore` suppresses the informational message and continues +running the command. Unlike **SilentlyContinue**, **Ignore** completely forgets the +informational message; it doesn't add the informational message to the +information stream. + +`-InformationAction:Inquire` displays the informational message that you specify +in a `Write-Information` command, then asks whether you want to continue. + +`-InformationAction:Continue` displays the informational message, and continues +running. + +`-InformationAction:Suspend` isn't supported on PowerShell Core as it is only +available for workflows. + +`-InformationAction:SilentlyContinue` no effect as the informational message +aren't (Default) displayed, and the script continues without interruption. + +#### InformationVariable + +The alias for **InformationVariable** is **iv**. + +Introduced in PowerShell 5.0. Within the command or script in which it's used, +the **InformationVariable** common parameter stores in a variable a string that +you specify by adding the `Write-Information` command. `Write-Information` +values are shown depending on the value of the **InformationAction** common +parameter; if you don't add the **InformationAction** common parameter, +`Write-Information` strings are shown depending on the value of the +`$InformationPreference` preference variable. For more information about +`$InformationPreference`, see [about_Preference_Variables](./about_Preference_Variables.md). + +#### OutBuffer + +The alias for **OutBuffer** is **ob** and takes a **System.Int32** value. + +Determines the number of objects to accumulate in a buffer before any objects +are sent through the pipeline. If you omit this parameter, objects are sent as +they're generated. + +This resource management parameter is designed for advanced users. When you use +this parameter, PowerShell doesn't call the next cmdlet in the pipeline until +the number of objects generated equals OutBuffer + 1. Thereafter, it sends all +objects as they're generated. + +#### OutVariable + +The alias for **OutVariable** is **ov**. + +Stores output objects from the command in the specified variable and displays it +at the command line. + +To add the output to the variable, instead of replacing any output that might +already be stored there, type a plus sign (+) before the variable name. + +For example, the following command creates the `$out` variable and stores the +process object in it: + +```powershell +Get-Process PowerShell -OutVariable out +``` + +The following command adds the process object to the `$out` variable: + +```powershell +Get-Process iexplore -OutVariable +out +``` + +The following command displays the contents of the `$out` variable: + +```powershell +$out +``` + +#### PipelineVariable + +The alias for **PipelineVariable** is **pv** and takes a **string** value. + +**PipelineVariable** stores the value of the current pipeline element as a +variable, for any named command as it flows through the pipeline. + +Valid values are strings, the same as for any variable names. + +The following is an example of how **PipelineVariable** works. In this example, +the **PipelineVariable** parameter is added to a `Foreach-Object` command to +store the results of the command in variables. A range of numbers, 1 to 10, are +piped into the first `Foreach-Object` command, the results of which are stored +in a variable named **Left**. + +The results of the first `Foreach-Object` command are piped into a second +`Foreach-Object` command, which filters the objects returned by the first +`Foreach-Object` command. The results of the second command are stored in a +variable named **Right**. + +In the third `Foreach-Object` command, the results of the first two +`Foreach-Object` piped commands, represented by the variables **Left** and +**Right**, are processed by using a multiplication operator. The command instructs +objects stored in the **Left** and **Right** variables to be multiplied, and +specifies that the results should be displayed as "Left range member * Right +range member = product". + +```powershell +1..10 | Foreach-Object -PipelineVariable Left -Process { $_ } | + Foreach-Object -PV Right -Process { 1..10 } | + Foreach-Object -Process { "$Left * $Right = " + ($Left*$Right) } +``` + +```output +1 * 1 = 1 +1 * 2 = 2 +1 * 3 = 3 +1 * 4 = 4 +1 * 5 = 5 +... +``` + +#### Verbose + +The alias for **Verbose** is **vb**. + +Displays detailed information about the operation done by the command. This +information resembles the information in a trace or in a transaction log. This +parameter works only when the command generates a verbose message. For example, +this parameter works when a command contains the `Write-Verbose` cmdlet. + +The **Verbose** parameter overrides the value of the `$VerbosePreference` +variable for the current command. Because the default value of the +`$VerbosePreference` variable is **SilentlyContinue**, verbose messages aren't +displayed by default. + +`-Verbose:$true` has the same effect as `-Verbose` + +`-Verbose:$false` suppresses the display of verbose messages. Use this parameter +when the value of `$VerbosePreference` isn't **SilentlyContinue** (the +default). + +#### WarningAction + +The alias for **WarningAction** is **wa**. + +Determines how the cmdlet responds to a warning from the command. **Continue** +is the default value. This parameter works only when the command generates a +warning message. For example, this parameter works when a command contains the +`Write-Warning` cmdlet. + +The **WarningAction** parameter overrides the value of the +`$WarningPreference` variable for the current command. Because the default +value of the `$WarningPreference` variable is **Continue**, warnings are +displayed and execution continues unless you use the **WarningAction** +parameter. + +`-WarningAction:Continue` displays the warning messages and continues executing +the command. `Continue` is the default. + +`-WarningAction:Inquire` displays the warning message and prompts you for +confirmation before continuing execution. This value is rarely used. + +`-WarningAction:SilentlyContinue` suppresses the warning message and continues +executing the command. + +`-WarningAction:Stop` displays the warning message and stops executing the +command. + +> [!NOTE] +> The `-WarningAction` parameter does not override the value of the +> `$WarningAction` preference variable when the parameter is used in a command +> to run a script or function. + +#### WarningVariable + +The alias for **WarningVariable** is **wv**. + +Stores warnings about the command in the specified variable. + +All generated warnings are saved in the variable even if the warnings aren't +displayed to the user. + +To append the warnings to the variable content, instead of replacing any +warnings that might already be stored there, type a plus sign (+) before the +variable name. + +For example, the following command creates the `$a` variable and then stores any +warnings in it: + +```powershell +Get-Process -Id 6 -WarningVariable a +``` + +The following command adds any warnings to the `$a` variable: + +```powershell +Get-Process -Id 2 -WarningVariable +a +``` + +The following command displays the contents of `$a`: + +```powershell +$a +``` + +You can use this parameter to create a variable that contains only warnings from +specific commands. You can use array notation, such as `$a[0]` or `$warning[1,2]` +to refer to specific warnings stored in the variable. + +> [!NOTE] +> The **WarningVariable** parameter does not capture warnings from nested +calls in functions or scripts. + +### Risk Management Parameter Descriptions + +#### WhatIf + +The alias for **WhatIf** is **wi**. + +Displays a message that describes the effect of the command, instead of +executing the command. + +The **WhatIf** parameter overrides the value of the `$WhatIfPreference` variable +for the current command. Because the default value of the `$WhatIfPreference` +variable is 0 (disabled), **WhatIf** behavior isn't done without the +**WhatIf** parameter. For more information, type the following command: + +```powershell +Get-Help about_Preference_Variables +``` + +`-WhatIf:$true` has the same effect as `-WhatIf`. + +`-WhatIf:$false` suppresses the automatic WhatIf behavior that results when the +value of the `$WhatIfPreference` variable is 1. + +For example, the following command uses the `-WhatIf` parameter in a +`Remove-Item` command: + +```powershell +PS> Remove-Item Date.csv -WhatIf +``` + +Instead of removing the item, PowerShell lists the operations it would +do and the items that would be affected. This command produces the +following output: + +```output +What if: Performing operation "Remove File" on +Target "C:\ps-test\date.csv". +``` + +#### Confirm + +The alias for **Confirm** is **cf**. + +Prompts you for confirmation before executing the command. + +The **Confirm** parameter overrides the value of the `$ConfirmPreference` +variable for the current command. The default value is true. For more +information, type the following command: + +```powershell +Get-Help about_Preference_Variables +``` + +`-Confirm:$true` has the same effect as `-Confirm`. + +`-Confirm:$false` suppresses automatic confirmation, which occurs when the value +of `$ConfirmPreference` is less than or equal to the estimated risk of the +cmdlet. + +For example, the following command uses the **Confirm** parameter with a +`Remove-Item` command. Before removing the item, PowerShell lists the +operations it would do and the items that would be affected, and asks for +approval. + +```powershell +PS C:\ps-test> Remove-Item tmp*.txt -Confirm +``` + +This command produces the following output: + +```output +Confirm +Are you sure you want to perform this action? +Performing operation "Remove File" on Target " C:\ps-test\tmp1.txt +[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend +[?] Help (default is "Y"): +``` + +The Confirm response options are as follows: + +|Response |Result | +|---------------|-----------------------------------------------------------| +|Yes (Y) |Perform the action. | +|Yes to All (A) |Perform all actions and suppress subsequent Confirm queries| +| |for this command. | +|No (N): |Do not perform the action. | +|No to All (L): |Do not perform any actions and suppress subsequent Confirm | +| |queries for this command. | +|Suspend (S): |Pause the command and create a temporary session. | +|Help (?) |Display help for these options. | + +The **Suspend** option places the command on hold and creates a temporary nested +session in which you can work until you're ready to choose a Confirm option. The +command prompt for the nested session has two extra carets (>>) to indicate that +it's a child operation of the original parent command. You can run commands and +scripts in the nested session. To end the nested session and return to the +Confirm options for the original command, type "exit". + +In the following example, the **Suspend** option (S) is used to halt a command +temporarily while the user checks the help for a command parameter. After +obtaining the needed information, the user types "exit" to end the nested prompt +and then selects the Yes (y) response to the Confirm query. + +```powershell +PS C:\ps-test> New-Item -ItemType File -Name Test.txt -Confirm +``` + +```output +Confirm +Are you sure you want to perform this action? + +Performing operation "Create File" on Target "Destination: +C:\ps-test\test.txt". +[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default +is "Y"): s + +PS C:\ps-test> Get-Help New-Item -Parameter ItemType + +-ItemType +Specifies the provider-specified type of the new item. + +Required? false +Position? named +Default value +Accept pipeline input? true (ByPropertyName) +Accept wildcard characters? false + +PS C:\ps-test> exit + +Confirm +Are you sure you want to perform this action? +Performing operation "Create File" on Target "Destination: C:\ps-test\test +.txt". +[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (defau +lt is "Y"): y + +Directory: C:\ps-test + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 8/27/2010 2:41 PM 0 test.txt +``` + +## KEYWORDS + +about_Common_Parameters + +## SEE ALSO + +[about_Preference_Variables](about_Preference_Variables.md) + +[Write-Debug](../../Microsoft.PowerShell.Utility/Write-Debug.md) + +[Write-Warning](../../Microsoft.PowerShell.Utility/Write-Warning.md) + +[Write-Error](../../Microsoft.PowerShell.Utility/Write-Error.md) + +[Write-Verbose](../../Microsoft.PowerShell.Utility/Write-Verbose.md) diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Comparison_Operators.md b/reference/7/Microsoft.PowerShell.Core/About/about_Comparison_Operators.md new file mode 100644 index 000000000000..c6fba6f2b79a --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Comparison_Operators.md @@ -0,0 +1,651 @@ +--- +ms.date: 01/18/2019 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Comparison_Operators +--- +# About Comparison Operators + +## Short description +Describes the operators that compare values in PowerShell. + +## Long description + +Comparison operators let you specify conditions for comparing values and +finding values that match specified patterns. To use a comparison operator, +specify the values that you want to compare together with an operator that +separates these values. + +PowerShell includes the following comparison operators: + +| Type | Operators | Description | +| ----------- | ------------ | --------------------------------------------| +| Equality | -eq | equals | +| | -ne | not equals | +| | -gt | greater than | +| | -ge | greater than or equal | +| | -lt | less than | +| | -le | less than or equal | +| | | | +| Matching | -like | Returns true when string matches wildcard | +| | | pattern | +| | -notlike | Returns true when string does not match | +| | | wildcard pattern | +| | -match | Returns true when string matches regex | +| | | pattern; $matches contains matching strings | +| | -notmatch | Returns true when string does not match | +| | | regex pattern; $matches contains matching | +| | | strings | +| | | | +| Containment | -contains | Returns true when reference value contained | +| | | in a collection | +| | -notcontains | Returns true when reference value not | +| | | contained in a collection | +| | -in | Returns true when test value contained in a | +| | | collection | +| | -notin | Returns true when test value not contained | +| | | in a collection | +| | | | +| Replacement | -replace | Replaces a string pattern | +| | | | +| Type | -is | Returns true if both object are the same | +| | | type | +| | -isnot | Returns true if the objects are not the same| +| | | type | + +By default, all comparison operators are case-insensitive. To make a +comparison operator case-sensitive, precede the operator name with a `c`. For +example, the case-sensitive version of `-eq` is `-ceq`. To make the +case-insensitivity explicit, precede the operator with an `i`. For example, +the explicitly case-insensitive version of `-eq` is `-ieq`. + +When the input to an operator is a scalar value, comparison operators return a +Boolean value. When the input is a collection of values, the comparison +operators return any matching values. If there are no matches in a collection, +comparison operators do not return anything. + +The exceptions are the containment operators (`-contains`, `-notcontains`), +the In operators (`-in`, `-notin`), and the type operators (`-is`, `-isnot`), +which always return a Boolean value. + +### Equality Operators + +The equality operators (`-eq`, `-ne`) return a value of TRUE or the matches +when one or more of the input values is identical to the specified pattern. +The entire pattern must match an entire value. + +Example: + +#### -eq + +Description: Equal to. Includes an identical value. + +Example: + +```powershell +C:PS> 2 -eq 2 +True + +C:PS> 2 -eq 3 +False + +C:PS> 1,2,3 -eq 2 +2 +PS> "abc" -eq "abc" +True + +PS> "abc" -eq "abc", "def" +False + +PS> "abc", "def" -eq "abc" +abc +``` + +#### -ne + +Description: Not equal to. Includes a different value. + +Example: + +```powershell +PS> "abc" -ne "def" +True + +PS> "abc" -ne "abc" +False + +PS> "abc" -ne "abc", "def" +True + +PS> "abc", "def" -ne "abc" +def +``` + +#### -gt + +Description: Greater-than. + +Example: + +```powershell +PS> 8 -gt 6 +True + +PS> 7, 8, 9 -gt 8 +9 +``` + +> [!NOTE] +> This should not to be confused with `>`, the greater-than operator in many other programming languages. In PowerShell, `>` is used for redirection. For more information, see [About_redirection](about_Redirection.md#potential-confusion-with-comparison-operators). + +#### -ge + +Description: Greater-than or equal to. + +Example: + +```powershell +PS> 8 -ge 8 +True + +PS> 7, 8, 9 -ge 8 +8 +9 +``` + +#### -lt + +Description: Less-than. + +Example: + +```powershell + +PS> 8 -lt 6 +False + +PS> 7, 8, 9 -lt 8 +7 +``` + +#### -le + +Description: Less-than or equal to. + +Example: + +```powershell +PS> 6 -le 8 +True + +PS> 7, 8, 9 -le 8 +7 +8 +``` + +### Matching Operators + +The like operators (`-like` and `-notlike`) find elements that match or do not +match a specified pattern using wildcard expressions. + +The syntax is: + +```powershell + -like + -notlike +``` + +The match operators (`-match` and `-notmatch`) find elements that match or do +not match a specified pattern using regular expressions. + +The match operators populate the `$Matches` automatic variable when the input +(the left-side argument) to the operator is a single scalar object. When the +input is scalar, the `-match` and `-notmatch` operators return a Boolean value +and set the value of the `$Matches` automatic variable to the matched +components of the argument. + +The syntax is: + +```powershell + -match + -notmatch +``` + +#### -like + +Description: Match using the wildcard character (\*). + +Example: + +```powershell +PS> "PowerShell" -like "*shell" +True + +PS> "PowerShell", "Server" -like "*shell" +PowerShell +``` + +#### -notlike + +Description: Does not match using the wildcard character (\*). + +Example: + +```powershell +PS> "PowerShell" -notlike "*shell" +False + +PS> "PowerShell", "Server" -notlike "*shell" +Server +``` + +### -match + +Description: Matches a string using regular expressions. When the input is +scalar, it populates the `$Matches` automatic variable. + +The match operators search only in strings. They cannot search in arrays of +integers or other objects. + +If the input is a collection, the `-match` and `-notmatch` operators return +the matching members of that collection, but the operator does not populate +the `$Matches` variable. + +For example, the following command submits a collection of strings to the +`-match` operator. The `-match` operator returns the items in the collection +that match. It does not populate the `$Matches` automatic variable. + +```powershell +PS> "Sunday", "Monday", "Tuesday" -match "sun" +Sunday + +PS> $Matches +PS> +``` + +In contrast, the following command submits a single string to the `-match` +operator. The `-match` operator returns a Boolean value and populates the +`$Matches` automatic variable. The `$Matches` automatic variable is a +**Hashtable**. If no grouping or capturing is used, only one key is populated. +The `0` key represents all text that was matched. For more information about +grouping and capturing using regular expressions, see +[about_Regular_Expressions](about_Regular_Expressions.md). + +```powershell +PS> "Sunday" -match "sun" +True + +PS> $Matches + +Name Value +---- ----- +0 Sun +``` + +It is important to note that the `$Matches` hashtable will only contain the +first occurrence of any matching pattern. + +```powershell +PS> "Banana" -match "na" +True + +PS> $Matches + +Name Value +---- ----- +0 na +``` + +> [!IMPORTANT] +> The `0` key is an **Integer**. You can use any **Hashtable** method to access +> the value stored. +> +> ```powershell +> PS> "Good Dog" -match "Dog" +> True +> +> PS> $Matches[0] +> Dog +> +> PS> $Matches.Item(0) +> Dog +> +> PS> $Matches.0 +> Dog +> ``` + +The `-notmatch` operator populates the `$Matches` automatic variable when the +input is scalar and the result is False, that it, when it detects a match. + +```powershell +PS> "Sunday" -notmatch "rain" +True + +PS> $matches +PS> + +PS> "Sunday" -notmatch "day" +False + +PS> $matches + +Name Value +---- ----- +0 day +``` + +#### -notmatch + +Description: Does not match a string. Uses regular expressions. When the input +is scalar, it populates the `$Matches` automatic variable. + +Example: + +```powershell +PS> "Sunday" -notmatch "sun" +False + +PS> $matches +Name Value +---- ----- +0 sun + +PS> "Sunday", "Monday" -notmatch "sun" +Monday +``` + +### Containment Operators + +The containment operators (`-contains` and `-notcontains`) are similar to the +equality operators. However, the containment operators always return a Boolean +value, even when the input is a collection. + +Also, unlike the equality operators, the containment operators return a value +as soon as they detect the first match. The equality operators evaluate all +input and then return all the matches in the collection. + +#### -contains + +Description: Containment operator. Tells whether a collection of reference +values includes a single test value. Always returns a Boolean value. Returns +TRUE only when the test value exactly matches at least one of the reference +values. + +When the test value is a collection, the Contains operator uses reference +equality. It returns TRUE only when one of the reference values is the same +instance of the test value object. + +In a very large collection, the `-contains` operator returns results quicker +than the equal to operator. + +Syntax: + +` -contains ` + +Examples: + +```powershell +PS> "abc", "def" -contains "def" +True + +PS> "Windows", "PowerShell" -contains "Shell" +False #Not an exact match + +# Does the list of computers in $DomainServers include $ThisComputer? +PS> $DomainServers -contains $thisComputer +True + +PS> "abc", "def", "ghi" -contains "abc", "def" +False + +PS> $a = "abc", "def" +PS> "abc", "def", "ghi" -contains $a +False +PS> $a, "ghi" -contains $a +True +``` + +#### -notcontains + +Description: Containment operator. Tells whether a collection of reference +values includes a single test value. Always returns a Boolean value. Returns +TRUE when the test value is not an exact matches for at least one of the +reference values. + +When the test value is a collection, the NotContains operator uses reference +equality. + +Syntax: + +` -notcontains ` + +Examples: + +```powershell +PS> "Windows", "PowerShell" -notcontains "Shell" +True #Not an exact match + +# Get cmdlet parameters, but exclude common parameters +function get-parms ($cmdlet) +{ + $Common = "Verbose", "Debug", "WarningAction", "WarningVariable", + "ErrorAction", "ErrorVariable", "OutVariable", "OutBuffer" + + $allparms = (Get-Command $Cmdlet).parametersets | + foreach {$_.Parameters} | + foreach {$_.Name} | Sort-Object | Get-Unique + + $allparms | where {$Common -notcontains $_ } +} + +# Find unapproved verbs in the functions in my module +PS> $ApprovedVerbs = Get-Verb | foreach {$_.verb} +PS> $myVerbs = Get-Command -Module MyModule | foreach {$_.verb} +PS> $myVerbs | where {$ApprovedVerbs -notcontains $_} +ForEach +Sort +Tee +Where +``` + +#### -in + +Description: In operator. Tells whether a test value appears in a collection +of reference values. Always return as Boolean value. Returns TRUE only when +the test value exactly matches at least one of the reference values. + +When the test value is a collection, the In operator uses reference equality. +It returns TRUE only when one of the reference values is the same instance of +the test value object. + +The `-in` operator was introduced in PowerShell 3.0. + +Syntax: + +` -in ` + +Examples: + +```powershell +PS> "def" -in "abc", "def" +True + +PS> "Shell" -in "Windows", "PowerShell" +False #Not an exact match + +PS> "Windows" -in "Windows", "PowerShell" +True #An exact match + +PS> "Windows", "PowerShell" -in "Windows", "PowerShell", "ServerManager" +False #Using reference equality + +PS> $a = "Windows", "PowerShell" +PS> $a -in $a, "ServerManager" +True #Using reference equality + +# Does the list of computers in $DomainServers include $ThisComputer? +PS> $thisComputer -in $domainServers +True +``` + +#### -notin + +Description: Tells whether a test value appears in a collection of reference +values. Always returns a Boolean value. Returns TRUE when the test value is +not an exact match for at least one of the reference values. + +When the test value is a collection, the In operator uses reference equality. +It returns TRUE only when one of the reference values is the same instance of +the test value object. + +The `-notin` operator was introduced in PowerShell 3.0. + +Syntax: + +` -notin \` + +Examples: + +```powershell +PS> "def" -notin "abc", "def" +False + +PS> "ghi" -notin "abc", "def" +True + +PS> "Shell" -notin "Windows", "PowerShell" +True #Not an exact match + +PS> "Windows" -notin "Windows", "PowerShell" +False #An exact match + +# Find unapproved verbs in the functions in my module +PS> $ApprovedVerbs = Get-Verb | foreach {$_.verb} +PS> $MyVerbs = Get-Command -Module MyModule | foreach {$_.verb} + +PS> $MyVerbs | where {$_ -notin $ApprovedVerbs} +ForEach +Sort +Tee +Where +``` + +### Replacement Operator + +The `-replace` operator replaces all or part of a value with the specified +value using regular expressions. You can use the `-replace` operator for many +administrative tasks, such as renaming files. For example, the following +command changes the file name extensions of all .txt files to .log: + +```powershell +Get-ChildItem *.txt | Rename-Item -NewName { $_.name -replace '\.txt$','.log' } +``` + +The syntax of the `-replace` operator is as follows, where the \ +placeholder represents the characters to be replaced, and the \ +placeholder represents the characters that will replace them: + +` , ` + +By default, the `-replace` operator is case-insensitive. To make it case +sensitive, use `-creplace`. To make it explicitly case-insensitive, use +`-ireplace`. + +Consider the following examples: + +```powershell +PS> "book" -replace "B", "C" +``` + +```output +Cook +``` + +```powershell +"book" -ireplace "B", "C" +``` + +```output +Cook +``` + +```powershell +"book" -creplace "B", "C" +``` + +```output +book +``` + +It is also possible to use regular expressions to dynamically replace text using +capturing groups, and substitutions. +For more information, see [about_Regular_Expressions](about_Regular_Expressions.md). + +### ScriptBlock substitutions + +Beginning in PowerShell 6, you can use a **ScriptBlock** argument for the +*Substitution* text. The **ScriptBlock** will execute for each match found in +the *input* string. + +Within the **ScriptBlock**, use the `$_` automatic variable to refer to the +current **System.Text.RegularExpressions.Match** object. The **Match** object +gives you access to the current input text being replaced, as well as other +useful information. + +This example replaces each sequence of three decimals with the character +equivalent. The **ScriptBlock** is run for each set of three decimals that +needs to be replaced. + +```powershell +PS> "072101108108111" -replace "\d{3}", {[char][int]$_.Value} +Hello +``` + +### Type comparison + +The type comparison operators (`-is` and `-isnot`) are used to determine if an +object is a specific type. + +#### -is + +Syntax: + +` -is ` + +Example: + +```powershell +PS> $a = 1 +PS> $b = "1" +PS> $a -is [int] +True +PS> $a -is $b.GetType() +False +``` + +#### -isnot + +Syntax: + +` -isnot ` + +Example: + +```powershell +PS> $a = 1 +PS> $b = "1" +PS> $a -isnot $b.GetType() +True +PS> $b -isnot [int] +True +``` + +## SEE ALSO + +- [about_Operators](about_Operators.md) +- [about_Regular_Expressions](about_Regular_Expressions.md) +- [about_Wildcards](about_Wildcards.md) +- [Compare-Object](../../Microsoft.PowerShell.Utility/Compare-Object.md) +- [Foreach-Object](../ForEach-Object.md) +- [Where-Object](../Where-Object.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Continue.md b/reference/7/Microsoft.PowerShell.Core/About/about_Continue.md new file mode 100644 index 000000000000..11bc0ce9a764 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Continue.md @@ -0,0 +1,50 @@ +--- +ms.date: 06/25/2017 +schema: 2.0.0 +keywords: powershell,cmdlet +title: about_Continue +--- +# About Continue + +## SHORT DESCRIPTION +Describes how the `Continue` statement immediately returns the program flow +to the top of a program loop. + +## LONG DESCRIPTION + +In a script, the `Continue` statement immediately returns the program flow +to the top of the innermost loop that is controlled by a `For`, `Foreach`, +or `While` statement. + +The `Continue` keyword supports labels. A label is a name you assign to a +statement in a script. For information about labels, see +[about_Break](about_Break.md). + +In the following example, program flow returns to the top of the While loop +if the $ctr variable is equal to 5. As a result, all the numbers between 1 +and 10 are displayed except for 5: + +```powershell +while ($ctr -lt 10) +{ + $ctr += 1 + if ($ctr -eq 5) {Continue} + Write-Host -Object $ctr +} +``` + +Note that in a `For` loop, execution continues at the first line in the +loop. If the arguments of the `For` statement test a value that is modified +by the `For` statement, an infinite loop may result. + +## SEE ALSO + +[about_Break](about_Break.md) + +[about_Comparison_Operators](about_Comparison_Operators.md) + +[about_Throw](about_Throw.md) + +[about_Trap](about_Trap.md) + +[about_Try_Catch_Finally](about_Try_Catch_Finally.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Core_Commands.md b/reference/7/Microsoft.PowerShell.Core/About/about_Core_Commands.md new file mode 100644 index 000000000000..56d250959a80 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Core_Commands.md @@ -0,0 +1,91 @@ +--- +ms.date: 06/09/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Core_Commands +--- +# About Core Commands + +## SHORT DESCRIPTION +Lists the cmdlets that are designed for use with PowerShell providers. + +## LONG DESCRIPTION + +PowerShell includes a set of cmdlets that are specifically designed to manage +the items in the data stores that are exposed by PowerShell providers. +You can use these cmdlets in the same ways to manage all the different types +of data that the providers make available to you. For more information about +providers, type "get-help about_providers". + +For example, you can use the Get-ChildItem cmdlet to list the files in a file +system directory, the keys under a registry key, or the items that are exposed +by a provider that you write or download. + +The following is a list of the PowerShell cmdlets that are designed for use +with providers: + +ChildItem cmdlets + +- Get-ChildItem + +Content cmdlets + +- Add-Content +- Clear-Content +- Get-Content +- Set-Content + +Item cmdlets + +- Clear-Item +- Copy-Item +- Get-Item +- Invoke-Item +- Move-Item +- New-Item +- Remove-Item +- Rename-Item +- Set-Item + +ItemProperty cmdlets + +- Clear-ItemProperty +- Copy-ItemProperty +- Get-ItemProperty +- Move-ItemProperty +- New-ItemProperty +- Remove-ItemProperty +- Rename-ItemProperty +- Set-ItemProperty + +Location cmdlets + +- Get-Location +- Pop-Location +- Push-Location +- Set-Location + +Path cmdlets + +- Join-Path +- Convert-Path +- Split-Path +- Resolve-Path +- Test-Path + +PSDrive cmdlets + +- Get-PSDrive +- New-PSDrive +- Remove-PSDrive + +PSProvider cmdlets + +- Get-PSProvider + +For more information about a cmdlet, type `get-help `. + +## SEE ALSO + +[about_Providers](about_Providers.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Data_Sections.md b/reference/7/Microsoft.PowerShell.Core/About/about_Data_Sections.md new file mode 100644 index 000000000000..e8e11ac3ae00 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Data_Sections.md @@ -0,0 +1,222 @@ +--- +ms.date: 06/09/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Data_Sections +--- +# About Data Sections + +## Short Description +Explains Data sections, which isolate text strings and other read-only +data from script logic. + +## Long Description + +Scripts that are designed for PowerShell can have one or more +Data sections that contain only data. You can include one or more Data +sections in any script, function, or advanced function. The content of +the Data section is restricted to a specified subset of the Windows +PowerShell scripting language. + +Separating data from code logic makes it easier to identify and manage +both logic and data. It lets you have separate string resource files for +text, such as error messages and Help strings. It also isolates the code +logic, which facilitates security and validation tests. + +In PowerShell, the Data section is used to support script +internationalization. You can use Data sections to make it easier to +isolate, locate, and process strings that will be translated into many +user interface (UI) languages. + +The Data section is a Windows PowerShell 2.0 feature. Scripts with Data +sections will not run in Windows PowerShell 1.0 without revision. + +### Syntax + +The syntax for a Data section is as follows: +```powershell +DATA [-supportedCommand ] { + +} +``` + +The Data keyword is required. It is not case-sensitive. + +The permitted content is limited to the following elements: + +- All PowerShell operators, except `-match` + +- `If`, `Else`, and `ElseIf` statements + +- The following automatic variables: `$PsCulture`, `$PsUICulture`, `$True`, +`$False`, and `$Null` + +- Comments + +- Pipelines + +- Statements separated by semicolons (`;`) + +- Literals, such as the following: + +```powershell +a +``` + +```powershell +1 +``` + +```powershell +1,2,3 +``` + +```powershell +"Windows PowerShell 2.0" +``` + +```powershell +@( "red", "green", "blue" ) +``` +```powershell +@{ a = 0x1; b = "great"; c ="script" } +``` + +```powershell +[XML] @' +

Hello, World

+'@ +``` + +- Cmdlets that are permitted in a Data section. By default, only the +`ConvertFrom-StringData` cmdlet is permitted. + +- Cmdlets that you permit in a Data section by using the +`-SupportedCommand` parameter. + +When you use the `ConvertFrom-StringData` cmdlet in a Data section, you can +enclose the key/value pairs in single-quoted or double-quoted strings or in +single-quoted or double-quoted here-strings. However, strings that contain +variables and subexpressions must be enclosed in single-quoted strings or +in single-quoted here-strings so that the variables are not expanded and the +subexpressions are not executable. + +### -SupportedCommand + +The `-SupportedCommand` parameter allows you to indicate that a cmdlet or +function generates only data. It is designed to allow users to include +cmdlets and functions in a data section that they have written or tested. + +The value of `-SupportedCommand` is a comma-separated list of one or more +cmdlet or function names. + +For example, the following data section includes a user-written cmdlet, +`Format-XML`, that formats data in an XML file: + +```powershell +DATA -supportedCommand Format-Xml +{ + Format-Xml -Strings string1, string2, string3 +} +``` + +### Using a Data Section + +To use the content of a Data section, assign it to a variable and use +variable notation to access the content. + +For example, the following data section contains a `ConvertFrom-StringData` +command that converts the here-string into a hash table. The hash table +is assigned to the `$TextMsgs` variable. + +The `$TextMsgs` variable is not part of the data section. + +```powershell +$TextMsgs = DATA { + ConvertFrom-StringData -StringData @' +Text001 = Windows 7 +Text002 = Windows Server 2008 R2 +'@ +} +``` + +To access the keys and values in hash table in $TextMsgs, use the +following commands. + +```powershell +$TextMsgs.Text001 +$TextMsgs.Text002 +``` + +### Examples + +Simple data strings. + +```powershell +DATA { + "Thank you for using my PowerShell Organize.pst script." + "It is provided free of charge to the community." + "I appreciate your comments and feedback." +} +``` + +Strings that include permitted variables. + +```powershell +DATA { + if ($null) { + "To get help for this cmdlet, type get-help new-dictionary." + } +} +``` + +A single-quoted here-string that uses the ConvertFrom-StringData cmdlet: + +```powershell +DATA { + ConvertFrom-StringData -stringdata @' +Text001 = Windows 7 +Text002 = Windows Server 2008 R2 +'@ +} +``` + +A double-quoted here-string that uses the ConvertFrom-StringData cmdlet: + +```powershell +DATA { + ConvertFrom-StringData -stringdata @" +Msg1 = To start, press any key. +Msg2 = To exit, type "quit". +"@ +} +``` + +A data section that includes a user-written cmdlet that generates data: + +```powershell +DATA -supportedCommand Format-XML { + Format-Xml -strings string1, string2, string3 +} +``` + +## See Also + +[about_Automatic_Variables](about_Automatic_Variables.md) + +[about_Comparison_Operators](about_Comparison_Operators.md) + +[about_Hash_Tables](about_Hash_Tables.md) + +[about_If](about_If.md) + +[about_Operators](about_Operators.md) + +[about_Quoting_Rules](about_Quoting_Rules.md) + +[about_Script_Internationalization](about_Script_Internationalization.md) + +[ConvertFrom-StringData](../../Microsoft.PowerShell.Utility/ConvertFrom-StringData.md) + +[Import-LocalizedData](../../Microsoft.PowerShell.Utility/Import-LocalizedData.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Debuggers.md b/reference/7/Microsoft.PowerShell.Core/About/about_Debuggers.md new file mode 100644 index 000000000000..dbe2a3a490b0 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Debuggers.md @@ -0,0 +1,863 @@ +--- +ms.date: 11/27/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Debuggers +--- +# About Debuggers + +## SHORT DESCRIPTION +Describes the PowerShell debugger. + +## LONG DESCRIPTION + +Debugging is the process of examining a script while it is running to identify +and correct errors in the script instructions. The PowerShell debugger +can help you examine and identify errors and inefficiencies in your scripts, +functions, commands, PowerShell workflows, PowerShell Desired +State Configuration (DSC) configurations, or expressions. + +Starting in Windows PowerShell 5.0, the PowerShell debugger has been +updated to debug scripts, functions, workflows, commands, configurations, or +expressions that are running in either the console or Windows PowerShell ISE +on remote computers. You can run Enter-PSSession to start an interactive +remote PowerShell session in which you can set breakpoints and debug script +files and commands on the remote computer. Enter-PSSession functionality has +been updated to let you reconnect to and enter a disconnected session that is +running a script or command on a remote computer. If the running script hits a +breakpoint, your client session automatically starts the debugger. If the +disconnected session that is running a script has already hit a breakpoint, +and is stopped at the breakpoint, Enter-PSSession automatically starts the +command-line debugger, after you reconnect to the session. + +The PowerShell debugger can also be used to debug PowerShell +workflows, in either the PowerShell console, or in Windows PowerShell +ISE. Starting in Windows PowerShell 5.0, you can debug within running jobs or +processes, either locally or remotely. + +You can use the features of the PowerShell debugger to examine a +PowerShell script, function, command, workflow, or expression while it +is running. The PowerShell debugger includes a set of cmdlets that let +you set breakpoints, manage breakpoints, and view the call stack. + +## Debugger Cmdlets + +The PowerShell debugger includes the following set of cmdlets: + +- `Set-PsBreakpoint`: Sets breakpoints on lines, variables, and commands. +- `Get-PsBreakpoint`: Gets breakpoints in the current session. +- `Disable-PsBreakpoint`: Turns off breakpoints in the current session. +- `Enable-PsBreakpoint`: Re-enables breakpoints in the current session. +- `Remove-PsBreakpoint`: Deletes breakpoints from the current session. +- `Get-PsCallStack`: Displays the current call stack. + +## Starting and Stopping the Debugger + +To start the debugger, set one or more breakpoints. Then, run the script, +command, or function that you want to debug. + +When you reach a breakpoint, execution stops, and control is turned over +to the debugger. + +To stop the debugger, run the script, command, or function until it is +complete. Or, type `stop` or `t`. + +### Debugger Commands + +When you use the debugger in the PowerShell console, use the following +commands to control the execution. In Windows PowerShell ISE, use commands on +the Debug menu. + +Note: For information about how to use the debugger in other host +applications, see the host application documentation. + +- `s`, `StepInto`: Executes the next statement and then stops. + +- `v`, `StepOver`: Executes the next statement, but skips functions and + invocations. The skipped statements are executed, but not stepped through. + +- `Ctrl+Break`: (Break All in ISE) Breaks into a running script within either + the PowerShell console, or Windows PowerShell ISE. Note that + Ctrl+Break in Windows PowerShell 2.0, 3.0, and 4.0 closes the program. Break + All works on both local and remote interactively-running scripts. + +- `o`, `StepOut`: Steps out of the current function; up one level if nested. + If in the main body, it continues to the end or the next breakpoint. The + skipped statements are executed, but not stepped through. + +- `c`, `Continue`: Continues to run until the script is complete or until the + next breakpoint is reached. The skipped statements are executed, but not + stepped through. + +- `l`, `List`: Displays the part of the script that is executing. By default, + it displays the current line, five previous lines, and 10 subsequent lines. + To continue listing the script, press ENTER. + +- `l `, `List`: Displays 16 lines of the script beginning with the line + number specified by ``. + +- `l `, `List`: Displays `` lines of the script, beginning with the + line number specified by ``. + +- `q`, `Stop`, `Exit`: Stops executing the script, and exits the debugger. If + you are debugging a job by running the Debug-Job cmdlet, the Exit command + detaches the debugger, and allows the job to continue running. + +- `k`, `Get-PsCallStack`: Displays the current call stack. + +- ``: Repeats the last command if it was Step (s), StepOver (v), or + List (l). Otherwise, represents a submit action. + +- `?`, `h`: Displays the debugger command Help. + +To exit the debugger, you can use Stop (q). + +Starting in Windows PowerShell 5.0, you can run the Exit command to exit a +nested debugging session that you started by running either Debug-Job or +Debug-Runspace. + +By using these debugger commands, you can run a script, stop on a point of +concern, examine the values of variables and the state of the system, and +continue running the script until you have identified a problem. + +NOTE: If you step into a statement with a redirection operator, such as ">", +the PowerShell debugger steps over all remaining statements in the +script. + +Displaying the Values of script Variables + +While you are in the debugger, you can also enter commands, display the value +of variables, use cmdlets, and run scripts at the command line. + +You can display the current value of all variables in the script that is being +debugged, except for the following automatic variables: + +```powershell +$_ +$Args +$Input +$MyInvocation +$PSBoundParameters +``` + +If you try to display the value of any of these variables, you get the +value of that variable for in an internal pipeline the debugger uses, not +the value of the variable in the script. + +To display the value these variables for the script that is being debugged, +in the script, assign the value of the automatic variable to a new variable. +Then you can display the value of the new variable. + +For example, + +```powershell +$scriptArgs = $Args +$scriptArgs +``` + +In the example in this topic, the value of the $MyInvocation variable is +reassigned as follows: + +```powershell +$scriptname = $MyInvocation.MyCommand.Path +``` + +## The Debugger Environment + +When you reach a breakpoint, you enter the debugger environment. The +command prompt changes so that it begins with "[DBG]:". If you are +debugging a workflow, the prompt is "[WFDBG]". You can customize +the prompt. + +Also, in some host applications, such as the PowerShell console, +(but not in Windows PowerShell Integrated Scripting Environment [ISE]), +a nested prompt opens for debugging. You can detect the nested prompt by +the repeating greater-than characters (ASCII 62) that appear at the +command prompt. + +For example, the following is the default debugging prompt in the +PowerShell console: + +``` +[DBG]: PS (get-location)>>> +``` + +You can find the nesting level by using the \$NestedPromptLevel +automatic variable. + +Additionally, an automatic variable, \$PSDebugContext, is defined in +the local scope. You can use the presence of the \$PsDebugContext +variable to determine whether you are in the debugger. + +For example: + +```powershell +if ($psdebugcontext) {"Debugging"} else {"Not Debugging"} +``` + +You can use the value of the \$PSDebugContext variable in your +debugging. + +``` +[DBG]: PS>>> $psdebugcontext.invocationinfo + +Name CommandLineParameters UnboundArguments Location +---- --------------------- ---------------- -------- += {} {} C:\ps-test\vote.ps1 (1) +``` + +## Debugging and Scope + +Breaking into the debugger does not change the scope in which you are +operating, but when you reach a breakpoint in a script, you move into the +script scope. The script scope is a child of the scope in which you ran the +debugger. + +To find the variables and aliases that are defined in the script scope, use +the Scope parameter of the Get-Alias or Get-Variable cmdlets. + +For example, the following command gets the variables in the local (script) +scope: + +```powershell +get-variable -scope 0 +``` + +You can abbreviate the command as: + +```powershell +gv -s 0 +``` + +This is a useful way to see only the variables that you defined in the script +and that you defined while debugging. + +Debugging at the Command Line + +When you set a variable breakpoint or a command breakpoint, you can set the +breakpoint only in a script file. However, by default, the breakpoint is set +on anything that runs in the current session. + +For example, if you set a breakpoint on the \$name variable, the debugger +breaks on any \$name variable in any script, command, function, script cmdlet +or expression that you run until you disable or remove the breakpoint. + +This allows you to debug your scripts in a more realistic context in which +they might be affected by functions, variables, and other scripts in the +session and in the user's profile. + +Line breakpoints are specific to script files, so they are set only in script +files. + +## Debugging Workflows + +The Windows PowerShell 4.0 debugger can be used to debug Windows PowerShell +workflows, either in the Windows PowerShell console, or in Windows PowerShell +ISE. There are some limitations with using the Windows PowerShell debugger to +debug workflows. + +- You can view workflow variables while you are in the debugger, but setting + workflow variables from within the debugger is not supported. +- Tab completion when stopped in the workflow debugger is not available. +- Workflow debugging works only with synchronous running of workflows from a + Windows PowerShell script. You cannot debug workflows if they are running as a + job (with the **-AsJob** parameter). +- Other nested debugging scenarios--such as a workflow calling another + workflow, or a workflow calling a script--are not implemented. + +The following example demonstrates debugging a workflow. Note that when the +debugger steps into the workflow function, the debugger prompt changes to +[WFDBG]. + +```powershell +PS C:> Set-PSBreakpoint -Script C:\TestWFDemo1.ps1 -Line 8 + +ID Script Line Command Variable Action +-- ------ ---- ------- -------- ------ +0 TestWFDemo1.ps1 8 + +PS C:> C:\TestWFDemo1.ps1 +Entering debug mode. Use h or ? for help. + +Hit Line breakpoint on 'C:\TestWFDemo1.ps1:8' + +At C:\TestWFDemo1.ps1:8 char:5 ++ Write-Output -InputObject "Now writing output:" +# +!INCLUDE[]~~~~~ + +[WFDBG:localhost]: PS C:>> list + +# 3: + +4: workflow SampleWorkflowTest +5: { +6: param ($MyOutput) +# 7: + +8:* Write-Output -InputObject "Now writing output:" +9: Write-Output -Input $MyOutput +# 10: + +11: Write-Output -InputObject "Get PowerShell process:" +12: Get-Process -Name powershell +# 13: + +14: Write-Output -InputObject "Workflow function complete." +15: } +# 16: + +17: # Call workflow function +18: SampleWorkflowTest -MyOutput "Hello" + +[WFDBG:localhost]: PS C:>> $MyOutput +Hello +[WFDBG:localhost]: PS C:>> stepOver +Now writing output: +At C:\TestWFDemo1.ps1:9 char:5 ++ Write-Output -Input $MyOutput +# +!INCLUDE[]~ + +[WFDBG:localhost]: PS C:>> list + +4: workflow SampleWorkflowTest +5: { +6: param ($MyOutput) +# 7: + +8: Write-Output -InputObject "Now writing output:" +9:* Write-Output -Input $MyOutput +# 10: + +11: Write-Output -InputObject "Get PowerShell process:" +12: Get-Process -Name powershell +# 13: + +14: Write-Output -InputObject "Workflow function complete." +15: } +# 16: + +17: # Call workflow function +18: SampleWorkflowTest -MyOutput "Hello" +# 19: + + +[WFDBG:localhost]: PS C:>> stepOver +Hello +At C:\TestWFDemo1.ps1:11 char:5 ++ Write-Output -InputObject "Get PowerShell process:" +# +!INCLUDE[]~~~~~~~~~ + +[WFDBG:localhost]: PS C:>> stepOut +Get PowerShell process: + +Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName +------- ------ ----- ----- ----- ------ -- ----------- + 433 35 106688 128392 726 2.67 7124 powershell + 499 44 134244 172096 787 2.79 7452 powershell + +Workflow function complete. +``` + +## Debugging Functions + +When you set a breakpoint on a function that has Begin, Process, and +End sections, the debugger breaks at the first line of each section. + +For example: + +```powershell +function test-cmdlet { + begin { + write-output "Begin" + } + process { + write-output "Process" + } + end { + write-output "End" + } +} + +C:\PS> set-psbreakpoint -command test-cmdlet + +C:\PS> test-cmdlet + +Begin +Entering debug mode. Use h or ? for help. + +Hit Command breakpoint on 'prompt:test-cmdlet' + +test-cmdlet + +[DBG]: C:\PS> c +Process +Entering debug mode. Use h or ? for help. + +Hit Command breakpoint on 'prompt:test-cmdlet' + +test-cmdlet + +[DBG]: C:\PS> c +End +Entering debug mode. Use h or ? for help. + +Hit Command breakpoint on 'prompt:test-cmdlet' + +test-cmdlet + +# [DBG]: C:\PS> +``` + +## Debugging Remote Scripts + +Starting in Windows PowerShell 5.0, you can run the PowerShell +debugger in a remote session, in either the console, or Windows PowerShell +ISE. Enter-PSSession functionality has been updated to let you reconnect to +and enter a disconnected session that is running on a remote computer, and +currently running a script. If the running script hits a breakpoint, your +client session automatically starts the debugger. + +The following is an example that shows how this works, with breakpoints set in +a script at lines 6, 11, 22, and 25. Note that in the example, when the +debugger starts, there are two identifying prompts: the name of the computer +on which the session is running, and the DBG prompt that lets you know you are +in debugging mode. + +```powershell +Enter-Pssession -Cn localhost +[localhost]: PS C:\psscripts> Set-PSBreakpoint .\ttest19.ps1 6,11,22,25 + +ID Script Line Command Variable Action +-- ------ ---- ------- -------- ------ +0 ttest19.ps1 6 +1 ttest19.ps1 11 +2 ttest19.ps1 22 +3 ttest19.ps1 25 + +[localhost]: PS C:\psscripts> .\ttest19.ps1 +Hit Line breakpoint on 'C:\psscripts\ttest19.ps1:11' + +At C:\psscripts\ttest19.ps1:11 char:1 ++ $winRMName = "WinRM" +# + ~ + +[localhost]: [DBG]: PS C:\psscripts>> list + +6: 1..5 | foreach { sleep 1; Write-Output "hello2day $_" } +7: } +# 8: + +9: $count = 10 +10: $psName = "PowerShell" +11:* $winRMName = "WinRM" +12: $myVar = 102 +# 13: + +14: for ($i=0; $i -lt $count; $i++) +15: { +16: sleep 1 +17: Write-Output "Loop iteration is: $i" +18: Write-Output "MyVar is $myVar" +# 19: + +20: hello2day +# 21: + + +[localhost]: [DBG]: PS C:\psscripts>> stepover +At C:\psscripts\ttest19.ps1:12 char:1 ++ $myVar = 102 +# + ~ + +[localhost]: [DBG]: PS C:\psscripts>> quit +[localhost]: PS C:\psscripts> Exit-PSSession +PS C:\psscripts> +``` + +## Examples + +This test script detects the version of the operating system and +displays a system-appropriate message. It includes a function, a function +call, and a variable. + +The following command displays the contents of the test script file: + +```powershell +c:>\PS-test> get-content test.ps1 + +function psversion { + "PowerShell " + $psversiontable.psversion + if ($psversiontable.psversion.major -lt 6) { + "Upgrade to PowerShell 6.0!" + } + else { + "Have you run a background job today (start-job)?" + } +} + +$scriptname = $MyInvocation.MyCommand.Path +psversion +"Done $scriptname." +``` + +To start, set a breakpoint at a point of interest in the script, such as a +line, command, variable, or function. + +Start by creating a line breakpoint on the first line of the Test.ps1 script +in the current directory. + +```powershell +PS C:\ps-test> set-psbreakpoint -line 1 -script test.ps1 +``` + +You can abbreviate this command as: + +```powershell +PS C:\ps-test> spb 1 -s test.ps1 +``` + +The command returns a line-breakpoint object +(System.Management.Automation.LineBreakpoint). + +``` +Column : 0 +Line : 1 +Action : +Enabled : True +HitCount : 0 +Id : 0 +Script : C:\ps-test\test.ps1 +ScriptName : C:\ps-test\test.ps1 +``` + +Now, start the script. + +```powershell +PS C:\ps-test> .\test.ps1 +``` + +When the script reaches the first breakpoint, the breakpoint message indicates +that the debugger is active. It describes the breakpoint and previews the +first line of the script, which is a function declaration. The command prompt +also changes to indicate that the debugger has control. + +The preview line includes the script name and the line number of the previewed +command. + +```powershell +Entering debug mode. Use h or ? for help. + +Hit Line breakpoint on 'C:\ps-test\test.ps1:1' + +test.ps1:1 function psversion { +# DBG> +``` + +Use the Step command (s) to execute the first statement in the script and to +preview the next statement. The next statement uses the $MyInvocation +automatic variable to set the value of the $ScriptName variable to the path +and file name of the script file. + +```powershell +DBG> s +test.ps1:11 $scriptname = $MyInvocation.MyCommand.Path +``` + +At this point, the \$ScriptName variable is not populated, but you can +verify the value of the variable by displaying its value. In this case, +the value is \$null. + +```powershell +DBG> $scriptname +# DBG> +``` + +Use another Step command (s) to execute the current statement and to +preview the next statement in the script. The next statement calls the +PsVersion function. + +```powershell +DBG> s +test.ps1:12 psversion +``` + +At this point, the $ScriptName variable is populated, but you verify the +value of the variable by displaying its value. In this case, the value +is set to the script path. + +```powershell +DBG> $scriptname +C:\ps-test\test.ps1 +``` + +Use another Step command to execute the function call. Press ENTER, +or type "s" for Step. + +```powershell +DBG> s +test.ps1:2 "PowerShell " + $psversiontable.psversion +``` + +The debug message includes a preview of the statement in the function. To +execute this statement and to preview the next statement in the function, you +can use a Step command. But, in this case, use a StepOut command (o). It +completes the execution of the function (unless it reaches a breakpoint) and +steps to the next statement in the script. + +```powershell +DBG> o +Windows PowerShell 2.0 +Have you run a background job today (start-job)? +test.ps1:13 "Done $scriptname" +``` + +Because we are on the last statement in the script, the Step, StepOut, and +Continue commands have the same effect. In this case, use StepOut (o). + +```powershell +Done C:\ps-test\test.ps1 +PS C:\ps-test> +``` + +The StepOut command executes the last command. The standard command prompt +indicates that the debugger has exited and returned control to the command +processor. + +Now, run the debugger again. First, to delete the current breakpoint, use the +Get-PsBreakpoint and Remove-PsBreakpoint cmdlets. (If you think you might +reuse the breakpoint, use the Disable-PsBreakpoint cmdlet instead of +Remove-PsBreakpoint.) + +```powershell +PS C:\ps-test> Get-PsBreakpoint | Remove-PSBreakpoint +``` + +You can abbreviate this command as: + +```powershell +PS C:\ps-test> gbp | rbp +``` + +Or, run the command by writing a function, such as the following +function: + +```powershell +function delbr { gbp | rbp } +``` + +Now, create a breakpoint on the \$scriptname variable. + +```powershell +PS C:\ps-test> set-psbreakpoint -variable scriptname -script test.ps1 +``` + +You can abbreviate the command as: + +```powershell +PS C:\ps-test> sbp -v scriptname -s test.ps1 +``` + +Now, start the script. The script reaches the variable breakpoint. The +default mode is Write, so execution stops just before the statement +that changes the value of the variable. + +```powershell +PS C:\ps-test> .\test.ps1 +Hit Variable breakpoint on 'C:\ps-test\test.ps1:$scriptname' +(Write access) + +test.ps1:11 $scriptname = $MyInvocation.mycommand.path +# DBG> +``` + +Display the current value of the \$scriptname variable, which is \$null. + +```powershell +DBG> $scriptname +# DBG> +``` + +Use a Step command (s) to execute the statement that populates the variable. +Then, display the new value of the \$scriptname variable. + +```powershell +DBG> $scriptname +C:\ps-test\test.ps1 +```powershell + +Use a Step command (s) to preview the next statement in the script. + +```powershell +DBG> s +test.ps1:12 psversion +``` + +The next statement is a call to the PsVersion function. To skip the function +but still execute it, use a StepOver command (v). If you are already in the +function when you use StepOver, it is not effective. The function call is +displayed, but it is not executed. + +```powershell +DBG> v +Windows PowerShell 2.0 +Have you run a background job today (start-job)? +test.ps1:13 "Done $scriptname" +``` + +The StepOver command executes the function, and it previews the next +statement in the script, which prints the final line. + +Use a Stop command (t) to exit the debugger. The command prompt +reverts to the standard command prompt. + +```powershell +C:\ps-test> +``` + +To delete the breakpoints, use the Get-PsBreakpoint and +Remove-PsBreakpoint cmdlets. + +```powershell +PS C:\ps-test> Get-PsBreakpoint | Remove-PSBreakpoint +``` + +Create a new command breakpoint on the PsVersion function. + +```powershell +PS C:\ps-test> Set-PsBreakpoint -command psversion -script test.ps1 +``` + +You can abbreviate this command to: + +```powershell +PS C:\ps-test> sbp -c psversion -s test.ps1 +``` + +Now, run the script. + +```powershell +PS C:\ps-test> .\test.ps1 +Hit Command breakpoint on 'C:\ps-test\test.ps1:psversion' + +test.ps1:12 psversion +# DBG> +``` + +The script reaches the breakpoint at the function call. At this point, the +function has not yet been called. This gives you the opportunity to use the +Action parameter of Set-PsBreakpoint to set conditions for the execution of +the breakpoint or to perform preparatory or diagnostic tasks, such as starting +a log or invoking a diagnostic or security script. + +To set an action, use a Continue command (c) to exit the script, and a +Remove-PsBreakpoint command to delete the current breakpoint. (Breakpoints are +read-only, so you cannot add an action to the current breakpoint.) + +```powershell +DBG> c +Windows PowerShell 2.0 +Have you run a background job today (start-job)? +Done C:\ps-test\test.ps1 + +PS C:\ps-test> get-psbreakpoint | remove-psbreakpoint +PS C:\ps-test> +``` + +Now, create a new command breakpoint with an action. The following command +sets a command breakpoint with an action that logs the value of the +\$scriptname variable when the function is called. Because the Break keyword is +not used in the action, execution does not stop. (The backtick (`) is the +line-continuation character.) + +```powershell +PS C:\ps-test> set-psbreakpoint -command psversion -script test.ps1 ` +-action { add-content "The value of `$scriptname is $scriptname." ` +-path action.log} +``` + +You can also add actions that set conditions for the breakpoint. In the +following command, the command breakpoint is executed only if the execution +policy is set to RemoteSigned, the most restrictive policy that still permits +you to run scripts. (The backtick (`) is the continuation character.) + +```powershell +PS C:\ps-test> set-psbreakpoint -script test.ps1 -command psversion ` +-action { if ((get-executionpolicy) -eq "RemoteSigned") { break }} +``` + +The Break keyword in the action directs the debugger to execute the +breakpoint. You can also use the Continue keyword to direct the debugger to +execute without breaking. Because the default keyword is Continue, you must +specify Break to stop execution. + +Now, run the script. + +```powershell +PS C:\ps-test> .\test.ps1 +Hit Command breakpoint on 'C:\ps-test\test.ps1:psversion' + +test.ps1:12 psversion +```powershell + +Because the execution policy is set to RemoteSigned, execution stops +at the function call. + +At this point, you might want to check the call stack. Use the Get-PsCallStack +cmdlet or the Get-PsCallStack debugger command (k). The following command gets +the current call stack. + +```powershell +DBG> k +2: prompt +1: .\test.ps1: $args=[] +0: prompt: $args=[] +``` + +This example demonstrates just a few of the many ways to use the Windows +PowerShell debugger. + +For more information about the debugger cmdlets, type the following command: + +```powershell +help -full +``` + +For example, type: + +```powershell +help set-psbreakpoint -full +``` + +## Other Debugging Features in PowerShell + +In addition to the PowerShell debugger, PowerShell includes +several other features that you can use to debug scripts and functions. + +- Windows PowerShell Integrated Scripting Environment (ISE) includes an + interactive graphical debugger. For more information, start PowerShell ISE + and press F1. + +- The Set-PSDebug cmdlet offers very basic script debugging features, + including stepping and tracing. + +- Use the Set-StrictMode cmdlet to detect references to uninitialized + variables, to references to non-existent properties of an object, and to + function syntax that is not valid. + +- Add diagnostic statements to a script, such as statements that display the + value of variables, statements that read input from the command line, or + statements that report the current instruction. Use the cmdlets that contain + the Write verb for this task, such as Write-Host, Write-Debug, Write-Warning, + and Write-Verbose. + +## SEE ALSO + +- [Disable-PsBreakpoint](../../Microsoft.PowerShell.Utility/Disable-PsBreakpoint.md) +- [Enable-PsBreakpoint](../../Microsoft.PowerShell.Utility/Enable-PsBreakpoint.md) +- [Get-PsBreakpoint](../../Microsoft.PowerShell.Utility/Get-PsBreakpoint.md) +- [Get-PsCallStack](../../Microsoft.PowerShell.Utility/Get-PsCallStack.md) +- [Remove-PsBreakpoint](../../Microsoft.PowerShell.Utility/Remove-PsBreakpoint.md) +- [Set-PsBreakpoint](../../Microsoft.PowerShell.Utility/Set-PsBreakpoint.md) +- [Write-Debug](../../Microsoft.PowerShell.Utility/Write-Debug.md) +- [Write-Verbose](../../Microsoft.PowerShell.Utility/Write-Verbose.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Do.md b/reference/7/Microsoft.PowerShell.Core/About/about_Do.md new file mode 100644 index 000000000000..6335b45880e5 --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Do.md @@ -0,0 +1,96 @@ +--- +ms.date: 06/09/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Do +--- +# About Do + +## SHORT DESCRIPTION +Runs a statement list one or more times, subject to a While or Until +condition. + +## LONG DESCRIPTION + +The Do keyword works with the While keyword or the Until keyword to run the +statements in a script block, subject to a condition. Unlike the related +While loop, the script block in a Do loop always runs at least once. + +A **Do-While** loop is a variety of the While loop. In a **Do-While** loop, +the condition is evaluated after the script block has run. As in a While +loop, the script block is repeated as long as the condition evaluates to +true. + +Like a **Do-While** loop, a **Do-Until** loop always runs at least once +before the condition is evaluated. However, the script block runs only +while the condition is false. + +The *Continue* and *Break* flow control keywords can be used in a +**Do-While** loop or in a **Do-Until** loop. + +### Syntax + +The following shows the syntax of the **Do-While** statement: + +```powershell +do {} while () +``` + +The following shows the syntax of the **Do-Until** statement: + +```powershell +do {} until () +``` + +The statement list contains one or more statements that run each time the +loop is entered or repeated. + +The condition portion of the statement resolves to true or false. + +### Example + +The following example of a Do statement counts the items in an array until +it reaches an item with a value of 0. + +```powershell +C:\PS> $x = 1,2,78,0 +C:\PS> do { $count++; $a++; } while ($x[$a] -ne 0) +C:\PS> $count +3 +``` + +The following example uses the Until keyword. Notice that the not equal to +operator (`-ne`) is replaced by the equal to operator (`-eq`). + +```powershell +C:\PS> $x = 1,2,78,0 +C:\PS> do { $count++; $a++; } until ($x[$a] -eq 0) +C:\PS> $count +3 +``` + +The following example writes all the values of an array, skipping any value +that is less than zero. + +```powershell +do { + if ($x[$a] -lt 0) { continue } + Write-Host $x[$a] +} +while (++$a -lt 10) +``` + +## SEE ALSO + +[about_While](about_While.md) + +[about_Operators](about_Operators.md) + +[about_Assignment_Operators](about_Assignment_Operators.md) + +[about_Comparison_Operators](about_Comparison_Operators.md) + +[about_Break](about_Break.md) + +[about_Continue](about_Continue.md) \ No newline at end of file diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Enum.md b/reference/7/Microsoft.PowerShell.Core/About/about_Enum.md new file mode 100644 index 000000000000..9d96349333ae --- /dev/null +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Enum.md @@ -0,0 +1,201 @@ +--- +ms.date: 11/27/2017 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_Enum +--- +# About Enum + +## SHORT DESCRIPTION +The `enum` statement is used to declare an enumeration. An enumeration is a +distinct type that consists of a set of named labels called the enumerator +list. + +## LONG DESCRIPTION + +The `enum` statement allows you to create a strongly typed set of labels. That +enumeration can be used in the code without having to parse or check for +spelling errors. + +Enumerations are internally represented as integers with a starting value of +zero. The first label in the list is assigned the value zero. The remaining +labels are assigned with consecutive numbers. + +In the definition, labels can be given any integer value. Labels with no value +assigned take the next integer value. + +## Syntax (basic) + +```syntax +enum { +