full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Disconnect-Unity.ps1
|
Disconnect-Unity.ps1
|
Function Disconnect-Unity {
<#
.SYNOPSIS
Disconnects from an EMC Unity Array
.DESCRIPTION
Disconnects from an EMC Unity Array. By default, Disconnect-Unity closes all sessions. To close a specific session, use the -Session parameter.
When a session is disconnected, it is removed form the default array list.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.EXAMPLE
Disconnect-Unity
Disconnects all the sessions
.EXAMPLE
$Session = Get-UnitySession -Server 192.168.0.1
Disconnect-Unity -Session $Session
Disconnects all the sessions matching the IP of the array 192.168.0.1
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'EMC Unity Session')]
$session = $global:DefaultUnitySession
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
}
Process {
Foreach ($sess in $session) {
Write-Verbose "Processing session with array: $($sess.Server) and SessionID: $($sess.SessionID) "
If ($Sess.IsConnected -eq $false) {
Write-Verbose "Session already disconnected. Delete it from DefaultUnitySession"
$global:DefaultUnitySession = $global:DefaultUnitySession | where-object {$_.SessionId -notmatch $Sess.SessionId}
} else {
#Building URI
$uri = 'https://'+$sess.Server+'/api/types/loginSessionInfo/action/logout'
Write-Verbose "URI: $URI"
Write-Verbose "Disconnecting session $($sess.SessionID)"
if ($pscmdlet.ShouldProcess($sess.Server,"Disconnecting from Unity Array")) {
#Sending request
$request = Invoke-WebRequest -Uri $URI -ContentType "application/json" -Websession $sess.Websession -Headers $sess.headers -Method POST
If ($request.StatusCode -eq 200) {
Write-Verbose "Delete session from DefaultUnitySession"
$global:DefaultUnitySession = $global:DefaultUnitySession | where-object {$_.SessionId -notmatch $Sess.SessionId}
}
}
}
}
}
End {
## update the Windows PowerShell titlebar with a bit of info about the Unity array(s) to which the PowerShell session is connected
Update-TitleBarForUnityConnection
}
}
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityPoolUnit.ps1
|
Get-UnityPoolUnit.ps1
|
Function Get-UnityPoolUnit {
<#
.SYNOPSIS
Queries the EMC Unity array to retrieve informations about poolUnit.
.DESCRIPTION
Querries the EMC Unity array to retrieve informations about poolUnit.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityPoolUnit
Retrieve information about poolUnit
.EXAMPLE
Get-UnityPoolUnit -Name 'POOL01'
Retrieves information about poolUnit named POOL01
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Pool Unit Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Pool Unit ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/poolUnit/instances' #URI
$TypeName = 'UnityPoolUnit'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnityLUN.ps1
|
Set-UnityLUN.ps1
|
Function Set-UnityLUN {
<#
.SYNOPSIS
Modifies LUN parameters.
.DESCRIPTION
Modifies LUN parameters.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running.
If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.PARAMETER ID
ID or Object.
.PARAMETER Name
New name of the LUN unique to the system.
.PARAMETER Description
New description of the LUN.
.PARAMETER Size
New LUN size. The size parameter can be greater than the current LUN size in this case the LUN is expanded.
.PARAMETER fastVPParameters
FAST VP settings for the storage resource
.PARAMETER isCompressionEnabled
Indicates whether to enable inline compression for the LUN. Default is True
.PARAMETER host
List of host to grant access to LUN.
.PARAMETER accessMask
Host access mask. Might be:
- NoAccess: No access.
- Production: Access to production LUNs only.
- Snapshot: Access to LUN snapshots only.
- Both: Access to both production LUNs and their snapshots.
.PARAMETER append
Add new host access to the existing configuration.
.PARAMETER snapSchedule
Snapshot schedule assigned to the storage resource
.PARAMETER isSnapSchedulePaused
Indicates whether the assigned snapshot schedule is paused.
.EXAMPLE
Set-UnityLUN -Name 'LUN01' -Description 'Modified description'
Change the description of the LUN named LUN01
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'LUN ID or Object')]
[String[]]$ID,
[Parameter(Mandatory = $false,HelpMessage = 'New Name of the LUN')]
[String]$Name,
[Parameter(Mandatory = $false,HelpMessage = 'New LUN Description')]
[String]$Description,
# lunParameters
[Parameter(Mandatory = $false,HelpMessage = 'New LUN Size in Bytes')]
[uint64]$Size,
[Parameter(Mandatory = $false,HelpMessage = 'FAST VP settings for the storage resource')]
[TieringPolicyEnum]$fastVPParameters,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether to enable inline compression for the LUN. Default is True')]
[bool]$isCompressionEnabled,
# snapScheduleParameters
[Parameter(Mandatory = $false,HelpMessage = 'ID of a protection schedule to apply to the storage resource')]
[String]$snapSchedule,
[Parameter(Mandatory = $false,HelpMessage = 'Is assigned snapshot schedule is paused ? (Default is false)')]
[bool]$isSnapSchedulePaused = $false,
# hostParameters
[Parameter(Mandatory = $false,HelpMessage = 'Host to grant access to LUN')]
[String[]]$host,
[Parameter(Mandatory = $false,HelpMessage = 'Append Host access to existing configuration')]
[Switch]$append,
[Parameter(Mandatory = $false,HelpMessage = 'Host access mask')]
[HostLUNAccessEnum]$accessMask = 'Production'
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/storageResource/<id>/action/modifyLun'
$Type = 'LUN'
$TypeName = 'UnityLUN'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityLUN -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityLUN -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
$UnitystorageResource = Get-UnitystorageResource -Session $sess | Where-Object {($_.Name -like $ObjectName) -and ($_.luns.id -like $ObjectID)}
# Creation of the body hash
$body = @{}
# Name parameter
If ($PSBoundParameters.ContainsKey('Name')) {
$body["name"] = $Name
}
# Description parameter
If ($PSBoundParameters.ContainsKey('description')) {
$body["description"] = $Description
}
# lunParameters parameter
If (($PSBoundParameters.ContainsKey('size')) -or ($PSBoundParameters.ContainsKey('host')) -or ($PSBoundParameters.ContainsKey('fastVPParameters')) -or ($PSBoundParameters.ContainsKey('isCompressionEnabled'))) {
$body["lunParameters"] = @{}
$lunParameters = @{}
If ($PSBoundParameters.ContainsKey('Size')) {
$lunParameters["size"] = $($Size)
}
If ($PSBoundParameters.ContainsKey('fastVPParameters')) {
$lunParameters["fastVPParameters"] = @{}
$fastVPParam = @{}
$fastVPParam['tieringPolicy'] = $fastVPParameters
$lunParameters["fastVPParameters"] = $fastVPParam
}
If ($PSBoundParameters.ContainsKey('isCompressionEnabled')) {
$lunParameters["isCompressionEnabled"] = $isCompressionEnabled
}
If ($PSBoundParameters.ContainsKey('host')) {
$lunParameters["hostAccess"] = @()
$hostAccess = @()
foreach ($h in $host) {
$blockHostAccessParam = @{}
$blockHostAccessParam['host'] = @{}
$HostParam = @{}
$HostParam['id'] = $h
$blockHostAccessParam['host'] = $HostParam
$blockHostAccessParam['accessMask'] = $accessMask
$hostAccess += $blockHostAccessParam
}
If ($PSBoundParameters.ContainsKey('append')) {
foreach ($h in $Object.hostAccess) {
if (-not ($hostAccess.host.id -contains $h.host.id)) {
$blockHostAccessParam = @{}
$blockHostAccessParam['host'] = @{}
$HostParam = @{}
$HostParam['id'] = $h.host.id
$blockHostAccessParam['host'] = $HostParam
$blockHostAccessParam['accessMask'] = $h.accessMask
$hostAccess += $blockHostAccessParam
}
}
} else {
Write-Warning -Message 'The existing host access parameters will be overwritten by the new settings. It could result to data unavailibility. Use the -Append parameter to add the new settings to the existing configuration.'
}
$lunParameters["hostAccess"] = $hostAccess
}
$body["lunParameters"] = $lunParameters
}
#snapScheduleParameters
If ($snapSchedule) {
$body["snapScheduleParameters"] = @{}
$snapScheduleParameters = @{}
$snapScheduleParam = @{}
$snapScheduleParam["id"] ="$($snapSchedule)"
$snapScheduleParameters["snapSchedule"] = $snapScheduleParam
$snapScheduleParameters["isSnapSchedulePaused"]= "$($isSnapSchedulePaused)"
$body["snapScheduleParameters"] = $snapScheduleParameters
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$UnitystorageResource.id
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $ObjectName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityLUN -Session $Sess -ID $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnityIscsiPortal.ps1
|
Set-UnityIscsiPortal.ps1
|
Function Set-UnityIscsiPortal {
<#
.SYNOPSIS
Modify an iSCSI network portal.
.DESCRIPTION
Modify an iSCSI network portal.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
iSCSI Network Portal ID or Object.
.PARAMETER ipAddress
IPv4 or IPv6 address for the iSCSI Network Portal.
.PARAMETER netmask
IPv4 netmask for the iSCSI Network Portal, if the iSCSI Network Portal uses an IPv4 address.
.PARAMETER v6PrefixLength
Prefix length in bits for IPv6 address.
.PARAMETER gateway
IPv4 or IPv6 gateway address for the iSCSI Network Portal.
.PARAMETER vlanId
Ethernet virtual LAN identifier used for tagging iSCSI portal outgoing packets and for filtering iSCSI portal incoming packets.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Set-UnityIscsiPortal -ID 'if_6' -vlanId 10
Modifies the iSCSI network portal with id 'if_6'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'iSCSI Network Portal ID or Oject')]
[String[]]$ID,
[Parameter(Mandatory = $false,HelpMessage = 'IPv4 or IPv6 address for the interface.')]
[string]$ipAddress,
[Parameter(Mandatory = $false,HelpMessage = 'IPv4 netmask for the interface, if the interface uses an IPv4 address.')]
[string]$netmask,
[Parameter(Mandatory = $false,HelpMessage = 'Prefix length in bits for IPv6 address.')]
[String[]]$v6PrefixLength,
[Parameter(Mandatory = $false,HelpMessage = 'Ethernet virtual LAN identifier used for tagging iSCSI portal outgoing packets and for filtering iSCSI portal incoming packets.')]
[String[]]$vlanId,
[Parameter(Mandatory = $false,HelpMessage = 'IPv4 or IPv6 gateway address for the interface.')]
[string]$gateway
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/iscsiPortal/<id>/action/modify'
$Type = 'iSCSI Portal'
$TypeName = 'UnityIscsiPortal'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityIscsiPortal -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityIscsiPortal -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
If ($PSBoundParameters.ContainsKey('ipAddress')) {
$body["ipAddress"] = $ipAddress
}
If ($PSBoundParameters.ContainsKey('netmask')) {
$body["netmask"] = "$($netmask)"
}
If ($PSBoundParameters.ContainsKey('v6PrefixLength')) {
$body["v6PrefixLength"] = "$($v6PrefixLength)"
}
If ($PSBoundParameters.ContainsKey('vlanId')) {
$body["vlanId"] = "$($vlanId)"
}
If ($PSBoundParameters.ContainsKey('gateway')) {
$body["gateway"] = "$($gateway)"
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $ObjectName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityIscsiPortal -Session $Sess -id $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnityHostIPPort.ps1
|
New-UnityHostIPPort.ps1
|
Function New-UnityHostIPPort {
<#
.SYNOPSIS
Create a host IP Port configuration.
.DESCRIPTION
Create a host IP Port configuration.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
New-UnityHostIPPort -host 'Host_1' - address 192.168.0.1 -netmask 255.255.255.0
Create Host IP Port for the host with ID 'Host_1'.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#Host ID or Object
[Parameter(Mandatory = $true,Position = 1,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Host ID or Object')]
$host,
#IP address or network name of the port.
[Parameter(Mandatory = $true,HelpMessage = 'IP address or network name of the port.')]
[string]$address,
#(Applies to IPV4 only.) Subnet mask for the IP address, if any.
[Parameter(Mandatory = $false,HelpMessage = '(Applies to IPV4 only.) Subnet mask for the IP address, if any.')]
[string]$netmask,
#(Applies to IPV6 only.) Subnet mask length.
[Parameter(Mandatory = $false,HelpMessage = '(Applies to IPV6 only.) Subnet mask length.')]
[string]$v6PrefixLength,
#(Applies to NFS access only.) Indicates whether the port should be ignored when storage access is granted to the host
[Parameter(Mandatory = $false,HelpMessage = '(Applies to NFS access only.) Indicates whether the port should be ignored when storage access is granted to the host')]
[bool]$isIgnored
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/types/hostIPPort/instances'
$Type = 'Host IP Port'
$TypeName = 'UnityHost'
$StatusCode = 201
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
Foreach ($h in $Host) {
# Determine input and convert to object if necessary
Switch ($h.GetType().Name)
{
"String" {
$Object = get-UnityHost -Session $Sess -ID $h
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($h.GetType().Name)"
$ObjectID = $h.id
If ($Object = Get-UnityHost -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
$body["host"] = @{}
$hostParameters = @{}
$hostParameters["id"] = $ObjectID
$body["host"] = $hostParameters
# address parameter
$body["address"] = $address
If ($PSBoundParameters.ContainsKey('netmask')) {
$body["netmask"] = $netmask
}
If ($PSBoundParameters.ContainsKey('v6PrefixLength')) {
$body["v6PrefixLength"] = $v6PrefixLength
}
If ($PSBoundParameters.ContainsKey('isIgnored')) {
$body["isIgnored"] = $isIgnored
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
If ($Sess.TestConnection()) {
##Building the URL
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $Type $n")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
Write-Verbose "Request status code: $($request.StatusCode)"
If ($request.StatusCode -eq $StatusCode) {
#Formating the result. Converting it from JSON to a Powershell object
$results = ($request.content | ConvertFrom-Json).content
Write-Verbose "$Type with the ID $($results.id) has been created"
Get-UnityHostIPPort -Session $Sess -ID $results.id
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End If ($request.StatusCode -eq $StatusCode)
} # End If ($Sess.TestConnection())
} # End Foreach
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityMgmtInterfaceSettings.ps1
|
Get-UnityMgmtInterfaceSettings.ps1
|
Function Get-UnityMgmtInterfaceSettings {
<#
.SYNOPSIS
Informations about global settings for the management interfaces.
.DESCRIPTION
Informations about global settings for the management interfaces.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.EXAMPLE
Get-UnityMgmtInterfaceSettings
Retrieve informations about global settings for the management interfaces.
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true})
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/mgmtInterfaceSettings/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityMgmtInterfaceSettings'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Remove-UnityNasServer.ps1
|
Remove-UnityNasServer.ps1
|
Function Remove-UnityNASServer {
<#
.SYNOPSIS
Delete a Nas Server.
.DESCRIPTION
Delete a Nas Server.
Before you can delete a NAS server, you must first delete all storage resources associated with it.
Deleting a NAS server removes everything configured on the NAS server, but does not delete the storage resources that use it.
You cannot delete a NAS server while it has any associated storage resources.
After the storage resources are deleted, the files and folders inside them cannot be restored from snapshots.
Back up the data from the storage resources before deleting them from the system.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Specifies the NAS server ID or Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Remove-UnityNasServer -ID 'nas_6'
Delete the Nas Server with ID 'nas_6'
.EXAMPLE
Get-UnityNasServer -Name 'NAS01' | Remove-UnityNasServer
Delete the Nas Server named 'NAS01'. The NAS server's informations are provided by the Get-UnityNasServer through the pipeline.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#NasServer
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Nas server ID or Object')]
$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/nasServer/<id>'
$Type = 'NAS Server'
$TypeName = 'UnityNasServer'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityNASServer -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityNASServer -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
if ($pscmdlet.ShouldProcess($Sess.Name,"Delete $Type $ObjectName")) {
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'DELETE'
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been deleted"
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityVMwareNFS.ps1
|
Get-UnityVMwareNFS.ps1
|
Function Get-UnityVMwareNFS {
<#
.SYNOPSIS
Queries the EMC Unity array to retrieve informations about VMware NFS LUN.
.DESCRIPTION
Querries the EMC Unity array to retrieve informations about VMware NFS LUN.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityVMwareNFS
Retrieve information about all VMware NFS LUN
.EXAMPLE
Get-UnityVMwareNFS -Name 'DATASTORE01'
Retrieves information about VMware NFS LUN named DATASTORE01
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'VMware LUN Name')]
[String[]]$Name='*',
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'VMware LUN ID')]
[String[]]$ID='*'
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$ResultCollection = @()
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
$StorageResource = Get-UnitystorageResource -Session $Sess -Type 'vmwarefs'
If ($StorageResource) {
$ResultCollection += Get-UnityFilesystem -Session $Sess -ID $StorageResource.filesystem.id
}
}
}
}
Process {
#Filter results
If ($ResultCollection) {
Switch ($PsCmdlet.ParameterSetName) {
'Name' {
Foreach ($N in $Name) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Return result(s) with the filter: $($N)"
Write-Output $ResultCollection | Where-Object {$_.Name -like $N}
Write-Debug -Message "[$($MyInvocation.MyCommand)] Found $($ResultCollection.Count) item(s)"
}
}
'ID' {
Foreach ($I in $ID) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Return result(s) with the filter: $($I)"
Write-Output $ResultCollection | Where-Object {$_.Id -like $I}
Write-Debug -Message "[$($MyInvocation.MyCommand)] Found $($ResultCollection.Count) item(s)"
}
}
} #End Switch
} # End If ($ResultCollection)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Remove-UnityUser.ps1
|
Remove-UnityUser.ps1
|
Function Remove-UnityUser {
<#
.SYNOPSIS
Delete a local user.
.DESCRIPTION
Delete a local user.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
User ID or Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running.
If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Remove-UnityUser -Name 'User'
Delete the user named 'user'
.EXAMPLE
Get-UnityUSer -Name 'User' | Remove-UnityUser
Delete the user named 'user'. The user's information are provided by the Get-UnityUser through the pipeline.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'User ID or Object')]
$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/user/<id>'
$Type = 'User'
$TypeName = 'UnityUser'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityUser -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityUser -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
if ($pscmdlet.ShouldProcess($Sess.Name,"Delete $Type $ObjectName")) {
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'DELETE'
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been deleted"
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnityMetricRealTimeQuery.ps1
|
New-UnityMetricRealTimeQuery.ps1
|
Function New-UnityMetricRealTimeQuery {
<#
.SYNOPSIS
Creates a new metrics real-time query.
.DESCRIPTION
Creates a new metrics real-time query.
After you create this query, the results are available whith the command Get-UnityMetricQueryResult
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER paths
Metric stat paths associated with the query.
.PARAMETER interval
Sampling frequency for the query in seconds.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
New-UnityMetricRealTimeQuery -paths sp.*.cpu.uptime -interval 60
Create a new query to gather statisitics about 'sp.*.cpu.uptime'.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#UnityMetricRealTimeQuery
[Parameter(Mandatory = $true,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Metric stat paths associated with the query.')]
$paths,
[Parameter(Mandatory = $true,HelpMessage = 'Sampling frequency for the query.')]
[Uint64]$interval
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/types/metricRealTimeQuery/instances'
$Type = 'Real Time Metric Query'
$StatusCode = 201
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
#### REQUEST BODY
# Creation of the body hash
$body = @{}
$body["paths"] = @()
foreach ($path in $paths) {
$body["paths"] += $path
}
$body["interval"] = $interval
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
If ($Sess.TestConnection()) {
##Building the URL
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $Type on storage resource ID $ObjectID")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
Write-Verbose "Request status code: $($request.StatusCode)"
If ($request.StatusCode -eq $StatusCode) {
#Formating the result. Converting it from JSON to a Powershell object
$results = ($request.content | ConvertFrom-Json).content
Write-Verbose "$Type with the ID $($results.id) has been created"
Get-UnityMetricRealTimeQuery -Session $Sess -ID $results.id
} # End If ($request.StatusCode -eq $StatusCode)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnityPool.ps1
|
New-UnityPool.ps1
|
Function New-UnityPool {
<#
.SYNOPSIS
Creates a new storage pool.
.DESCRIPTION
Creates a new storage pool. Storage pools are the groups of disks on which you create storage resources like LUN or filesystems.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Name
Name of the pool.
.PARAMETER Description
Description of the pool.
.PARAMETER virtualDisk
Virtual Disks only with associated parameters to add to the pool. See examples for details.
.PARAMETER raidGroup
Parameters to add RAID groups to the pool (disk group, number of disks, RAID level, stripe length). See examples for details.
.PARAMETER isFASTCacheEnabled
Specify whether to enable FAST Cache on the storage pool.
.PARAMETER isFASTVpScheduleEnabled
Specify whether to enable scheduled data relocations for the pool.
.PARAMETER alertThreshold
For thin provisioning, specify the threshold, as a percentage, when the system will alert on the amount of subscription space used.
.PARAMETER isHarvestEnabled
Indicate whether the system should check the pool full high water mark for autodelete.
.PARAMETER poolSpaceHarvestHighThreshold
Specify the pool full high watermark for the storage pool.
.PARAMETER poolSpaceHarvestLowThreshold
Specify the pool full low watermark for the storage pool.
.PARAMETER isSnapHarvestEnabled
Indicate whether the system should check the snapshot space used high water mark for auto-delete.
.PARAMETER snapSpaceHarvestHighThreshold
Specify the snapshot space used high watermark to trigger auto-delete on the storage pool.
.PARAMETER snapSpaceHarvestLowThreshold
Specify the snapshot space used low watermark to trigger auto-delete on the storage pool.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
New-UnityPool -Name 'POOL01' -virtualDisk @{"id"='vdisk_1';"tier"='Extreme_Performance'},@{"id"='vdisk_2';"tier"='Capacity'}
Create pool named 'POOL01' with virtual disks 'vdisk_1' and 'vdisk_2'. Virtual disks are assigned to the Extreme Performance and Capacity tier. Apply to Unity VSA only.
.EXAMPLE
New-UnityPool -Name 'POOL01' -raidGroup @{"id"='dg_11';"numDisks"= 15; 'raidType'='RAID5'; 'stripeWidth'='5'}
Create pool named 'POOL01' with with 15 disks from diskgroup ID 'dg_11'.RAID protection is a 'RAID5' with a stripe width of 5 (4+1). Apply to physical deployment only.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High',DefaultParameterSetName="RaidGroup")]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#UnityPool
[Parameter(Mandatory = $true,Position = 1,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Pool Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,HelpMessage = 'Pool Description')]
[String]$Description,
[Parameter(Mandatory = $true,ParameterSetName="VirtualDisk",HelpMessage = 'Parameters to add virtual disks to the pool')]
[array]$virtualDisk,
[Parameter(Mandatory = $true,ParameterSetName="RaidGroup",HelpMessage = 'Parameters to add RAID groups to the pool')]
[array]$raidGroup,
[Parameter(Mandatory = $false,HelpMessage = 'Threshold at which the system will generate alerts about the free space in the pool')]
[Int]$alertThreshold,
[Parameter(Mandatory = $false,HelpMessage = 'Pool used space high threshold at which the system will automatically starts to delete snapshots in the pool, specified as a percentage with .01% granularity')]
[Long]$poolSpaceHarvestHighThreshold,
[Parameter(Mandatory = $false,HelpMessage = 'Pool used space low threshold under which the system will automatically stop deletion of snapshots in the pool, specified as a percentage with .01% granularity')]
[Long]$poolSpaceHarvestLowThreshold,
[Parameter(Mandatory = $false,HelpMessage = 'Snapshot used space high threshold at which the system automatically starts to delete snapshots in the pool, specified as a percentage with .01% granularity.')]
[Long]$snapSpaceHarvestHighThreshold,
[Parameter(Mandatory = $false,HelpMessage = 'Snapshot used space low threshold below which the system will stop automatically deleting snapshots in the pool, specified as a percentage with .01% granularity.')]
[Long]$snapSpaceHarvestLowThreshold,
[Parameter(Mandatory = $false,HelpMessage = 'Is Harvest Enabled?')]
[Bool]$isHarvestEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Is Snapshot Harvest Enabled')]
[Bool]$isSnapHarvestEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Is FAST Cache Enabled?')]
[Bool]$isFASTCacheEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Is FAST Vp Schedule Enabled?')]
[Bool]$isFASTVpScheduleEnabled
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/types/pool/instances'
$Type = 'Pool'
$StatusCode = 201
$tier = @{
"Extreme_Performance" = "10"
"Performance" = "20"
"Capacity" = "30"
}
$Raid =@{
"None" = "0"
"RAID5" = "1"
"RAID0" = "2"
"RAID1" = "3"
"RAID3" = "4"
"RAID10" = "7"
"RAID6" = "10"
"Mixed" = "12"
"Automatic" = "48879"
}
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
Foreach ($n in $Name) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
# Name parameter
$body["name"] = "$($n)"
# Description parameter
If ($Description) {
$body["description"] = "$($Description)"
}
If ($virtualDisk) {
# addPoolUnitParameters parameter
$body["addPoolUnitParameters"] = @()
Foreach ($vdisk in $virtualDisk) {
$addPoolUnitParameters = @{}
$addPoolUnitParameters["poolUnit"] = @{}
$poolUnit = @{}
$poolUnit["id"] = "$($vdisk['id'])"
$tierType = "$($tier["$($vdisk['tier'])"])"
$addPoolUnitParameters["poolUnit"] = $poolUnit
$addPoolUnitParameters["tierType"] = $tierType
$body["addPoolUnitParameters"] += $addPoolUnitParameters
}
}
If ($raidGroup) {
# addRaidGroupParameters parameter
$body["addRaidGroupParameters"] = @()
Foreach ($rg in $raidGroup) {
$addRaidGroupParameters = @{}
$addRaidGroupParameters["dskGroup"] = @{}
$diskGroup = @{}
$diskGroup["id"] = "$($rg['id'])"
$addRaidGroupParameters["dskGroup"] = $diskGroup
$addRaidGroupParameters["numDisks"] = "$($rg['numDisks'])"
$addRaidGroupParameters["raidType"] = "$($raid["$($rg['raidType'])"])"
$addRaidGroupParameters["stripeWidth"] = "$($rg['stripeWidth'])"
$body["addRaidGroupParameters"] += $addRaidGroupParameters
}
}
If ($alertThreshold) {
$body["alertThreshold"] = "$($alertThreshold)"
}
If ($poolSpaceHarvestHighThreshold) {
$body["poolSpaceHarvestHighThreshold"] = "$($poolSpaceHarvestHighThreshold)"
}
If ($poolSpaceHarvestLowThreshold) {
$body["poolSpaceHarvestLowThreshold"] = "$($poolSpaceHarvestLowThreshold)"
}
If ($snapSpaceHarvestHighThreshold) {
$body["snapSpaceHarvestHighThreshold"] = "$($snapSpaceHarvestHighThreshold)"
}
If ($snapSpaceHarvestLowThreshold) {
$body["snapSpaceHarvestLowThreshold"] = "$($snapSpaceHarvestLowThreshold)"
}
If ($PSBoundParameters.ContainsKey('isHarvestEnabled')) {
$body["isHarvestEnabled"] = $isHarvestEnabled
}
If ($PSBoundParameters.ContainsKey('isSnapHarvestEnabled')) {
$body["isSnapHarvestEnabled"] = $isSnapHarvestEnabled
}
If ($PSBoundParameters.ContainsKey('isFASTCacheEnabled')) {
$body["isFASTCacheEnabled"] = $isFASTCacheEnabled
}
If ($PSBoundParameters.ContainsKey('isFASTVpScheduleEnabled')) {
$body["isFASTVpScheduleEnabled"] = $isFASTVpScheduleEnabled
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
If ($Sess.TestConnection()) {
##Building the URL
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $Type $n")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
Write-Verbose "Request status code: $($request.StatusCode)"
If ($request.StatusCode -eq $StatusCode) {
#Formating the result. Converting it from JSON to a Powershell object
$results = ($request.content | ConvertFrom-Json).content
Write-Verbose "$Type with the ID $($results.id) has been created"
Get-UnityPool -Session $Sess -ID $results.id
} # End If ($request.StatusCode -eq $StatusCode)
} # End If ($Sess.TestConnection())
} # End Foreach
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnityAlert.ps1
|
Set-UnityAlert.ps1
|
Function Set-UnityAlert {
<#
.SYNOPSIS
Update the "ack" status of alert.
.DESCRIPTION
Update the "ack" status of alert.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
Management interface ID or Object.
.PARAMETER isAcknowledged
Whether alert is acknowledged.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Set-UnityAlert -ID 'alert_38' -isAcknowledged $true
Acknoledge alert with id 'alert_38'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'ID or Object')]
[String[]]$ID,
[Parameter(Mandatory = $false,HelpMessage = 'Whether alert is acknowledged.')]
[bool]$isAcknowledged = $false
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/alert/<id>/action/modify'
$Type = 'Pool'
$TypeName = 'UnityAlert'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityAlert -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityAlert -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
$body["isAcknowledged"] = $isAcknowledged
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $($ObjectName)")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityAlert -Session $Sess -id $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnitySnapSchedule.ps1
|
New-UnitySnapSchedule.ps1
|
Function New-UnitySnapSchedule {
<#
.SYNOPSIS
Creates a new snapshot schedule.
.DESCRIPTION
Creates a new snapshot schedule.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Name
Name of new schedule.
.PARAMETER type
Type of snapshot schedule rule. Values are:
- N_HOURS_AT_MM: Snap every <interval> hours, at <minutes> past the hour. Supported parameters: interval (required), minutes (optional, default 0).
- DAY_AT_HHMM: Specify a list of <hour[,...]> to snap one or more times each day at <minutes> past the hour. Supported parameters: hours (at least one required), minutes (optional).
- N_DAYS_AT_HHMM: Snap every <interval> days at the time <hours>:<minutes>. Supported Parameters: interval (required), hours (optional, exactly one), minutes (optional).
- SELDAYS_AT_HHMM: Snap on the selected <daysOfWeek>, at the time <hours>:<minutes>. Supported parameters: daysOfWeek (at least one required), hours (optional, default 0), minutes (optional, default 0).
- NTH_DAYOFMONTH_AT_HHMM: Snap on the selected <daysOfMonth>, at the time <hours>:<minutes>. Supported parameters: daysOfMonth (at least one required), hours (optional, default 0), minutes (optional, default 0).
.PARAMETER minute
Minute frequency for the snapshot schedule rule.
.PARAMETER hours
Hourly frequency for the snapshot schedule rule.
.PARAMETER daysOfWeek
Days of the week for which the snapshot schedule rule applies.
.PARAMETER daysOfMonth
Days of the month for which the snapshot schedule rule applies.
.PARAMETER interval
Number of days or hours between snaps, depending on the rule type.
.PARAMETER isAutoDelete
Indicates whether the system can automatically delete the snapshot based on pool automatic-deletion thresholds. Values are:
- $True: System can delete the snapshot based on pool automatic-deletion thresholds.
- $False: System cannot delete the snapshot based on pool automatic-deletion thresholds.
.PARAMETER retentionTime
(Applies when the value of the isAutoDelete attribute is false.) Period of time in seconds for which to keep the snapshot.
.PARAMETER accessType
For a file system or VMware NFS datastore snapshot schedule, indicates whether the snapshot created by the schedule has checkpoint or protocol type access
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
New-UnitySnapSchedule -Name 'SCHEDULE01' -Type N_HOURS_AT_MM -Interval 12 -Minute 30
Create snapshot schedule named 'SCHEDULE01'. Snap every 12 hours, at 30 minutes past the hour.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#UnitySnapSchedule
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Name of new schedule')]
[String[]]$name,
#UnitySnapScheduleRule
[Parameter(Mandatory = $true,HelpMessage = 'Type of snapshot schedule rule.')]
[ScheduleTypeEnum]$type,
[Parameter(Mandatory = $false,HelpMessage = 'Minute frequency for the snapshot schedule rule.')]
[UInt32]$minute,
[Parameter(Mandatory = $false,HelpMessage = 'Hourly frequency for the snapshot schedule rule.')]
[UInt32[]]$hours,
[Parameter(Mandatory = $false,HelpMessage = 'Days of the week for which the snapshot schedule rule applies.')]
[DayOfWeekEnum[]]$daysOfWeek,
[Parameter(Mandatory = $false,HelpMessage = 'Days of the month for which the snapshot schedule rule applies.')]
[UInt32]$daysOfMonth,
[Parameter(Mandatory = $false,HelpMessage = 'Number of days or hours between snaps, depending on the rule type.')]
[UInt32]$interval,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether the system can automatically delete the snapshot based on pool automatic-deletion thresholds.')]
[bool]$isAutoDelete,
[Parameter(Mandatory = $false,HelpMessage = '(Applies when the value of the isAutoDelete attribute is false.) Period of time in seconds for which to keep the snapshot.')]
[UInt64]$retentionTime,
[Parameter(Mandatory = $false,HelpMessage = 'For a file system or VMware NFS datastore snapshot schedule, indicates whether the snapshot created by the schedule has checkpoint or protocol type access.')]
[FilesystemSnapAccessTypeEnum]$accessType
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/types/snapSchedule/instances'
$TypeName = 'Schedule'
$StatusCode = 201
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
Foreach ($n in $name) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
$body["name"] = $n
$body["rules"] = @()
$snapScheduleRule = @{}
$snapScheduleRule["type"] = $type
If ($PSBoundParameters.ContainsKey('minute')) {
$snapScheduleRule["minute"] = $minute
}
If ($PSBoundParameters.ContainsKey('hours')) {
$snapScheduleRule["hours"] = @()
$hoursParameters += $hours
$snapScheduleRule["hours"] = $hoursParameters
}
If ($PSBoundParameters.ContainsKey('daysOfWeek')) {
$snapScheduleRule["daysOfWeek"] = $daysOfWeek
}
If ($PSBoundParameters.ContainsKey('daysOfMonth')) {
$snapScheduleRule["daysOfMonth"] = $daysOfMonth
}
If ($PSBoundParameters.ContainsKey('interval')) {
$snapScheduleRule["interval"] = $interval
}
If ($PSBoundParameters.ContainsKey('isAutoDelete')) {
$snapScheduleRule["isAutoDelete"] = $isAutoDelete
}
If ($PSBoundParameters.ContainsKey('retentionTime')) {
$snapScheduleRule["retentionTime"] = $retentionTime
}
If ($PSBoundParameters.ContainsKey('accessType')) {
$snapScheduleRule["accessType"] = $accessType
}
$body["rules"] += $snapScheduleRule
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
If ($Sess.TestConnection()) {
##Building the URL
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $TypeName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
Write-Verbose "Request status code: $($request.StatusCode)"
If ($request.StatusCode -eq $StatusCode) {
#Formating the result. Converting it from JSON to a Powershell object
$results = ($request.content | ConvertFrom-Json).content
Write-Verbose "$Type with the ID $($results.id) has been created"
Get-UnitySnapSchedule -Session $Sess -ID $results.id
} # End If ($request.StatusCode -eq $StatusCode)
} # End If ($Sess.TestConnection())
} # End Foreach
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Remove-UnitySnap.ps1
|
Remove-UnitySnap.ps1
|
Function Remove-UnitySnap {
<#
.SYNOPSIS
Delete a snapshot.
.DESCRIPTION
Delete a snapshot.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
ID of the snapshot or snapshot Object. ID need to be surounded by quote like this '171798691854'.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running.
If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Remove-UnitySnap -ID '171798691854'
Delete the snapshot with ID '171798691854'
.EXAMPLE
Get-UnitySnap | Remove-UnitySnap
Delete all existing snapshots.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'snapshot ID or snapshot Object')]
[Object[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/snap/<id>'
$Type = 'snapshot'
$TypeName = 'UnitySnap'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
#Snap ID are normally integers. Convert it to strings
If (($i.GetType().Name) -Like "*Int*") {
$i = $i.ToString()
}
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = Get-UnitySnap -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnitySnap -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
if ($pscmdlet.ShouldProcess($Sess.Name,"Delete $Type $ObjectName")) {
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'DELETE'
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been deleted"
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnitySmtpServer.ps1
|
Get-UnitySmtpServer.ps1
|
Function Get-UnitySMTPServer {
<#
.SYNOPSIS
Information about the SMTP servers in the storage system.
.DESCRIPTION
Information about the SMTP servers in the storage system.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnitySMTPServer
Retrieve informations about all the SMTP servers.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'SMTP Server ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/smtpServer/instances' #URI
$TypeName = 'UnitySmtpServer'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnitySnap.ps1
|
Get-UnitySnap.ps1
|
Function Get-UnitySnap {
<#
.SYNOPSIS
Queries the EMC Unity array to retrieve informations about snapshots.
.DESCRIPTION
Queries the EMC Unity array to retrieve informations about snapshots.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnitySnap
Retrieve information about Snap
.EXAMPLE
Get-UnitySnap -Name 'SNAP01'
Retrieves information about snapshot named SNAP01
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Snap Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Snap ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/snap/instances' #URI
$TypeName = 'UnitySnap'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnityNasServer.ps1
|
New-UnityNasServer.ps1
|
Function New-UnityNASServer {
<#
.SYNOPSIS
Creates a NAS Server.
.DESCRIPTION
Create a NAS server. You can create a maximum of 24 NAS servers per system.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Name
Specifies the NAS server name.
NAS server names can contain alphanumeric characters, a single dash, and a single underscore.
Server names cannot contain spaces or begin or end with a dash.
You can create NAS server names in four parts that are separated by periods (example: aa.bb.cc.dd).
Names can contain up to 255 characters, but the first part of the name (before the first period) is limited to 15 characters.
.PARAMETER homeSP
Specifies the parent SP for the NAS server.
.PARAMETER Pool
Specifies the ID of the storage pool for the NAS server.
.PARAMETER isReplicationDestination
Replication destination settings for the NAS server.
When this option is set to yes, only mandatory parameters may be included.
All other optional parameters will be inherited from the source NAS server.
Valid values are $true or $false (default).
.PARAMETER UnixDirectoryService
Directory Service used for querying identity information for Unix (such as UIDs, GIDs, net groups). Valid values are:
- NIS
- LDAP
- None (Default)
.PARAMETER isMultiProtocolEnabled
Indicates whether multiprotocol sharing mode is enabled. Value is $true or $false (default).
.PARAMETER allowUnmappedUser
Use this flag to mandatorily disable access in case of any user mapping failure. Valide value are $true or $false (default).
.PARAMETER defaultUnixUser
Default Unix user name that grants file access in the multiprotocol sharing mode.
This user name is used when the corresponding Unix/Linux user name is not found by the mapping mechanism.
.PARAMETER defaultWindowsUser
Default Windows user name that grants file access in the multiprotocol sharing mode.
This user name is used when the corresponding Windows user name is not found by the mapping mechanism.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
New-UnityNasServer -Name 'NAS01' -Pool 'pool_1' -homeSP 'spa'
Create NAS server named 'NAS01' on the pool ID 'pool_1' and attached to the sp 'spa'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 1,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Name for the NAS server')]
#NasServer
[String[]]$Name,
[Parameter(Mandatory = $true,HelpMessage = 'Storage processor ID on which the NAS server will run')]
$homeSP,
[Parameter(Mandatory = $true,HelpMessage = 'A Storage pool ID that stores NAS server configuration information')]
[String]$Pool,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether the NAS server is a replication destination')]
[bool]$isReplicationDestination,
[Parameter(Mandatory = $false,HelpMessage = 'Directory Service used for quering identity information for Unix')]
[NasServerUnixDirectoryServiceEnum]$UnixDirectoryService,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether multiprotocol sharing mode is enabled')]
[bool]$isMultiProtocolEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Use this flag to mandatorily disable access in case of any user mapping failure')]
[bool]$allowUnmappedUser,
[Parameter(Mandatory = $false,HelpMessage = 'Default Unix user name used for granting access in case of Windows to Unix user mapping failure')]
[String]$defaultUnixUser,
[Parameter(Mandatory = $false,HelpMessage = 'Default Windows user name used for granting access in case of Unix to Windows user mapping failure. When empty, access in such case is denied')]
[String]$defaultWindowsUser
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/types/nasServer/instances'
$Type = 'NAS Server'
$StatusCode = 201
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
Foreach ($n in $Name) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
# Name parameter
$body["name"] = "$($n)"
# homeSP parameter
$body["homeSP"] = @{}
$homeSPParameters = @{}
$homeSPParameters["id"] = "$($homeSP)"
$body["homeSP"] = $homeSPParameters
# Pool parameter
$body["pool"] = @{}
$poolParameters = @{}
$poolParameters["id"] = "$($Pool)"
$body["pool"] = $poolParameters
If ($PSBoundParameters.ContainsKey('isReplicationDestination')) {
$body["isReplicationDestination"] = $isReplicationDestination
}
If ($PSBoundParameters.ContainsKey('UnixDirectoryService')) {
$body["currentUnixDirectoryService"] = $($UnixDirectoryService)
}
If ($PSBoundParameters.ContainsKey('isMultiProtocolEnabled')) {
$body["isMultiProtocolEnabled"] = $isMultiProtocolEnabled
}
If ($PSBoundParameters.ContainsKey('allowUnmappedUser')) {
$body["allowUnmappedUser"] = $allowUnmappedUser
}
If ($PSBoundParameters.ContainsKey('defaultUnixUser')) {
$body["defaultUnixUser"] = $defaultUnixUser
}
If ($PSBoundParameters.ContainsKey('defaultWindowsUser')) {
$body["defaultWindowsUser"] = $defaultWindowsUser
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
If ($Sess.TestConnection()) {
##Building the URL
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $Type $n")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
Write-Verbose "Request status code: $($request.StatusCode)"
If ($request.StatusCode -eq $StatusCode) {
#Formating the result. Converting it from JSON to a Powershell object
$results = ($request.content | ConvertFrom-Json).content
Write-Verbose "$Type with the ID $($results.id) has been created"
Get-UnityNASServer -Session $Sess -ID $results.id
} # End If ($request.StatusCode -eq $StatusCode)
} # End If ($Sess.TestConnection())
} # End Foreach
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityNasServer.ps1
|
Get-UnityNasServer.ps1
|
Function Get-UnityNASServer {
<#
.SYNOPSIS
View details about configured NAS servers.
.DESCRIPTION
View details about configured NAS servers. You can filter on ID or Name.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityNasServer
Retrieve information about all NAS Servers
.EXAMPLE
Get-UnityNasServer -Name 'NAS01'
Retrieves information about NAS server named NAS01
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'NAS Server Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'NAS Server ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/nasServer/instances' #URI
$TypeName = 'UnityNasServer'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Remove-UnityFileDnsServer.ps1
|
Remove-UnityFileDnsServer.ps1
|
Function Remove-UnityFileDNSServer {
<#
.SYNOPSIS
Delete a file DNS Server.
.DESCRIPTION
Delete a file DNS Server.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
File DNS ID or Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Remove-UnityFileDnsServer -ID 'dns_1'
Delete the file DNS server with ID 'dns_1'
.EXAMPLE
Get-UnityFileDnsServer | Remove-UnityFileDnsServer
Delete all the file DNS Servers
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'File DNS ID or Object')]
$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/fileDNSServer/<id>'
$Type = 'File DNS Server'
$TypeName = 'UnityFileDnsServer'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityFileDNSServer -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityFileDNSServer -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
if ($pscmdlet.ShouldProcess($Sess.Name,"Delete $Type $ObjectName")) {
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'DELETE'
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been deleted"
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnitySnap.ps1
|
Set-UnitySnap.ps1
|
Function Set-UnitySnap {
<#
.SYNOPSIS
Modifies snapshot parameters.
.DESCRIPTION
Modifies snapshot parameters.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
Snapshot ID or Object.
.PARAMETER Name
Snapshot name (Applies to block type storage resource snaps only. Filesystem snapshot names cannot be modified).
.PARAMETER Description
Snapshot description.
.PARAMETER isAutoDelete
Indicates whether the system will automatically delete the snapshot when the pool snapshot space or total pool space reaches an automatic deletion threshold.
.PARAMETER retentionDuration
How long (in seconds) to keep the snapshot (Can be specified only if auto delete is set to false).
.PARAMETER ioLimitParameters
The IO limit policy that is applied to this snapshot. This is only applicable to attached snapshots.
.PARAMETER copyName
Base name for the new snapshot copies or Name of the backup snapshot created before the restore/attach operation occurs.
.PARAMETER numCopies
Number of snapshot copies to make.
.PARAMETER copyStartNum
Starting number for the group of copies. This number gets appended to the name specified in the copyName argument to form the name of the first snapshot copy. The system increments the number for each new snapshot.
.PARAMETER copy
Copy a snapshot.
.PARAMETER restore
Restore the snapshot to the associated storage resource.
.PARAMETER refresh
Refresh the snapshot to the associated storage resource.
.PARAMETER attach
Attach the snapshot so hosts can access it. Attaching a snapshot makes the snapshot accessible to configured hosts for restoring files and data.
.PARAMETER detach
Detach the snapshot so hosts can no longer access it.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Set-UnitySnap -ID '171798691854' -Description 'Modified description'
Change the description of the snapshot with ID '171798691854'
.EXAMPLE
Set-UnitySnap -ID '171798691854' -Copy -numCopies 2
Copy 2 times the snapshot with ID '171798691854'
.EXAMPLE
Set-UnitySnap -ID '171798691854' -Restore
Restore the snapshot with ID '171798691854' to the associated storage resource.
.EXAMPLE
Set-UnitySnap -ID '171798691854' -Attach
Attach the snapshot with ID '171798691854' so hosts can access it.'
.EXAMPLE
Set-UnitySnap -ID '171798691854' -Detach
Detach the snapshot with ID '171798691854' so hosts can no longer access it.
.EXAMPLE
Set-UnitySnap -ID '171798691854' -Refresh
Refreshes snapshot with ID '171798691854' with the latest data from the parent LUN.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High',DefaultParameterSetName="Set")]
Param (
#Default Parameters
[Parameter(Mandatory = $false,ParameterSetName="Set",HelpMessage = 'EMC Unity Session')]
[Parameter(Mandatory = $false,ParameterSetName="Copy",HelpMessage = 'EMC Unity Session')]
[Parameter(Mandatory = $false,ParameterSetName="Restore",HelpMessage = 'EMC Unity Session')]
[Parameter(Mandatory = $false,ParameterSetName="Attach",HelpMessage = 'EMC Unity Session')]
[Parameter(Mandatory = $false,ParameterSetName="Detach",HelpMessage = 'EMC Unity Session')]
[Parameter(Mandatory = $false,ParameterSetName="Refresh",HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#ID
[Parameter(Mandatory = $true,Position = 0,ParameterSetName="Set",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Snapshot ID or Object.')]
[Parameter(Mandatory = $true,Position = 0,ParameterSetName="Copy",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Snapshot ID or Object.')]
[Parameter(Mandatory = $true,Position = 0,ParameterSetName="Restore",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Snapshot ID or Object.')]
[Parameter(Mandatory = $true,Position = 0,ParameterSetName="Attach",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Snapshot ID or Object.')]
[Parameter(Mandatory = $true,Position = 0,ParameterSetName="Detach",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Snapshot ID or Object.')]
[Parameter(Mandatory = $true,Position = 0,ParameterSetName="Refresh",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Snapshot ID or Object.')]
[String[]]$ID,
# Set
[Parameter(Mandatory = $false,ParameterSetName="Set",HelpMessage = 'Snapshot name (Applies to block type storage resource snaps only. Filesystem snapshot names cannot be modified).')]
[String[]]$name,
[Parameter(Mandatory = $false,ParameterSetName="Set",HelpMessage = 'Snapshot description.')]
[String]$Description,
[Parameter(Mandatory = $false,ParameterSetName="Set",HelpMessage = 'Auto delete policy for snapshot')]
[bool]$isAutoDelete,
[Parameter(Mandatory = $false,ParameterSetName="Set",HelpMessage = 'How long to keep the snapshot (Can be specified only if auto delete is set to false).')]
[uint64]$retentionDuration,
[Parameter(Mandatory = $false,ParameterSetName="Set",HelpMessage = 'The IO limit policy that is applied to this snapshot. This is only applicable to attached snapshots.')]
[String]$ioLimitParameters,
# Copy
[Parameter(Mandatory = $true,ParameterSetName="Copy",HelpMessage = 'Copy a snapshot.')]
[switch]$copy,
[Parameter(Mandatory = $false,ParameterSetName="Copy",HelpMessage = 'Number of snapshot copies to make.')]
[Uint32]$numCopies,
[Parameter(Mandatory = $false,ParameterSetName="Copy",HelpMessage = 'Starting number for the group of copies.')]
[Uint32]$copyStartNum,
# Restore
[Parameter(Mandatory = $true,ParameterSetName="Restore",HelpMessage = 'Restore the snapshot to the associated storage resource. ')]
[switch]$restore,
# Attach
[Parameter(Mandatory = $true,ParameterSetName="Attach",HelpMessage = 'Attach the snapshot so hosts can access it.')]
[switch]$attach,
# Detach
[Parameter(Mandatory = $true,ParameterSetName="Detach",HelpMessage = 'Detach the snapshot so hosts can no longer access it.')]
[switch]$detach,
# Refresh
[Parameter(Mandatory = $true,ParameterSetName="Refresh",HelpMessage = 'Refresh the snapshot data from the parent volume.')]
[switch]$refresh,
# Copy, Restore, Refresh & Attach
[Parameter(Mandatory = $false,ParameterSetName="Copy",HelpMessage = 'Base name for the new snapshot copies.')]
[Parameter(Mandatory = $false,ParameterSetName="Restore",HelpMessage = 'Name of the backup snapshot created before the restore operation occurs.')]
[Parameter(Mandatory = $false,ParameterSetName="Attach",HelpMessage = 'Name of the backup snapshot created before the attach operation occurs.')]
[Parameter(Mandatory = $false,ParameterSetName="Refresh",HelpMessage = 'Name of the backup snapshot created before the attach operation occurs.')]
[String]$copyName
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
Switch ($PsCmdlet.ParameterSetName) {
'Set' {
$URI = '/api/instances/snap/<id>/action/modify'
$StatusCode = 204
}
'Copy' {
$URI = '/api/instances/snap/<id>/action/copy'
$StatusCode = 200
}
'Restore' {
$URI = '/api/instances/snap/<id>/action/restore'
$StatusCode = 200
}
'Attach' {
$URI = '/api/instances/snap/<id>/action/attach'
$StatusCode = 200
}
'Detach' {
$URI = '/api/instances/snap/<id>/action/detach'
$StatusCode = 204
}
'Refresh' {
$URI = '/api/instances/snap/<id>/action/refresh'
$StatusCode = 200
}
}
$Type = 'snapshot'
$TypeName = 'UnitySnap'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
#Snap ID are normally integers. Convert it to strings
If (($i.GetType().Name) -Like "*Int*") {
$i = $i.ToString()
}
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnitySnap -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnitySnap -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
Switch ($PsCmdlet.ParameterSetName) {
'Set' {
If ($PSBoundParameters.ContainsKey('name')) {
$body["name"] = $name
}
If ($PSBoundParameters.ContainsKey('description')) {
$body["description"] = $description
}
If ($PSBoundParameters.ContainsKey('isAutoDelete')) {
$body["isAutoDelete"] = $isAutoDelete
}
If ($PSBoundParameters.ContainsKey('retentionDuration')) {
$body["retentionDuration"] = $retentionDuration
}
If ($PSBoundParameters.ContainsKey('ioLimitParameters')) {
$body["ioLimitParameters"] = @{}
$ioLimit = @{}
$ioLimit['id'] = $ioLimitParameters
$body["ioLimitParameters"] = $ioLimit
}
}
'Copy' {
If ($PSBoundParameters.ContainsKey('copyName')) {
$body["copyName"] = $copyName
}
If ($PSBoundParameters.ContainsKey('numCopies')) {
$body["numCopies"] = $numCopies
}
If ($PSBoundParameters.ContainsKey('copyStartNum')) {
$body["copyStartNum"] = $copyStartNum
}
}
'Restore' {
If ($PSBoundParameters.ContainsKey('copyName')) {
$body["copyName"] = $copyName
}
}
'Attach' {
If ($PSBoundParameters.ContainsKey('copyName')) {
$body["copyName"] = $copyName
}
}
'Refresh' {
If ($PSBoundParameters.ContainsKey('copyName')) {
$body["copyName"] = $copyName
}
}
'Detach' {}
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $ObjectName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnitySnap -Session $Sess -ID $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityFeature.ps1
|
Get-UnityFeature.ps1
|
Function Get-UnityFeature {
<#
.SYNOPSIS
Queries the EMC Unity array to retrieve informations about features.
.DESCRIPTION
Querries the EMC Unity array to retrieve informations about features.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityFeature
Retrieve information about all features
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Feature Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Feature ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/feature/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityFeature'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnityFileDNSServer.ps1
|
Set-UnityFileDNSServer.ps1
|
Function Set-UnityFileDnsServer {
<#
.SYNOPSIS
Modifies File DNS Server parameters.
.DESCRIPTION
Modifies File DNS Server parameters.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
File DNS Server ID or Object
.PARAMETER domain
DNS domain name
.PARAMETER addresses
The list of DNS server IP addresses
.PARAMETER replicationPolicy
Status of the LDAP list in the NAS server operating as a replication destination.
.EXAMPLE
Set-UnityFileDnsServer -ID 'dns_1' -ipAddress '192.168.0.1'
Change ip of the file DNS server with ID 'dns_1'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'File DNS Server ID or Object')]
$ID,
[Parameter(Mandatory = $false,HelpMessage = 'DNS domain name')]
[string]$domain,
[Parameter(Mandatory = $false,HelpMessage = 'The list of DNS server IP addresses')]
[String[]]$addresses,
[Parameter(Mandatory = $false,HelpMessage = 'Status of the LDAP list in the NAS server operating as a replication destination.')]
[ReplicationPolicyEnum]$replicationPolicy
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/fileDNSServer/<id>/action/modify'
$Type = 'File DNS Server'
$TypeName = 'UnityFileDnsServer'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityFileDnsServer -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityFileDnsServer -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
# Creation of the body hash
$body = @{}
#Addresses argument
$body['addresses'] = @()
Foreach ($Addresse in $Addresses) {
$body["addresses"] += $Addresse
}
If ($PSBoundParameters.ContainsKey('domain')) {
$body["domain"] = "$($domain)"
}
If ($PSBoundParameters.ContainsKey('replicationPolicy')) {
$body["replicationPolicy"] = $replicationPolicy
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $ObjectName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityFileDnsServer -Session $Sess -id $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnityMgmtInterface.ps1
|
Set-UnityMgmtInterface.ps1
|
Function Set-UnityMgmtInterface {
<#
.SYNOPSIS
Modify settings for an management interface.
.DESCRIPTION
Modify settings for an management interface.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
Management interface ID or Object.
.PARAMETER ipAddress
IPv4 or IPv6 address for the interface.
.PARAMETER netmask
IPv4 netmask for the interface, if the interface uses an IPv4 address.
.PARAMETER v6PrefixLength
Prefix length in bits for IPv6 address.
.PARAMETER gateway
IPv4 or IPv6 gateway address for the interface.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Set-UnityMgmtInterface -ID 'mgmt_ipv4' -gateway '192.168.0.254'
Change gateway of the management interface with ID 'mgmt_ipv4'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Management interface ID or Object')]
[String[]]$ID,
[Parameter(Mandatory = $false,Position = 1,HelpMessage = 'IPv4 or IPv6 address for the interface.')]
[string]$ipAddress,
[Parameter(Mandatory = $false,HelpMessage = 'IPv4 netmask for the interface, if the interface uses an IPv4 address.')]
[string]$netmask,
[Parameter(Mandatory = $false,HelpMessage = 'Prefix length in bits for IPv6 address.')]
[String[]]$v6PrefixLength,
[Parameter(Mandatory = $false,Position = 1,HelpMessage = 'IPv4 or IPv6 gateway address for the interface.')]
[string]$gateway
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/mgmtInterface/<id>/action/modify'
$Type = 'Management Interface'
$TypeName = 'UnityMgmtInterface'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Foreach ($i in $ID) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityMgmtInterface -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityMgmtInterface -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
# ipAddress argument
If ($PSBoundParameters.ContainsKey('ipAddress')) {
$body["ipAddress"] = "$ipAddress"
}
If ($PSBoundParameters.ContainsKey('netmask')) {
$body["netmask"] = "$netmask"
}
If ($PSBoundParameters.ContainsKey('v6PrefixLength')) {
$body["v6PrefixLength"] = "$v6PrefixLength"
}
If ($PSBoundParameters.ContainsKey('gateway')) {
$body["gateway"] = "$gateway"
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $ObjectName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityMgmtInterface -Session $Sess -id $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityFastCache.ps1
|
Get-UnityFastCache.ps1
|
Function Get-UnityFastCache {
<#
.SYNOPSIS
View the FAST Cache parameters.
.DESCRIPTION
View the FAST Cache parameters.
Physical deployments only.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityFastCache
Retrieve information about Fast Cache.
.EXAMPLE
Get-UnityFastCache -Name '200 GB SAS Flash 2'
Retrieves information about disk groups names '200 GB SAS Flash 2'
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Fast Cache ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/fastCache/instances' #URI
$TypeName = 'UnityFastCache'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
# Test if the Unity is a virtual appliance
If ($Sess.isUnityVSA()) {
Write-Warning -Message "This functionnality is not supported on the Unity VSA ($($Sess.Name))"
} else {
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End If ($Sess.isUnityVSA())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityDiskGroup.ps1
|
Get-UnityDiskGroup.ps1
|
Function Get-UnityDiskGroup {
<#
.SYNOPSIS
View details about disk groups on the system.
.DESCRIPTION
View details about disk groups on the system.
Physical deployment only.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityDiskGroup
Retrieve information about all disk groups
.EXAMPLE
Get-UnityDiskGroup -Name '200 GB SAS Flash 2'
Retrieves information about disk groups names '200 GB SAS Flash 2'
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Disk group Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Disk group ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/diskGroup/instances' #URI
$TypeName = 'UnityDiskGroup'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
# Test if the Unity is a virtual appliance
If ($Sess.isUnityVSA()) {
Write-Warning -Message "This functionnality is not supported on the Unity VSA ($($Sess.Name))"
} else {
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End If ($Sess.isUnityVSA())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityMetricValue.ps1
|
Get-UnityMetricValue.ps1
|
Function Get-UnityMetricValue {
<#
.SYNOPSIS
Historical values for requested metrics.
.DESCRIPTION
Historical values for requested metrics.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Path
Stat path for the metric. A stat path identifies the metric's location in the stats namespace.
.PARAMETER Count
Specifies the number of samples to display.
.EXAMPLE
Get-UnityMetricValue -Path 'sp.*.cpu.summary.utilization'
Retrieves information about metrics who's path is 'sp.*.cpu.summary.utilization'
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Stat path for the metric')]
[Object[]]$Path,
[Parameter(Mandatory = $false,HelpMessage = 'Specifies the number of samples to display')]
[Int64]$Count = 20
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$ResultCollection = @()
$URI = '/api/types/metricValue/instances' #URI
$TypeName = 'UnityMetricValue'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($P in $Path) {
Write-Verbose "Processing path: $P"
# Determine input and convert to object if necessary
Write-Verbose "Input object type is $($P.GetType().Name)"
Switch ($P.GetType().Name)
{
"UnityMetric" {$ObjectPath = $P.Path}
"String" {$ObjectPath = $P}
}
Write-Verbose "Object path: $ObjectPath"
$PathFilter = "filter=path EQ `"$ObjectPath`""
$Page = '&page=1'
$Results = @()
While (($Results.count) -le $Count) {
#Building the URL from Object Type.
$URL = 'https://'+ $sess.Server + $URI +'?'+ $PathFilter + $Page
Write-Verbose "URL: $URL"
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'GET'
#Formating the result. Converting it from JSON to a Powershell object
$Results += ($request.content | ConvertFrom-Json).entries.content
$Links = ($request.content | ConvertFrom-Json).links
$Page = ($links | Where-Object {$_.rel -eq 'next'}).href
}
#Building the result collection (Add ressource type)
If ($Results) {
$Results = $Results | Select-Object -First $Count
$ResultCollection = ConvertTo-Hashtable -Data $Results
Foreach ($Result in $ResultCollection) {
# Instantiate object
$Object = New-Object -TypeName $TypeName -Property $Result
# Output results
$Object
} # End Foreach ($Result in $ResultCollection)
} # End If ($Results)
} # End Foreach ($P in $Path)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnityHost.ps1
|
Set-UnityHost.ps1
|
Function Set-UnityHost {
<#
.SYNOPSIS
Modify a host configuration.
.DESCRIPTION
Modify a host configuration.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running.
If the value is $false, the cmdlet runs without asking for Host confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.PARAMETER ID
Host ID or Object.
.EXAMPLE
Set-UnityHost -ID 'Host_21' -Name HOST01
Change the name of the host with ID 'Host_21'
.EXAMPLE
Get-UnityHost -ID 'Host_21' | Set-UnityHost -Name HOST01
Change the name of the host with ID 'Host_21'. The Host's information are provided by the Get-UnityHost through the pipeline.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Host ID or Object')]
[String[]]$ID,
#Host Name. (Applies to manually-created hosts only.)
[Parameter(Mandatory = $false,Position = 1,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Host Name. (Applies to manually-created hosts only.)')]
[String]$Name,
#Host Description
[Parameter(Mandatory = $false,HelpMessage = 'Host Description')]
[String]$Description,
#Operating system running on the host. (Applies to manually-created hosts only.)
[Parameter(Mandatory = $false,HelpMessage = 'Operating system running on the host. (Applies to manually-created hosts only.)')]
[string]$osType
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/host/<id>/action/modify'
$Type = 'Host'
$TypeName = 'UnityHost'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityHost -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityHost -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
# Name parameter
If ($PSBoundParameters.ContainsKey('name')) {
$body["name"] = $name
}
If ($PSBoundParameters.ContainsKey('description')) {
$body["description"] = $description
}
If ($PSBoundParameters.ContainsKey('osType')) {
$body["osType"] = $osType
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $ObjectName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityHost -Session $Sess -id $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnityCIFSShare.ps1
|
New-UnityCIFSShare.ps1
|
Function New-UnityCIFSShare {
<#
.SYNOPSIS
Creates CIFS share.
.DESCRIPTION
Creates CIFS share.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Filesystem
Specify Filesystem ID
.PARAMETER Path
Local path to a location within a file system.
.PARAMETER Name
Name of the CIFS share unique to NAS server
.PARAMETER cifsServer
CIFS server ID to use for CIFS share creation, as defined by the cifsServer type
.PARAMETER description
CIFS share description
.PARAMETER isReadOnly
Indicates whether the CIFS share is read-only
.PARAMETER isEncryptionEnabled
Indicates whether CIFS encryption for Server Message Block (SMB) 3.0 is enabled for the CIFS share
.PARAMETER isContinuousAvailabilityEnabled
Indicates whether continuous availability for SMB 3.0 is enabled for the CIFS share
.PARAMETER isABEEnabled
Enumerate file with read access and directories with list access in folder listings
.PARAMETER isBranchCacheEnabled
Branch Cache optimizes traffic between the NAS server and Branch Office Servers
.PARAMETER offlineAvailability
Offline Files store a version of the shared resources on the client computer in the file system cache, a reserved portion of disk space, which the client computer can access even when it is disconnected from the network
.PARAMETER umask
The default UNIX umask for new files created on the share
.EXAMPLE
New-UnityCIFSShare -Filesystem 'fs_1' -Name 'SHARE01' -path '/' -cifsServer 'cifs_1'
Create a new CIFS Share named 'SHARE01'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#SetFilesystem
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Filesystem ID')]
[String[]]$Filesystem,
#cifsShareCreate
[Parameter(Mandatory = $true,HelpMessage = 'Local path to a location within a file system')]
[String]$Path,
[Parameter(Mandatory = $true,HelpMessage = 'Name of the CIFS share unique to NAS server')]
[String]$Name,
[Parameter(Mandatory = $true,HelpMessage = 'CIFS server ID to use for CIFS share creation, as defined by the cifsServer type')]
[String]$cifsServer,
#$cifsShareParameters
[Parameter(Mandatory = $false,HelpMessage = 'CIFS share description')]
[String]$description,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether the CIFS share is read-only')]
[bool]$isReadOnly,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether CIFS encryption for Server Message Block (SMB) 3.0 is enabled for the CIFS share')]
[bool]$isEncryptionEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether continuous availability for SMB 3.0 is enabled for the CIFS share')]
[bool]$isContinuousAvailabilityEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Enumerate file with read access and directories with list access in folder listings')]
[bool]$isABEEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Branch Cache optimizes traffic between the NAS server and Branch Office Servers')]
[bool]$isBranchCacheEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Offline Files store a version of the shared resources on the client computer in the file system cache, a reserved portion of disk space, which the client computer can access even when it is disconnected from the network')]
[CifsShareOfflineAvailabilityEnum]$offlineAvailability,
[Parameter(Mandatory = $false,HelpMessage = 'The default UNIX umask for new files created on the share')]
[String]$umask
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/instances/storageResource/<id>/action/modifyFilesystem'
$Type = 'Share CIFS'
$TypeName = 'UnityFilesystem'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($fs in $Filesystem) {
# Determine input and convert to UnityFilesystem object
Switch ($fs.GetType().Name)
{
"String" {
$Object = get-UnityFilesystem -Session $Sess -ID $fs
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $fs.id
If ($Object = Get-UnityFilesystem -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
#### REQUEST BODY
$UnityStorageRessource = Get-UnitystorageResource -Session $sess | ? {($_.Name -like $ObjectName) -and ($_.filesystem.id -like $ObjectID)}
# Creation of the body hash
$body = @{}
$body["cifsShareCreate"] = @()
$cifsShareCreateParameters = @{}
# path
$cifsShareCreateParameters["path"] = "$($path)"
# name
$cifsShareCreateParameters["name"] = "$($name)"
# cifsServer
$cifsShareCreateParameters["cifsServer"] = @{}
$cifsServerParameters = @{}
$cifsServerParameters['id'] = "$($cifsServer)"
$cifsShareCreateParameters["cifsServer"] = $cifsServerParameters
#$cifsShareParameters
If (($PSBoundParameters.ContainsKey('description')) -or ($PSBoundParameters.ContainsKey('isReadOnly')) -or ($PSBoundParameters.ContainsKey('isEncryptionEnabled')) -or ($PSBoundParameters.ContainsKey('isContinuousAvailabilityEnabled')) -or ($PSBoundParameters.ContainsKey('isABEEnabled')) -or ($PSBoundParameters.ContainsKey('isBranchCacheEnabled')) -or ($PSBoundParameters.ContainsKey('offlineAvailability')) -or ($PSBoundParameters.ContainsKey('umask'))){
$cifsShareCreateParameters["cifsShareParameters"] = @{}
$cifsShareParameters = @{}
If ($PSBoundParameters.ContainsKey('description')) {
$cifsShareParameters["description"] = "$($description)"
}
If ($PSBoundParameters.ContainsKey('isReadOnly')) {
$cifsShareParameters["isReadOnly"] = $isReadOnly
}
If ($PSBoundParameters.ContainsKey('isEncryptionEnabled')) {
$cifsShareParameters["isEncryptionEnabled"] = $isEncryptionEnabled
}
If ($PSBoundParameters.ContainsKey('isContinuousAvailabilityEnabled')) {
$cifsShareParameters["isContinuousAvailabilityEnabled"] = $isContinuousAvailabilityEnabled
}
If ($PSBoundParameters.ContainsKey('isABEEnabled')) {
$cifsShareParameters["isABEEnabled"] = $isABEEnabled
}
If ($PSBoundParameters.ContainsKey('isBranchCacheEnabled')) {
$cifsShareParameters["isBranchCacheEnabled"] = $isBranchCacheEnabled
}
If ($PSBoundParameters.ContainsKey('offlineAvailability')) {
$cifsShareParameters["offlineAvailability"] = "$($offlineAvailability)"
}
If ($PSBoundParameters.ContainsKey('umask')) {
$cifsShareParameters["umask"] = "$($umask)"
}
$cifsShareCreateParameters["cifsShareParameters"] = $cifsShareParameters
}
$body["cifsShareCreate"] += $cifsShareCreateParameters
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$URI = $URI -replace '<id>',$UnityStorageRessource.id
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $Type $name")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityCIFSShare -Session $Sess -Name $name
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($fs in $Filesystem)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Remove-UnityFileInterface.ps1
|
Remove-UnityFileInterface.ps1
|
Function Remove-UnityFileInterface {
<#
.SYNOPSIS
Delete a file interface.
.DESCRIPTION
Delete a Nas Server.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
File Interface ID or Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Remove-UnityFileInterface -ID 'if_1'
Delete the file interface with ID 'if_1'
.EXAMPLE
Get-UnityFileInterface -Name 'if_1' | Remove-UnityFileInterface
Delete the file interface with ID 'if_1'. The file interface informations are provided by the Get-UnityFileInterface through the pipeline.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'File interface ID or Object')]
$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/fileInterface/<id>'
$Type = 'File Interface'
$TypeName = 'UnityFileInterface'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityFileInterface -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityFileInterface -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
if ($pscmdlet.ShouldProcess($Sess.Name,"Delete $Type $ObjectName")) {
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'DELETE'
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been deleted"
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnityUser.ps1
|
Set-UnityUser.ps1
|
Function Set-UnityUser {
<#
.SYNOPSIS
Modifies local user parameters.
.DESCRIPTION
Modifies local user parameters.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running.
If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.PARAMETER ID
User ID or Object.
.PARAMETER role
User role. Might be:
- administrator
- storageadmin
- vmadmin
- operator
.PARAMETER newPassword
New password for the user
.PARAMETER oldPassword
Initial password for the user.
.EXAMPLE
Set-UnityUser -Name 'User' -Role 'operator'
Gives the role 'operator' to the user 'User'
.EXAMPLE
Get-UnityUSer -Name 'User' | Set-UnityUser -Role 'operator'
Gives the role 'operator' to the user 'User'. The user's information are provided by the Get-UnityUser through the pipeline.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'User ID or Object')]
[String[]]$ID,
[Parameter(Mandatory = $false,HelpMessage = 'User role. It mights be administrator, storageadmin, vmadmin or operator')]
[ValidateSet('administrator', 'storageadmin', 'vmadmin', 'operator')]
[String]$Role,
[Parameter(Mandatory = $false,HelpMessage = 'User Password')]
[String]$newPassword,
[Parameter(Mandatory = $false,HelpMessage = 'User Password')]
[String]$oldPassword
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/user/<id>/action/modify'
$Type = 'User'
$TypeName = 'UnityUser'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityUser -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityUser -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
# Role parameter
$body["id"] = "$($ObjectID)"
# role parameter
If ($Role) {
$body["role"] = "$($Role)"
}
# oldPassword parameter
If ($password -and $oldPassword) {
$body["oldPassword"] = "$($oldPassword)"
$body["password"] = "$($newPassword)"
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $ObjectName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityUser -Session $Sess -id $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Disable-UnityFastCache.ps1
|
Disable-UnityFastCache.ps1
|
Function Disable-UnityFastCache {
<#
.SYNOPSIS
Disable FAST Cache.
.DESCRIPTION
Disable FAST Cache.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.EXAMPLE
Disable-UnityFastCache
Disable FAST Cache.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true})
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
#Building the URI
$URI = 'https://'+$sess.Server+'/api/instances/fastCache/0/action/disable?timeout=0' #run async
Write-Verbose "URI: $URI"
#Sending the request
If ($pscmdlet.ShouldProcess($($Sess.Server),"Disable Fast Cache")) {
$request = Send-UnityRequest -uri $URI -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq '202') {
Write-Host "Fast Cache is currently disabling"
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Connect-Unity.ps1
|
Connect-Unity.ps1
|
Function Connect-Unity {
<#
.SYNOPSIS
Connects to an EMC Unity Array
.DESCRIPTION
Connects to an EMC Unity Array. This cmdlet starts a new session with an EMC Unity Array using the specified parameters.
When you attempt to connect to an array, the array checks for valid certificates. To avoid this use the -TrusAllCerts param.
You can have more than one connection to the same array. To disconnect from an array, you need to close all active connections to this server using the Disconnect-Unity cmdlet.
Every new connection is stored in the $global:DefaultUnitySession array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Server
IP or FQDN of the Unity array.
.PARAMETER Username
Specifies the username.
.PARAMETER Password
Specifies the password. It as to be a powershell's secure string.
.PARAMETER Credentials
Credentials object of type [System.Management.Automation.PSCredential]
.PARAMETER TrustAllCerts
Specifies if
.EXAMPLE
Connect-Unity -Server 192.168.0.1
Connects to the array with the IP 192.168.0.1
.EXAMPLE
Connect-Unity -Server 192.168.0.1 -TrustAllCerts $false
Connects to the array with the IP 192.168.0.1 and don't accept unknown certificates.
.EXAMPLE
Connect-Unity -Server 192.168.0.1,192.168.0.2
Connects to the arrays with the IP 192.168.0.1 and 192.168.0.2. The same user and password is used.
.EXAMPLE
$IP = '192.168.0.1'
$Username = 'admin'
$Password = 'Password123#'
$Secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($Username,$secpasswd)
Connect-Unity -Server $IP -Credentials $Credentials
Connects to the arrays with the IP 192.168.0.1 and using powershell credentials
#>
[CmdletBinding(DefaultParameterSetName="ByServer")]
Param(
[Parameter(Mandatory = $true,Position = 0,ParameterSetName="ByServer",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'EMC Unity FQDN or IP address')]
[String[]]$Server,
[Parameter(Mandatory = $true,ParameterSetName="BySession",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'EMC Unity Session object')]
$Session,
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity username')]
[String]$Username,
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity password')]
[SecureString]$Password,
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity credentials')]
[PSCredential]$Credentials,
[Parameter(Mandatory = $false,HelpMessage = 'Trust all certs ?')]
[Bool]$TrustAllCerts = $True
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
if ($TrustAllCerts) {
Unblock-UnityCerts
}
}
Process {
If ($PsCmdlet.ParameterSetName -eq 'BySession') {
Write-Verbose -Message "Disconnect or delete previous session"
Disconnect-Unity -Session $Session -Confirm:$False
Write-Verbose -Message "Server: $($Session.Server)"
$Server = $Session.Server
}
Write-Verbose -Message 'Validating that login details were passed into username/password or credentials'
if ($Password -eq $null -and $Credentials -eq $null)
{
Write-Verbose -Message 'Missing username, password, or credentials.'
$Credentials = Get-Credential -Message 'Please enter administrative credentials for your EMC Unity Array'
}
if ($Credentials -eq $null)
{
Try {
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password
}
Catch {
throw
}
}
#Encoding username and password for HTTP Basic authentication
$EncodedAuthorization = [System.Text.Encoding]::UTF8.GetBytes($Credentials.username + ':' + $Credentials.GetNetworkCredential().Password)
$EncodedPassword = [System.Convert]::ToBase64String($EncodedAuthorization)
foreach ($srv in $Server) {
#Initializing Cookies Container
$Cookies = New-Object -TypeName System.Net.CookieContainer
$result = Get-UnityAuth -Server $srv -EncodedPassword $EncodedPassword -Cookies $Cookies
#Building the UnitySession Object
$Sess = New-Object -TypeName UnitySession
$Sess.IsConnected = $true
$Sess.Server = $srv
$Sess.Headers = $result['Headers']
$Sess.Cookies = $result['Cookies']
$Sess.SessionId = ([guid]::NewGuid())
$Sess.User = $Credentials.username
#Initialazing Websession variable
$Websession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
#Add session's cookies to Websession
Foreach ($cookie in $sess.Cookies) {
Write-Verbose "Add cookie: $($cookie.Name) to WebSession"
$Websession.Cookies.Add($cookie);
}
$Sess.Websession = $Websession
# Get types definitions from API
$Types = Get-UnityItem -URI '/api/types' -Session $Sess
$Sess.Types = $Types.entries.content | where-object {$_.name -notlike '*Enum'}
# Get informations about the array
$System = Get-UnitySystem -Session $Sess
$BasicSystemInfo = Get-UnityBasicSystemInfo -Session $Sess
$Sess.Name = $System.Name
$Sess.Model = $System.model
$Sess.SerialNumber = $System.SerialNumber
$Sess.ApiVersion = $BasicSystemInfo.ApiVersion
$Sess.SoftwareVersion = $BasicSystemInfo.SoftwareVersion
#Add the UnitySession Object to the $global:DefaultUnitySession array
$global:DefaultUnitySession += $Sess
#Return the new session
Write-Output $Sess
}
}
End {
## update the Windows PowerShell titlebar with a bit of info about the Unity array(s) to which the PowerShell session is connected
Update-TitleBarForUnityConnection
}
}
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Remove-UnityCIFSShare.ps1
|
Remove-UnityCIFSShare.ps1
|
Function Remove-UnityCIFSShare {
<#
.SYNOPSIS
Deletes CIFS share.
.DESCRIPTION
Deletes CIFS share.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
CIFS Share ID or Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Remove-UnityCIFSShare -ID 'SMBShare_1'
Delete the CIFS share with id 'SMBShare_1'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#cifsShareDelete
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'ID of the CIFS share')]
$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/storageResource/<id>/action/modifyFilesystem'
$Type = 'Share CIFS'
$TypeName = 'UnityCIFSShare'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityCIFSShare -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityCIFSShare -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
$UnityStorageResource = Get-UnitystorageResource -Session $sess | Where-Object {($_.filesystem.id -like $Object.filesystem.id)}
#### REQUEST BODY
# Creation of the body hash
$body = @{}
$body["cifsShareDelete"] = @()
$cifsShareDeleteParameters = @{}
$cifsShareDeleteParameters["cifsShare"] = @{}
$cifsShareParameters = @{}
$cifsShareParameters['id'] = $ObjectID
$cifsShareDeleteParameters["cifsShare"] = $cifsShareParameters
$body["cifsShareDelete"] += $cifsShareDeleteParameters
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$UnityStorageResource.id
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
if ($pscmdlet.ShouldProcess($Sess.Name,"Delete $Type $ObjectName")) {
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been deleted"
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityMgmtInterface.ps1
|
Get-UnityMgmtInterface.ps1
|
Function Get-UnityMgmtInterface {
<#
.SYNOPSIS
Information about management interfaces in the storage system.
.DESCRIPTION
Information about management interfaces in the storage system.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityMgmtInterface
Retrieve informations about all the management interface.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Mgmt interface ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/mgmtInterface/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityMgmtInterface'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Remove-UnitySMTPServer.ps1
|
Remove-UnitySMTPServer.ps1
|
Function Remove-UnitySMTPServer {
<#
.SYNOPSIS
Delete SMTP Server.
.DESCRIPTION
Delete SMTP Server.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
Management interface ID or Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running.
If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Remove-UnitySMTPServer -ID 'default'
Delete the SMTP server with ID 'default'
.EXAMPLE
Get-UnitySMTPServer -Name 'default' | Remove-UnitySMTPServer
Delete the SMTP server with ID 'default'. SMTP server informations are provided by the Get-UnitySMTPServer through the pipeline.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'SMTP Server ID or Object')]
$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/smtpServer/<id>'
$Type = 'SMTP Server'
$TypeName = 'UnitySMTPServer'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnitySMTPServer -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnitySMTPServer -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
if ($pscmdlet.ShouldProcess($Sess.Name,"Delete $Type $ObjectName")) {
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'DELETE'
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been deleted"
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Remove-UnityFilesystem.ps1
|
Remove-UnityFilesystem.ps1
|
Function Remove-UnityFilesystem {
<#
.SYNOPSIS
Delete a filesystem.
.DESCRIPTION
Delete a filesystem.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
Filesystem ID or Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Remove-UnityFilesystem -ID 'fs_1'
Delete the filesystem named 'fs_1'
.EXAMPLE
Get-UnityFilesystem -Name 'FS01' | Remove-UnityFilesystem
Delete the filesystem named 'FS01'. The filesystem's informations are provided by the Get-UnityFilesystem through the pipeline.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Filesystem ID or Object.')]
$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/storageResource/<id>'
$Type = 'Filesystem'
$TypeName = 'UnityFilesystem'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityFilesystem -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityFilesystem -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
$UnityStorageResource = Get-UnitystorageResource -Session $sess | ? {($_.Name -like $ObjectName) -and ($_.filesystem.id -like $ObjectID)}
#Building the URL
$FinalURI = $URI -replace '<id>',$UnityStorageResource.id
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
if ($pscmdlet.ShouldProcess($Sess.Name,"Delete $Type $ObjectName")) {
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'DELETE'
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "Filesystem with ID: $filesystemID has been deleted"
}
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Test-UnityEmailAlert.ps1
|
Test-UnityEmailAlert.ps1
|
Function Test-UnityEmailAlert {
<#
.SYNOPSIS
Test email alert notification by sending a test alert to all configured email destinations.
.DESCRIPTION
Test email alert notification by sending a test alert to all configured email destinations.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
ID or Object of a Alert Config..
.EXAMPLE
Test-UnityEmailAlert
Test email alert notification by sending a test alert to all configured email destinations.
#>
[CmdletBinding(DefaultParameterSetName="Refresh")]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'ID or Object of Alert Config')]
[String[]]$ID = '0'
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/alertConfig/<id>/action/testEmailAlert'
$Type = 'Alert'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityAlertConfig -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityAlertConfig -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST'
If ($request.StatusCode -eq $StatusCode) {
Write-Host "$Type send to $($Object.destinationEmails)"
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityMetric.ps1
|
Get-UnityMetric.ps1
|
Function Get-UnityMetric {
<#
.SYNOPSIS
Queries the EMC Unity array to retrieve informations about metrics.
.DESCRIPTION
Queries the EMC Unity array to retrieve informations about metrics.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityMetric
Retrieve information about all metrics
.EXAMPLE
Get-UnityMetric -Name 'Read IO time'
Retrieves information about metrics named 'Read IO time'
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Pool Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Pool ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/metric/instances' #URI
$TypeName = 'UnityMetric'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityFilesystem.ps1
|
Get-UnityFilesystem.ps1
|
Function Get-UnityFilesystem {
<#
.SYNOPSIS
Queries the EMC Unity array to retrieve informations about filesystems.
.DESCRIPTION
Querries the EMC Unity array to retrieve informations about filesystems.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityFilesystem
Retrieve information about filesystem
.EXAMPLE
Get-UnityFilesystem -Name 'FS01'
Retrieves information about filesystem named FS01
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Filesystem Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Filesystem ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/filesystem/instances' #URI
$TypeName = 'UnityFilesystem'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityFileDnsServer.ps1
|
Get-UnityFileDnsServer.ps1
|
Function Get-UnityFileDNSServer {
<#
.SYNOPSIS
Information about File DNS Servers.
.DESCRIPTION
Information about File DNS Servers.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityFileDnsServer
Retrieve informations about all file dns servers with an active session.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'File DNS Server ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/fileDNSServer/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityFileDnsServer'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityUser.ps1
|
Get-UnityUser.ps1
|
Function Get-UnityUser {
<#
.SYNOPSIS
Information about local users, including their roles, and how they are authenticated.
.DESCRIPTION
Information about local users, including their roles, and how they are authenticated.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityUser
Retrieve informations about all the local users
.EXAMPLE
Get-UnityUser -Name 'administrator'
Retrieves informations about the local user named 'administrator'
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'User Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'User ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/user/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityUser'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Update-UnityvCenter.ps1
|
Update-UnityvCenter.ps1
|
Function Update-UnityvCenter {
<#
.SYNOPSIS
Refresh vCenter hosts.
.DESCRIPTION
Refresh vCenter hosts.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
ID or Object of a vCenter server
.PARAMETER Refresh
'Refresh all the hosts managed by the host container.
.PARAMETER RefreshAll
Refresh all known vCenters and ESX servers.
.EXAMPLE
Update-UnityvCenter -ID '' -Refresh
Refresh all the hosts managed by this vCenter.
#>
[CmdletBinding(DefaultParameterSetName="Refresh")]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#vCenter
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'ID or Object of a vCenter server')]
[String[]]$ID,
[Parameter(Mandatory = $true,ParameterSetName="Refresh",HelpMessage = 'Refresh all the hosts managed by the host container.')]
[switch]$Refresh,
[Parameter(Mandatory = $true,ParameterSetName="RefreshAll",HelpMessage = 'Refresh all known vCenters and ESX servers.')]
[Switch]$RefreshAll
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/storageResource/<id>/action/modifyLun'
$Type = 'vCenter'
$TypeName = 'UnityvCenterServer'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityvCenter -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityvCenter -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
# Creation of the body hash
$body = @{}
# serviceType parameter
$body["doRescan"] = $True
#Building the URI
Switch ($PsCmdlet.ParameterSetName) {
'Refresh' {
$URI = 'https://'+$sess.Server+'/api/instances/hostContainer/'+$ObjectID+'/action/refresh'
}
'RefreshAll' {
$URI = 'https://'+$sess.Server+'/api/types/hostContainer/action/refreshAll'
}
}
Write-Verbose "URI: $URI"
#Sending the request
$request = Send-UnityRequest -uri $URI -Session $Sess -Method 'POST' -Body $Body
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been refreshed"
Get-UnityvCenter -Session $Sess -ID $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Remove-UnityAlert.ps1
|
Remove-UnityAlert.ps1
|
Function Remove-UnityAlert {
<#
.SYNOPSIS
Delete alert.
.DESCRIPTION
Delete alert.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
Alert ID or Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Remove-UnityAlert -ID 'alert_28'
Delete the Alert with ID 'alert_28'
.EXAMPLE
Get-UnityAlert -ID 'alert_28' | Remove-UnityAlert
Delete the Alert with ID 'alert_28'. Alert informations are provided by the Get-UnityAlert through the pipeline.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'ID or Object')]
$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/alert/<id>'
$Type = 'Alert'
$TypeName = 'UnityAlert'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityAlert -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityAlert -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
} # End Switch
If ($ObjectID) {
#Building the URL
$FinalURI = $URI -replace '<id>',$ObjectID
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
if ($pscmdlet.ShouldProcess($Sess.Name,"Delete $Type $($ObjectName)")) {
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'DELETE'
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been deleted"
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnityNFSServer.ps1
|
New-UnityNFSServer.ps1
|
Function New-UnityNFSServer {
<#
.SYNOPSIS
Create a new NFS Server.
.DESCRIPTION
Create a new NFS Server.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
New-UnityNFSServer -nasServer 'nas_15' -hostName 'NFS01'
Create a new NFS Server.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#ID of the NAS server associated with the NFS server.
[Parameter(Mandatory = $true,HelpMessage = 'ID of the NAS server associated with the NFS server.')]
[string]$nasServer,
#Host name of the NFS server. If host name is not specified then SMB server name or NAS server name will be used to auto generate the host name.
[Parameter(Mandatory = $false,HelpMessage = 'Host name of the NFS server. If host name is not specified then SMB server name or NAS server name will be used to auto generate the host name.')]
[string]$hostName,
#Indicates whether the NFSv4 is enabled on the NAS server specified in the nasServer attribute.
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether the NFSv4 is enabled on the NAS server specified in the nasServer attribute.')]
[bool]$nfsv4Enabled,
#Indicates whether the secure NFS is enabled.
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether the secure NFS is enabled.')]
[bool]$isSecureEnabled,
#Type of Kerberos Domain Controller used for secure NFS service.
[Parameter(Mandatory = $false,HelpMessage = 'Type of Kerberos Domain Controller used for secure NFS service.')]
[KdcTypeEnum]$kdcType,
#Kerberos Domain Controller administrator's name.
[Parameter(Mandatory = $false,HelpMessage = 'Kerberos Domain Controller administrator s name.')]
[string]$kdcUsername,
#Kerberos Domain Controller administrator's password.
[Parameter(Mandatory = $false,HelpMessage = 'Kerberos Domain Controller administrator s password.')]
[string]$kdcPassword,
#Support for more than 16 Unix groups.
[Parameter(Mandatory = $false,HelpMessage = 'Support for more than 16 Unix groups.')]
[bool]$isExtendedCredentialsEnabled,
#Credential cache refresh timeout. Resolution is in minutes.
#Default value is 15 minutes.
[Parameter(Mandatory = $false,HelpMessage = 'Credential cache refresh timeout. Resolution is in minutes.')]
[DateTime]$credentialsCacheTTL
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/types/nfsServer/instances'
$Item = 'NFS Server'
$StatusCode = 201
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
#### REQUEST BODY
#Creation of the body hash
$body = @{}
#Body arguments
$body["nasServer"] = @{}
$nasServerParameters = @{}
$nasServerParameters["id"] = $nasServer
$body["nasServer"] = $nasServerParameters
If ($PSBoundParameters.ContainsKey('hostName')) {
$body["hostName"] = "$hostName"
}
If ($PSBoundParameters.ContainsKey('isReplicationDestination')) {
$body["isReplicationDestination"] = $isReplicationDestination
}
If ($PSBoundParameters.ContainsKey('nfsv4Enabled')) {
$body["nfsv4Enabled"] = $nfsv4Enabled
}
If ($PSBoundParameters.ContainsKey('isSecureEnabled')) {
$body["isSecureEnabled"] = $isSecureEnabled
}
If ($PSBoundParameters.ContainsKey('kdcType')) {
$body["kdcType"] = "$kdcType"
}
If ($PSBoundParameters.ContainsKey('kdcUsername')) {
$body["kdcUsername"] = "$kdcUsername"
}
If ($PSBoundParameters.ContainsKey('kdcPassword')) {
$body["kdcPassword"] = "$kdcPassword"
}
If ($PSBoundParameters.ContainsKey('isExtendedCredentialsEnabled')) {
$body["isExtendedCredentialsEnabled"] = $isExtendedCredentialsEnabled
}
If ($PSBoundParameters.ContainsKey('credentialsCacheTTL')) {
$body["credentialsCacheTTL"] = $credentialsCacheTTL
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
If ($Sess.TestConnection()) {
##Building the URL
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $Item $address")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
Write-Verbose "Request status code: $($request.StatusCode)"
If ($request.StatusCode -eq $StatusCode) {
#Formating the result. Converting it from JSON to a Powershell object
$results = ($request.content | ConvertFrom-Json).content
Write-Verbose "$Item with the ID $($results.id) has been created"
#Executing Get-UnityUser with the ID of the new user
Get-UnityNFSServer -Session $Sess -ID $results.id
} # End If ($request.StatusCode -eq $StatusCode)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnitySMTPServer.ps1
|
New-UnitySMTPServer.ps1
|
Function New-UnitySMTPServer {
<#
.SYNOPSIS
Create a new SMTP server (Default or PhoneHome).
.DESCRIPTION
Create a new SMTP server (Default or PhoneHome).
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER address
IP address of the SMTP server.
.PARAMETER type
SMTP server type. Might be:
- Default
- PhoneHome
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
New-UnitySMTPServer -address 'smtp.example.com' -type 'default'
Create a new default SMTP server.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,HelpMessage = 'IP address of the SMTP server.')]
[string]$address,
[Parameter(Mandatory = $true,HelpMessage = 'SMTP server type.')]
[SmtpTypeEnum]$type
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/types/smtpServer/instances'
$Item = 'SMTP Server'
$StatusCode = 201
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
#### REQUEST BODY
#Creation of the body hash
$body = @{}
#Body arguments
$body["address"] = $address
$body["type"] = $type
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
If ($Sess.TestConnection()) {
##Building the URL
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $Item $address")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
Write-Verbose "Request status code: $($request.StatusCode)"
If ($request.StatusCode -eq $StatusCode) {
#Formating the result. Converting it from JSON to a Powershell object
$results = ($request.content | ConvertFrom-Json).content
Write-Verbose "$Item with the ID $($results.id) has been created"
#Executing Get-UnityUser with the ID of the new user
Get-UnitySMTPServer -Session $Sess -ID $results.id
} # End If ($request.StatusCode -eq $StatusCode)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityMetricRealTimeQuery.ps1
|
Get-UnityMetricRealTimeQuery.ps1
|
Function Get-UnityMetricRealTimeQuery {
<#
.SYNOPSIS
Information about real times metric queries.
.DESCRIPTION
Information about real times metric queries.
It represents a query to obtain real-time information for one or more metrics, including a specified sampling frequency.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Queries ID.
.EXAMPLE
Get-UnityMetricRealTimeQuery
Retrieve informations about all queries.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Queries ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/metricRealTimeQuery/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityMetricRealTimeQuery'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnityNFSShare.ps1
|
Set-UnityNFSShare.ps1
|
Function Set-UnityNFSShare {
<#
.SYNOPSIS
Modifies NFS share.
.DESCRIPTION
Modifies NFS share.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
ID of the NFS share.
.PARAMETER description
NFS share description
.PARAMETER isReadOnly
Indicates whether the NFS share is read-only. Values are:
- true - NFS share is read-only.
- false - NFS share is read-write.
.PARAMETER defaultAccess
Default access level for all hosts accessing the NFS share.
.PARAMETER minSecurity
Minimal security level that must be provided by a client to mount the NFS share.
.PARAMETER noAccessHosts
Hosts with no access to the NFS share or its snapshots, as defined by the host resource type.
.PARAMETER readOnlyHosts
Hosts with read-only access to the NFS share and its snapshots, as defined by the host resource type.
.PARAMETER readWriteHosts
Hosts with read-write access to the NFS share and its snapshots, as defined by the host resource type.
.PARAMETER rootAccessHosts
Hosts with root access to the NFS share and its snapshots, as defined by the host resource type.
.PARAMETER Append
Append Hosts access to existing configuration
.EXAMPLE
Set-UnityNFSShare -id 'NFSShare_2' -rootAccessHosts Host_20 -append
Set NFS Share with id 'NFSShare_2'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#NFSShareModify
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'ID of the NFS share')]
[String[]]$ID,
#$nfsShareParameters
[Parameter(Mandatory = $false,HelpMessage = 'NFS share description')]
[String]$description,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether the NFS share is read-only')]
[bool]$isReadOnly = $false,
[Parameter(Mandatory = $false,HelpMessage = 'Default access level for all hosts accessing the NFS share.')]
[NFSShareDefaultAccessEnum]$defaultAccess,
[Parameter(Mandatory = $false,HelpMessage = 'Minimal security level that must be provided by a client to mount the NFS share.')]
[NFSShareSecurityEnum]$minSecurity,
[Parameter(Mandatory = $false,HelpMessage = 'Hosts with no access to the NFS share or its snapshots.')]
[string[]]$noAccessHosts,
[Parameter(Mandatory = $false,HelpMessage = 'Hosts with read-only access to the NFS share and its snapshots.')]
[string[]]$readOnlyHosts,
[Parameter(Mandatory = $false,HelpMessage = 'Hosts with read-write access to the NFS share and its snapshots.')]
[string[]]$readWriteHosts,
[Parameter(Mandatory = $false,HelpMessage = 'Hosts with root access to the NFS share and its snapshots.')]
[string[]]$rootAccessHosts,
[Parameter(Mandatory = $false,HelpMessage = 'Append Hosts access to existing configuration')]
[Switch]$append
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/storageResource/<id>/action/modifyFilesystem'
$Type = 'NFS Share'
$TypeName = 'UnityNFSShare'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityNFSShare -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityNFSShare -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
$UnitystorageResource = Get-UnitystorageResource -Session $sess | Where-Object {($_.filesystem.id -like $Object.Filesystem.id)}
#### REQUEST BODY
# Creation of the body hash
$body = @{}
$body["nfsShareModify"] = @{}
#$NFSShareParameters
$nfsShareModifyParameters = @{}
$NFSShareModifyParameters["nfsShare"] = @{}
$NFSShare = @{}
$NFSShare['id'] = $ObjectID
$NFSShareModifyParameters["nfsShare"] = $NFSShare
#$nfsShareParameters
$nfsShareModifyParameters["nfsShareParameters"] = @{}
$nfsShareParameters = @{}
If ($PSBoundParameters.ContainsKey('description')) {
$nfsShareParameters["description"] = "$($description)"
}
$nfsShareParameters["isReadOnly"] = $isReadOnly
If ($PSBoundParameters.ContainsKey('defaultAccess')) {
$nfsShareParameters["defaultAccess"] = $defaultAccess
}
If ($PSBoundParameters.ContainsKey('minSecurity')) {
$nfsShareParameters["minSecurity"] = $minSecurity
}
If ($PSBoundParameters.ContainsKey('noAccessHosts')) {
$nfsShareParameters["noAccessHosts"] = @()
foreach ($h in $noAccessHosts) {
$HostParam = @{}
$HostParam['id'] = $h
$nfsShareParameters["noAccessHosts"] += $HostParam
}
If ($append) {
foreach ($h in $Object.noAccessHosts) {
$nfsShareParameters["noAccessHosts"] += $h
}
}
}
If ($PSBoundParameters.ContainsKey('readOnlyHosts')) {
$nfsShareParameters["readOnlyHosts"] = @()
foreach ($h in $readOnlyHosts) {
$HostParam = @{}
$HostParam['id'] = $h
$nfsShareParameters["readOnlyHosts"] += $HostParam
}
If ($append) {
foreach ($h in $Object.readOnlyHosts) {
$nfsShareParameters["readOnlyHosts"] += $h
}
}
}
If ($PSBoundParameters.ContainsKey('readWriteHosts')) {
$nfsShareParameters["readWriteHosts"] = @()
foreach ($h in $readWriteHosts) {
$HostParam = @{}
$HostParam['id'] = $h
$nfsShareParameters["readWriteHosts"] += $HostParam
}
If ($append) {
foreach ($h in $Object.readWriteHosts) {
$nfsShareParameters["readWriteHosts"] += $h
}
}
}
If ($PSBoundParameters.ContainsKey('rootAccessHosts')) {
$nfsShareParameters["rootAccessHosts"] = @()
foreach ($h in $rootAccessHosts) {
$HostParam = @{}
$HostParam['id'] = $h
$nfsShareParameters["rootAccessHosts"] += $HostParam
}
If ($append) {
foreach ($h in $Object.rootAccessHosts) {
$nfsShareParameters["rootAccessHosts"] += $h
}
}
}
$nfsShareModifyParameters["nfsShareParameters"] = $nfsShareParameters
$body["nfsShareModify"] = $nfsShareModifyParameters
If (-not $append) {
Write-Warning -Message 'The existing host access parameters will be overwritten by the new settings. It could result to data unavailibility. Use the -Append parameter to add the new settings to the existing configuration.'
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$UnitystorageResource.id
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $ObjectName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityNFSShare -Session $Sess -ID $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityMetricQueryResult.ps1
|
Get-UnityMetricQueryResult.ps1
|
Function Get-UnityMetricQueryResult {
<#
.SYNOPSIS
A set of values for one or more metrics for a given period of time.
.DESCRIPTION
A set of values for one or more metrics for a given period of time.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER queryId
Queries ID or object.
.EXAMPLE
Get-UnityMetricQueryResult -queryId 5
Retrieve informations about query who's ID is 5.
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Queries ID or object')]
[Object[]]$queryId
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$ResultCollection = @()
$URI = '/api/types/metricQueryResult/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityMetricQueryResult'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($Query in $QueryID) {
# Determine input and convert to object if necessary
Write-Verbose "Input object type is $($Query.GetType().Name)"
Switch -wildcard ($Query.GetType().Name)
{
"UnityMetricRealTimeQuery" {
$ObjectID = $Query.id
}
"Int*" {
If ($Object = Get-UnityMetricRealTimeQuery -Session $Sess -ID $Query -ErrorAction SilentlyContinue) {
$ObjectID = $Object.id
} else {
Throw "This query does not exist"
}
}
}
$Filter = 'queryId EQ '+$ObjectID
#Building the URL from Object Type.
$URL = Get-URLFromObjectType -Session $sess -URI $URI -TypeName $TypeName -Compact -Filter $Filter
Write-Verbose "URL: $URL"
#Sending the request
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'GET'
#Formating the result. Converting it from JSON to a Powershell object
$Results = ($request.content | ConvertFrom-Json).entries.content
#Building the result collection (Add ressource type)
If ($Results) {
$ResultCollection = ConvertTo-Hashtable -Data $Results
Foreach ($Result in $ResultCollection) {
# Instantiate object
$Object = New-Object -TypeName $TypeName -Property $Result
# Output results
$Object
} # End Foreach ($Result in $ResultCollection)
} # End If ($Results)
} # End Foreach ($Query in $QueryID) {
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnityUser.ps1
|
New-UnityUser.ps1
|
Function New-UnityUser {
<#
.SYNOPSIS
Create a new local user.
.DESCRIPTION
Create a new local user and specified role and password.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER name
User name.
.PARAMETER role
User role. Might be:
- administrator
- storageadmin
- vmadmin
- operator
.PARAMETER password
Initial password for the user.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running. If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
New-UnityUser -Name 'user' -Role 'operator' -Password 'Password@123'
Creates a new local user named 'User' with the role 'operator' and the password 'Password@123'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'User Name')]
[String[]]$Name,
[Parameter(Mandatory = $true,HelpMessage = 'User role. It mights be administrator, storageadmin, vmadmin or operator')]
[ValidateSet('administrator', 'storageadmin', 'vmadmin', 'operator')]
[String]$Role,
[Parameter(Mandatory = $true,HelpMessage = 'User Password')]
[String]$Password
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/types/user/instances'
$Type = 'User'
$StatusCode = 201
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
Foreach ($n in $Name) {
#### REQUEST BODY
# Creation of the body hash
$body = @{}
# Name parameter
$body["name"] = "$($n)"
# Role parameter
$body["role"] = "$($Role)"
# Password parameter
$body["password"] = "$($Password)"
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
If ($Sess.TestConnection()) {
##Building the URL
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $Type $n")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
Write-Verbose "Request status code: $($request.StatusCode)"
If ($request.StatusCode -eq $StatusCode) {
#Formating the result. Converting it from JSON to a Powershell object
$results = ($request.content | ConvertFrom-Json).content
Write-Verbose "$Type with the ID $($results.id) has been created"
Get-UnityUser -Session $Sess -ID $results.id
} # End If ($request.StatusCode -eq $StatusCode)
} # End If ($Sess.TestConnection())
} # End Foreach
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityIpPort.ps1
|
Get-UnityIpPort.ps1
|
Function Get-UnityIPPort {
<#
.SYNOPSIS
Queries the EMC Unity array to retrieve informations about IP Ports.
.DESCRIPTION
Queries the EMC Unity array to retrieve informations about IP Ports.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityIpPort
Retrieve information about all IP Ports
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'IP Port Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'IP Port ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/ipPort/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityIpPort'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Get-UnityvCenter.ps1
|
Get-UnityvCenter.ps1
|
Function Get-UnityvCenter {
<#
.SYNOPSIS
View details about vCenter configuration on the system.
.DESCRIPTION
View details about vCenter configuration on the system.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityvCenter
Retrieve information about all hosts
.EXAMPLE
Get-UnityvCenter -Name 'VCENTER01'
Retrieves information about vCenter named 'VCENTER01'
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'vCenter Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'vCenter ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/hostContainer/instances' #URI
$Filter = 'type eq 2'
$TypeName = 'UnityHostContainer'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName] -Filter $Filter
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/New-UnityVMwareLUN.ps1
|
New-UnityVMwareLUN.ps1
|
Function New-UnityVMwareLUN {
<#
.SYNOPSIS
Creates a Unity VMware block LUN.
.DESCRIPTION
Creates a Unity VMware block LUN.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER Name
Name of the VMware VMFS datastore unique to the system.
.PARAMETER Pool
Pool ID
.PARAMETER Description
Description of the VMware VMFS datastore.
.PARAMETER Size
LUN Size.
.PARAMETER fastVPParameters
FAST VP settings for the storage resource
.PARAMETER isCompressionEnabled
Indicates whether to enable inline compression for the LUN. Default is True on supported arrays
.PARAMETER isThinEnabled
Is Thin enabled? (Default is true)
.PARAMETER host
List of host to grant access to LUN.
.PARAMETER accessMask
Host access mask. Might be:
- NoAccess: No access.
- Production: Access to production LUNs only.
- Snapshot: Access to LUN snapshots only.
- Both: Access to both production LUNs and their snapshots.
.PARAMETER snapSchedule
Snapshot schedule assigned to the storage resource
.PARAMETER isSnapSchedulePaused
Indicates whether the assigned snapshot schedule is paused.
.EXAMPLE
New-UnityVMwareLUN -Name 'DATASTORE01' -Pool 'pool_1' -Size 10GB -host 'Host_12' -accessMask 'Production'
Create LUN named 'DATASTORE01' on pool 'pool_1' and with a size of '10GB', grant production access to 'Host_12'
.EXAMPLE
for($i=1; $i -le 10; $i++){New-UnityVMwareLUN -Name "DATASTORE0$i" -Size 2TB -Pool 'pool_1' -host (Get-UnityHost).id}
Create 10 datastores on pool 'pool_1' and with a size of '2TB', grant production access to all existing hosts.
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'VMware LUN Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,HelpMessage = 'VMware LUN Description')]
[String]$Description,
# lunParameters
[Parameter(Mandatory = $true,HelpMessage = 'VMware LUN Pool ID')]
[String]$Pool,
[Parameter(Mandatory = $true,HelpMessage = 'VMware LUN Size in Bytes')]
[uint64]$Size,
[Parameter(Mandatory = $false,HelpMessage = 'Host to grant access to VMware LUN')]
[String[]]$host,
[Parameter(Mandatory = $false,HelpMessage = 'Host access mask')]
[HostLUNAccessEnum]$accessMask = 'Production',
[Parameter(Mandatory = $false,HelpMessage = 'Is Thin enabled on VMware LUN ? (Default is true)')]
[bool]$isThinEnabled = $true,
[Parameter(Mandatory = $false,HelpMessage = 'FAST VP settings for the storage resource')]
[TieringPolicyEnum]$fastVPParameters,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether to enable inline compression for the LUN. Default is True')]
[bool]$isCompressionEnabled,
# snapScheduleParameters
[Parameter(Mandatory = $false,HelpMessage = 'ID of a protection schedule to apply to the storage resource')]
[String]$snapSchedule,
[Parameter(Mandatory = $false,HelpMessage = 'Is assigned snapshot schedule is paused ? (Default is false)')]
[bool]$isSnapSchedulePaused = $false
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
## Variables
$URI = '/api/types/storageResource/action/createVmwareLun'
$Type = 'VMware LUN'
$StatusCode = 200
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
Foreach ($n in $Name) {
# Creation of the body hash
$body = @{}
# Name parameter
$body["name"] = "$($n)"
# Domain parameter
If ($Description) {
$body["description"] = "$($Description)"
}
# lunParameters parameter
$body["lunParameters"] = @{}
$lunParameters = @{}
$poolParameters = @{}
$poolParameters["id"] = "$($Pool)"
$lunParameters["pool"] = $poolParameters
$lunParameters["size"] = $($Size)
If ($PSBoundParameters.ContainsKey('fastVPParameters')) {
$lunParameters["fastVPParameters"] = @{}
$fastVPParam = @{}
$fastVPParam['tieringPolicy'] = $fastVPParameters
$lunParameters["fastVPParameters"] = $fastVPParam
}
If ($PSBoundParameters.ContainsKey('isCompressionEnabled')) {
$lunParameters["isCompressionEnabled"] = $isCompressionEnabled
} else {
$lunParameters["isCompressionEnabled"] = Test-CompressionUnsupported -Session $Sess -Pool $Pool
}
If ($PSBoundParameters.ContainsKey('host')) {
$lunParameters["hostAccess"] = @()
$hostAccess = @()
foreach ($h in $host) {
$blockHostAccessParam = @{}
$blockHostAccessParam['host'] = @{}
$HostParam = @{}
$HostParam['id'] = $h
$blockHostAccessParam['host'] = $HostParam
$blockHostAccessParam['accessMask'] = $accessMask
$hostAccess += $blockHostAccessParam
}
$lunParameters["hostAccess"] = $hostAccess
}
$body["lunParameters"] = $lunParameters
#snapScheduleParameters
If ($snapSchedule) {
$body["snapScheduleParameters"] = @{}
$snapScheduleParameters = @{}
$snapScheduleParam = @{}
$snapScheduleParam["id"] ="$($snapSchedule)"
$snapScheduleParameters["snapSchedule"] = $snapScheduleParam
$snapScheduleParameters["isSnapSchedulePaused"]= "$($isSnapSchedulePaused)"
$body["snapScheduleParameters"] = $snapScheduleParameters
}
# isThinEnabled
If ($isThinEnabled) {
$lunParameters["isThinEnabled"] = $isThinEnabled
}
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
If ($Sess.TestConnection()) {
##Building the URL
$URL = 'https://'+$sess.Server+$URI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Create $Type $n")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
Write-Verbose "Request status code: $($request.StatusCode)"
If ($request.StatusCode -eq $StatusCode) {
#Formating the result. Converting it from JSON to a Powershell object
$results = ($request.content | ConvertFrom-Json).content
$Storageresource = Get-UnitystorageResource -session $Sess -ID $results.storageResource.id
Write-Verbose "$Type with the ID $($Storageresource.luns.id) has been created"
Get-UnityVMwareLUN -Session $Sess -ID $Storageresource.luns.id
} # End If ($request.StatusCode -eq $StatusCode)
} # End If ($Sess.TestConnection())
} # End Foreach
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Set-UnityCIFSShare.ps1
|
Set-UnityCIFSShare.ps1
|
Function Set-UnityCIFSShare {
<#
.SYNOPSIS
Modifies CIFS share.
.DESCRIPTION
Modifies CIFS share.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specify an UnitySession Object.
.PARAMETER ID
ID of the CIFS share.
.PARAMETER description
CIFS share description
.PARAMETER isReadOnly
Indicates whether the CIFS share is read-only
.PARAMETER isEncryptionEnabled
Indicates whether CIFS encryption for Server Message Block (SMB) 3.0 is enabled for the CIFS share
.PARAMETER isContinuousAvailabilityEnabled
Indicates whether continuous availability for SMB 3.0 is enabled for the CIFS share
.PARAMETER isABEEnabled
Enumerate file with read access and directories with list access in folder listings
.PARAMETER isBranchCacheEnabled
Branch Cache optimizes traffic between the NAS server and Branch Office Servers
.PARAMETER offlineAvailability
Offline Files store a version of the shared resources on the client computer in the file system cache,
a reserved portion of disk space, which the client computer can access even when it is disconnected from the network.
.PARAMETER umask
The default UNIX umask for new files created on the share.
.PARAMETER Confirm
If the value is $true, indicates that the cmdlet asks for confirmation before running.
If the value is $false, the cmdlet runs without asking for user confirmation.
.PARAMETER WhatIf
Indicate that the cmdlet is run only to display the changes that would be made and actually no objects are modified.
.EXAMPLE
Set-UnityCIFSShare -ID 'SMBShare_1' -Description 'New description'
Modifies the CIFS share with id 'SMBShare_1'
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param (
#Default Parameters
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
#cifsShareModify
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'ID of the CIFS share')]
[String[]]$ID,
#$cifsShareParameters
[Parameter(Mandatory = $false,HelpMessage = 'CIFS share description')]
[String]$description,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether the CIFS share is read-only')]
[bool]$isReadOnly,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether CIFS encryption for Server Message Block (SMB) 3.0 is enabled for the CIFS share')]
[bool]$isEncryptionEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Indicates whether continuous availability for SMB 3.0 is enabled for the CIFS share')]
[bool]$isContinuousAvailabilityEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Enumerate file with read access and directories with list access in folder listings')]
[bool]$isABEEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Branch Cache optimizes traffic between the NAS server and Branch Office Servers')]
[bool]$isBranchCacheEnabled,
[Parameter(Mandatory = $false,HelpMessage = 'Offline Files store a version of the shared resources on the client computer in the file system cache, a reserved portion of disk space, which the client computer can access even when it is disconnected from the network')]
[CifsShareOfflineAvailabilityEnum]$offlineAvailability,
[Parameter(Mandatory = $false,HelpMessage = 'The default UNIX umask for new files created on the share')]
[String]$umask
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
# Variables
$URI = '/api/instances/storageResource/<id>/action/modifyFilesystem'
$Type = 'CIFS Share'
$TypeName = 'UnityCIFSShare'
$StatusCode = 204
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "Processing Session: $($sess.Server) with SessionId: $($sess.SessionId)"
If ($Sess.TestConnection()) {
Foreach ($i in $ID) {
# Determine input and convert to object if necessary
Switch ($i.GetType().Name)
{
"String" {
$Object = get-UnityCIFSShare -Session $Sess -ID $i
$ObjectID = $Object.id
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
"$TypeName" {
Write-Verbose "Input object type is $($i.GetType().Name)"
$ObjectID = $i.id
If ($Object = Get-UnityCIFSShare -Session $Sess -ID $ObjectID) {
If ($Object.Name) {
$ObjectName = $Object.Name
} else {
$ObjectName = $ObjectID
}
}
}
}
If ($ObjectID) {
$UnitystorageResource = Get-UnitystorageResource -Session $sess | Where-Object {($_.filesystem.id -like $Object.Filesystem.id)}
#### REQUEST BODY
# Creation of the body hash
$body = @{}
$body["cifsShareModify"] = @()
$cifsShareModifyParameters = @{}
$cifsShareModifyParameters["cifsShare"] = @{}
$cifsShare = @{}
$cifsShare['id'] = $ObjectID
$cifsShareModifyParameters["cifsShare"] = $cifsShare
#$cifsShareParameters
If (($PSBoundParameters.ContainsKey('description')) -or ($PSBoundParameters.ContainsKey('isReadOnly')) -or ($PSBoundParameters.ContainsKey('isEncryptionEnabled')) -or ($PSBoundParameters.ContainsKey('isContinuousAvailabilityEnabled')) -or ($PSBoundParameters.ContainsKey('isABEEnabled')) -or ($PSBoundParameters.ContainsKey('isBranchCacheEnabled')) -or ($PSBoundParameters.ContainsKey('offlineAvailability')) -or ($PSBoundParameters.ContainsKey('umask'))){
$cifsShareModifyParameters["cifsShareParameters"] = @{}
$cifsShareParameters = @{}
If ($PSBoundParameters.ContainsKey('description')) {
$cifsShareParameters["description"] = "$($description)"
}
If ($PSBoundParameters.ContainsKey('isReadOnly')) {
$cifsShareParameters["isReadOnly"] = $isReadOnly
}
If ($PSBoundParameters.ContainsKey('isEncryptionEnabled')) {
$cifsShareParameters["isEncryptionEnabled"] = $isEncryptionEnabled
}
If ($PSBoundParameters.ContainsKey('isContinuousAvailabilityEnabled')) {
$cifsShareParameters["isContinuousAvailabilityEnabled"] = $isContinuousAvailabilityEnabled
}
If ($PSBoundParameters.ContainsKey('isABEEnabled')) {
$cifsShareParameters["isABEEnabled"] = $isABEEnabled
}
If ($PSBoundParameters.ContainsKey('isBranchCacheEnabled')) {
$cifsShareParameters["isBranchCacheEnabled"] = $isBranchCacheEnabled
}
If ($PSBoundParameters.ContainsKey('offlineAvailability')) {
$cifsShareParameters["offlineAvailability"] = "$($offlineAvailability)"
}
If ($PSBoundParameters.ContainsKey('umask')) {
$cifsShareParameters["umask"] = "$($umask)"
}
$cifsShareModifyParameters["cifsShareParameters"] = $cifsShareParameters
}
$body["cifsShareModify"] += $cifsShareModifyParameters
####### END BODY - Do not edit beyond this line
#Show $body in verbose message
$Json = $body | ConvertTo-Json -Depth 10
Write-Verbose $Json
#Building the URL
$FinalURI = $URI -replace '<id>',$UnitystorageResource.id
$URL = 'https://'+$sess.Server+$FinalURI
Write-Verbose "URL: $URL"
#Sending the request
If ($pscmdlet.ShouldProcess($Sess.Name,"Modify $Type $ObjectName")) {
$request = Send-UnityRequest -uri $URL -Session $Sess -Method 'POST' -Body $Body
}
If ($request.StatusCode -eq $StatusCode) {
Write-Verbose "$Type with ID $ObjectID has been modified"
Get-UnityCIFSShare -Session $Sess -ID $ObjectID
} # End If ($request.StatusCode -eq $StatusCode)
} else {
Write-Warning -Message "$Type with ID $i does not exist on the array $($sess.Name)"
} # End If ($ObjectID)
} # End Foreach ($i in $ID)
} # End If ($Sess.TestConnection())
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Hardware/Get-UnitySsd.ps1
|
Get-UnitySsd.ps1
|
Function Get-UnitySsd {
<#
.SYNOPSIS
Information about internal Flash-based Solid State Disks (SSDs, mSATAs) in the storage system.
.DESCRIPTION
Information about internal Flash-based Solid State Disks (SSDs, mSATAs) in the storage system.
Applies to physical deployments only.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Specifies the object ID.
.PARAMETER Name
Specifies the object name.
.EXAMPLE
Get-UnitySsd
Retrieve Information about SSD.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'SSD Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'SSD ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/ssd/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnitySsd'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Hardware/Get-UnityStorageProcessor.ps1
|
Get-UnityStorageProcessor.ps1
|
Function Get-UnityStorageProcessor {
<#
.SYNOPSIS
Information about Storage Processor.
.DESCRIPTION
Information about Storage Processor.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityStorageProcessor
Retrieve Information about Storage Processor.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Storage Processor Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Storage Processor ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/storageProcessor/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityStorageProcessor'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Hardware/Get-UnityDae.ps1
|
Get-UnityDae.ps1
|
Function Get-UnityDae {
<#
.SYNOPSIS
Information about Disk Array Enclosure (DAE) components in the storage system.
.DESCRIPTION
Information about Disk Array Enclosure (DAE) components in the storage system.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityDae
Retrieve Information about Disk Array Enclosure (DAE) components in the storage system.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'DAE Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'DAE ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/dae/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityDae'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Hardware/Get-UnityDisk.ps1
|
Get-UnityDisk.ps1
|
Function Get-UnityDisk {
<#
.SYNOPSIS
View details about disks on the system.
.DESCRIPTION
View details about disk on the system.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityDisk
Retrieve information about all disks
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Disk Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Disk ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/disk/instances' #URI
$TypeName = 'UnityDisk'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Hardware/Get-UnityDpe.ps1
|
Get-UnityDpe.ps1
|
Function Get-UnityDpe {
<#
.SYNOPSIS
Information about Disk Processor Enclosures (DPEs) in the storage system.
.DESCRIPTION
Information about Disk Processor Enclosures (DPEs) in the storage system.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityDpe
Retrieve Information about Disk Processor Enclosures (DPEs) in the storage system.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'DPE Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'DPE ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/dpe/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityDpe'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Hardware/Get-UnityEthernetPort.ps1
|
Get-UnityEthernetPort.ps1
|
Function Get-UnityEthernetPort {
<#
.SYNOPSIS
Queries the EMC Unity array to retrieve informations about Ethernet Ports.
.DESCRIPTION
Queries the EMC Unity array to retrieve informations about Ethernet Ports.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityEthernetPort
Retrieve information about all ethernet ports
.EXAMPLE
Get-UnityEthernetPort -Name 'Ethernet Ports01'
Retrieves information about ethernet port named 'Ethernet Ports01'
#>
[CmdletBinding(DefaultParameterSetName="Name")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Ethernet port Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Ethernet port ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/ethernetPort/instances' #URI
$TypeName = 'UnityEthernetPort'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Hardware/Get-UnityEncryption.ps1
|
Get-UnityEncryption.ps1
|
Function Get-UnityEncryption {
<#
.SYNOPSIS
Information about Encryption.
.DESCRIPTION
Information about Encryption.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityEncryption
Retrieve Information about Encryption.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Encryption ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/encryption/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnityEncryption
'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/Unity-Powershell/0.14.2/Public/Hardware/Get-UnitySsc.ps1
|
Get-UnitySsc.ps1
|
Function Get-UnitySsc {
<#
.SYNOPSIS
Information about System Status Cards (SSCs) in the storage system.
.DESCRIPTION
Information about System Status Cards (SSCs) in the storage system.
Applies to physical deployments only.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Specifies the object ID.
.PARAMETER Name
Specifies the object name.
.EXAMPLE
Get-UnitySsc
Retrieve Information about System Status Cards (SSCs) in the storage system.
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'SSD Name')]
[String[]]$Name,
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'SSD ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/ssc/instances' #URI for the ressource (example: /api/types/lun/instances)
$TypeName = 'UnitySsc'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
|
PowerShellCorpus/PowerShellGallery/PartnerCenterModule/0.9.0.8/PartnerCenterModule.ps1
|
PartnerCenterModule.ps1
|
# v1.4.0.0
<#
© 2017 Microsoft Corporation. All rights reserved. This sample code is not supported under any Microsoft standard support program or service.
This sample code is provided AS IS without warranty of any kind. Microsoft disclaims all implied warranties including, without limitation,
any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance
of the sample code and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation,
production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business
profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the
sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.
#>
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\src\commons.ps1"
class Attributes
{
[string] $ObjectType
Attributes ([string] $ObjectType)
{
$this.ObjectType = $ObjectType
}
}
class CompanyProfile
{
[string] $TenantId
[string] $Domain
[string] $CompanyName
[Attributes] $Attributes
CompanyProfile ([string] $Domain)
{
$att_tmp = [Attributes]::new('CompanyProfile')
$this.Domain = $Domain
$this.Attributes = $att_tmp
}
}
class DefaultAddress
{
[string] $Country
[string] $Region
[string] $City
[string] $State
[string] $AddressLine1
[string] $AddressLine2
[string] $PostalCode
[string] $FirstName
[string] $LastName
[string] $PhoneNumber
#main constructor
DefaultAddress ([string] $Country, [string] $Region, [string] $City, [string] $State, [string] $AddressLine1, `
[string] $PostalCode, [string] $FirstName, [string] $LastName, [string] $PhoneNumber)
{
$this.Country = $Country
$this.Region = $Region
$this.City = $City
$this.State = $State
$this.AddressLine1 = $AddressLine1
$this.PostalCode = $PostalCode
$this.FirstName = $FirstName
$this.LastName = $LastName
$this.PhoneNumber = $PhoneNumber
}
DefaultAddress ([string] $Country, [string] $Region, [string] $City, [string] $State, [string] $AddressLine1, `
[string] $PostalCode)
{
$this.Country = $Country
$this.Region = $Region
$this.City = $City
$this.State = $State
$this.AddressLine1 = $AddressLine1
$this.PostalCode = $PostalCode
}
}
class BillingProfile
{
#read only
[string] $Id
[string] $Email
[string] $Culture
[string] $Language
[string] $CompanyName
[DefaultAddress] $DefaultAddress
[Attributes] $Attributes
#main constructors
BillingProfile ([string] $Email,[string] $Culture,[string] $Language,[string] $CompanyName, [string] $Country, [string] $Region, [string] $City, [string] $State, [string] $AddressLine1,[string] $PostalCode, [string] $FirstName, [string] $LastName, [string] $PhoneNumber)
{
$defaultAddresstmp = [DefaultAddress]::new($Country, $Region, $City,$State,$AddressLine1,$PostalCode,$FirstName,$LastName,$PhoneNumber)
$att_tmp = [Attributes]::new('BillingProfile')
$this.DefaultAddress = $defaultAddresstmp
$this.Email = $Email
$this.Culture = $Culture
$this.Language = $Language
$this.CompanyName = $CompanyName
$this.Attributes = $att_tmp
}
BillingProfile ([string] $Email,[string]$Culture,[string]$Language,[string]$CompanyName,[DefaultAddress] $DefaultAddress)
{
$att_tmp = [Attributes]::new('BillingProfile')
$this.Email = $Email
$this.Culture = $Culture
$this.Language = $Language
$this.CompanyName = $CompanyName
$this.DefaultAddress = $DefaultAddress
$this.Attributes = $att_tmp
}
}
class Customer
{
#read only
[string] $Id
[string] $CommerceId
[string] $RelationshipToPartner = 'none'
[string] $UserCredentials
#mandatoryFields
[BillingProfile]$BillingProfile
[CompanyProfile]$CompanyProfile
#optionalFields
[string] $AllowDelegatedAccess
[Attributes] $Attributes
#main constructors
Customer ([string] $Email,[string] $Culture,[string] $Language,[string] $CompanyName, `
[string] $Country, [string] $Region, [string] $City, [string] $State, [string] $AddressLine1, `
[string] $PostalCode, [string] $FirstName, [string] $LastName, [string] $PhoneNumber, `
[string] $Domain)
{
$defaultaddress_tmp = [DefaultAddress]::new($Country,$Region,$City,$State,$AddressLine1, `
$PostalCode,$FirstName,$LastName,$PhoneNumber)
$billingprofile_tmp = [BillingProfile]::new($Email,$Culture,$Language,$CompanyName,$defaultaddress_tmp)
$companyprofile_tmp = [CompanyProfile]::new($Domain)
$att_tmp = [Attributes]::new('Customer')
$this.CompanyProfile = $companyprofile_tmp
$this.BillingProfile = $billingprofile_tmp
$this.Attributes = $att_tmp
}
Customer ([BillingProfile]$BillingProfile,[CompanyProfile]$CompanyProfile)
{
$att_tmp = [Attributes]::new('Customer')
$this.CompanyProfile = $CompanyProfile
$this.BillingProfile = $BillingProfile
$this.Attributes = $att_tmp
}
}
class CustomerUserPasswordProfile
{
[string] $password
[bool] $forceChangePassword
CustomerUserPasswordProfile ([SecureString] $password,[bool]$forceChangePassword)
{
$this.password = _unsecureString -string $password
$this.forceChangePassword = $forceChangePassword
}
}
class CustomerUser
{
[string] $Id
[string] $usageLocation
[string] $userPrincipalName
[string] $firstName
[string] $lastName
[string] $displayName
[CustomerUserPasswordProfile] $passwordProfile
[Attributes] $Attributes
CustomerUser ([string]$usageLocation ,[string] $userPrincipalName,[string] $firstName,[string] $lastName,[string] $displayName,[SecureString] $password,[bool] $forceChangePassword)
{
$passwordProfile_tmp = [CustomerUserPasswordProfile]::new($password,$forceChangePassword)
$att_tmp = [Attributes]::new('CustomerUser')
$this.usageLocation = $usageLocation
$this.userPrincipalName = $userPrincipalName
$this.firstName = $firstName
$this.lastName = $lastName
$this.displayName = $displayName
$this.passwordProfile = $passwordProfile_tmp
$this.Attributes = $att_tmp
}
<#
CustomerUser([string]$usageLocation ,[string] $userPrincipalName,[string] $firstName,[string] $lastName,[string] $displayName,[CustomerUserPasswordProfile]$CustomerUserPasswordProfile)
{
$att_tmp = [Attributes]::new('CustomerUser')
$this.usageLocation = $usageLocation
$this.userPrincipalName = $userPrincipalName
$this.firstName = $firstName
$this.lastName = $lastName
$this.displayName = $displayName
$this.passwordProfile = $CustomerUserPasswordProfile
$this.Attributes = $att_tmp
}
#>
}
class DirectoryRoleMember
{
[string] $id
}
class Order
{
#ReadOnly Fields
[string] $Id
#Mandatory Fields
[string] $ReferenceCustomerId
[Array] $LineItems
#Optional fields
[string] $Status = 'none'
[string] $CreationDate
[string] $BillingCycleType
[Attributes] $Attributes
Order ([string] $ReferenceCustomerId,[Array] $LineItems)
{
$this.ReferenceCustomerId = $ReferenceCustomerId
$this.LineItems = $LineItems
$att_tmp = [Attributes]::new('Order')
$this.Attributes = $att_tmp
}
}
class OrderLineItem
{
#Mandatory Fields
[uint16] $LineItemNumber
[string] $OfferId
[uint16] $Quantity
#Optional Fields
[string] $ReferencedEntitlementUris
[string] $FriendlyName
[string] $PartnerIdOnRecord
[string] $ParentSubscriptionId
#[psobject] $Links
OrderLineItem ([uint16] $LineItemNumber,[string] $OfferId,[uint16] $Quantity)
{
$this.LineItemNumber = $LineItemNumber
$this.OfferId = $OfferId
$this.Quantity = $Quantity
}
OrderLineItem ()
{
}
}
class SpendingBudget
{
[double] $amount
SpendingBudget ([double] $amount)
{
$this.amount = $amount
}
}
#region SR class
class ServiceRequestOrganization
{
[string] $Id
[string] $Name
[string] $PhoneNumber
}
class ServiceRequestContact
{
[string] $ContactId
[string] $LastName
[string] $FirstName
[string] $Email
[string] $PhoneNumber
[ServiceRequestOrganization] $Organization
}
class ServiceRequestNote
{
[string] $CreatedByName
[string] $Text
[datetime] $CreatedDate
ServiceRequestNote ([string]$Text)
{
$this.Text = $Text
# $this.CreatedDate = Get-Date
}
ServiceRequestNote ()
{
}
}
class FileInfo
{
[string] $Comment
[string] $FileExtension
[string] $FileNameWithoutExtension
[long] $FileSize
[string] $Id
}
class ServiceRequest
{
#Mandatory Fields
[string] $Title
[string] $Description
[string] $Severity
[string] $SupportTopicId
#Optional Fields
[string] $SupportTopicName
[string] $Id
[string] $ProductName
[string] $ProductId
[datetime] $CreatedDate
[datetime] $LastModifiedDate
[datetime] $LastClosedDate
[string] $CountryCode
[Object] $Attributes
[FileInfo[]] $FileLinks
[ServiceRequestNote] $NewNote
[ServiceRequestNote[]] $Notes
[ServiceRequestContact] $PrimaryContact
[ServiceRequestContact] $LastUpdatedBy
[ServiceRequestOrganization] $Organization
[validateset('none','open','closed','attention_needed')][string] $Status
#main constructor
ServiceRequest ([string]$Title,[string]$Description,[string]$Severity,[string]$SupportTopicId)
{
$this.Title = $Title
$this.Severity = $Severity
$this.Description = $Description
$this.SupportTopicId = $SupportTopicId
}
#constructor
ServiceRequest ()
{
}
}
#endregion
class _Filter
{
#filter example: '{"Field":"CompanyName","Value":"csp","Operator":"starts_with"}'
#Mandatory Fields
[string]$Field
[string]$Value
[string]$Operator
<#
[validateset('CONTAINS','NOT_CONTAINS','IS','IS_NOT','ARE','IN','NOT_IN',
'IN_RANGE','NOT_IN_RANGE','STARTS_WITH','ENDS_WITH','ON_OR_BEFORE','ON_OR_AFTER','BETWEEN',
'EARLIER_THAN','WITHIN_THE_LAST','GREATER_THAN','LESS_THAN','IS_EMPTY','IS_NOT_EMPTY','INCLUDE'
'DO_NOT_INCLUDE','IS_APPLIED','IS_NOT_APPLIED',
)][string] $Operator
#>
_Filter([string]$Field,[string]$Value,[string]$Operator)
{
$this.Field = $Field
$this.Value = $Value
$this.Operator = $Operator
}
[string] _ToString ()
{
return '{"Field":"' + $this.Field + '","Value":"' + $this.Value + '","Operator":"' + $this.Operator + '"}'
}
}
#region class from GraphAPI
class PasswordResetInfo
{
[PasswordProfile] $passwordProfile
}
class PasswordProfile
{
[string] $password
[bool] $forceChangePasswordNextLogin
}
Set-Variable -Name "GlobalCustomerID" -Value "" -Scope Global -Visibility Private
Set-Variable -Name "GlobalToken" -Value "" -Scope Global -Visibility Private
#telemetry variables
Set-Variable -Name "GlobalPCPSTelemetry" -Value $true -Scope Global -Visibility Private
Set-Variable -Name "GlobalPCPSCSPDomain" -Value $null -Scope Global -Visibility Private
Set-Variable -Name "GlobalPCPSExecutionId" -Value $null -Scope Global -Visibility Private
Set-Variable -Name "GlobalPCPSModuleVersion" -Value $null -Scope Global -Visibility Private
|
PowerShellCorpus/PowerShellGallery/PartnerCenterModule/0.9.0.8/src/commons.ps1
|
commons.ps1
|
<#
© 2017 Microsoft Corporation. All rights reserved. This sample code is not supported under any Microsoft standard support program or service.
This sample code is provided AS IS without warranty of any kind. Microsoft disclaims all implied warranties including, without limitation,
any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance
of the sample code and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation,
production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business
profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the
sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.
#>
function _applyTypes {
param($item,$type)
$item.PSObject.TypeNames.Insert(0, $type)
}
function _formatResult {
param ($obj, $type)
try
{
if($obj.items)
{
foreach($item in $obj.items){_applyTypes -item $item -type $type}
return $obj.items
}
}
catch
{
_applyTypes -item $obj -type $type
return $obj
}
}
function _testTenantContext($tenantID)
{
if ($tenantid.Length -lt 1)
{
throw ">>>Use Select-PartnerCenterCustomer function to select a specific tenant or use -tenantid parameter<<<"
}
}
function _testTokenContext($satoken)
{
if ($satoken.Length -lt 1)
{
throw ">>>Use Add-PartnerCenterAuthentication function to login to partnercenter or use -satoken parameter<<<"
}
}
function _unsecureString
{
param ([SecureString]$string)
$tmp_cred = New-Object System.Management.Automation.PSCredential -ArgumentList "tmp", $string
return $tmp_cred.GetNetworkCredential().Password
}
#Setting Global Token
function Get-SAToken
{
[CmdletBinding()]
param ($aadtoken,[bool]$global)
$url = "https://api.partnercenter.microsoft.com/generatetoken"
$body = "grant_type=jwt_token"
$headers=@{Authorization="Bearer $aadtoken"}
$response = Invoke-RestMethod -Uri $url -ContentType "application/x-www-form-urlencoded" -Headers $headers -Body $body -method "POST" #-Debug -Verbose
#setting SAToke variable as global
if ($global){
Set-Variable -Name "GlobalToken" -Value $response.access_token -Scope Global
}
return $response.access_token
}
|
PowerShellCorpus/PowerShellGallery/UpdateServicesClientDSC/1.1.0.0/Examples/Sample_UpdateServicesClientDSC.ps1
|
Sample_UpdateServicesClientDSC.ps1
|
configuration Sample_WindowsUpdateClient {
Import-DscResource -ModuleName UpdateServicesClientDSC
Node localhost {
UpdateServicesClientDSC UpdateSettings {
Ensure = 'Present'
AutomaticUpdateEnabled = $true
AutomaticUpdateOption = 'AutoDownloadAndNotifyForInstall'
UpdateServer = 'https://wsus01.dscdomain.local:8530'
UpdateTargetGroup = 'test'
}
}
}
Sample_WindowsUpdateClient -OutputPath C:\temp
|
PowerShellCorpus/PowerShellGallery/UpdateServicesClientDSC/1.1.0.0/Tests/Unit/UpdateServicesClientDSC.Tests.ps1
|
UpdateServicesClientDSC.Tests.ps1
|
$DSCResourceName = 'UpdateServicesClientDSC'
$root = (Resolve-Path $PSScriptRoot\..\..).Path
Import-Module (Join-Path $root "DSCResources\$DSCResourceName\$DSCResourceName.psm1") -Force
InModuleScope $DSCResourceName {
Describe "$DSCResourceName\Get-TargetResource" -Tag UnitTest {
Mock Get-AutomaticUpdate
Mock Get-UpdateOption
Mock Get-UpdateServer
Mock Get-UpdateTargetGroup
Mock Get-UpdateScheduledInstallDay
Mock Get-UpdateScheduledInstallHour
Context 'Invoking Get-TargetResource' {
It 'Should return Ensure = Present and is a hashtable' {
$props = @{
Ensure = 'Present'
AutomaticUpdateEnabled = $true
}
$Result = Get-TargetResource @props
$Result.Ensure | Should Be $props.Ensure
$Result -is [System.Collections.Hashtable] | Should Be $true
}
It 'Should call all the mocks' {
Assert-MockCalled -CommandName Get-AutomaticUpdate -Exactly 1
Assert-MockCalled -CommandName Get-UpdateOption -Exactly 1
Assert-MockCalled -CommandName Get-UpdateServer -Exactly 1
Assert-MockCalled -CommandName Get-UpdateTargetGroup -Exactly 1
Assert-MockCalled -CommandName Get-UpdateScheduledInstallDay -Exactly 1
Assert-MockCalled -CommandName Get-UpdateScheduledInstallHour -Exactly 1
}
}
}
Describe "$DSCResourceName\Set-TargetResource" -Tag UnitTest {
Mock Get-TargetResource -MockWith {
[PSCustomObject]@{
Ensure = 'Present'
AutomaticUpdateEnabled = $true
AutomaticUpdateOption = 'NotifyBeforeDownload'
UpdateServer = 'https://wsus01.testdomain.local:8530'
UpdateTargetGroup = 'test'
}
}
Mock Set-AutomaticUpdate -MockWith {
[PSCustomObject]@{
Enabled = $true
}
}
Mock Remove-AutomaticUpdate
Mock Set-UpdateOption -MockWith {
[PSCustomObject]@{
Setting = 'AutoDownloadAndNotifyForInstall'
}
}
Mock Remove-UpdateOption
Mock Set-UpdateServer -MockWith {
[PSCustomObject]@{
Enabled = $true
URL = 'https://wsus01:8530'
}
}
Mock Remove-UpdateServer
Mock Set-UpdateTargetGroup -MockWith {
[PSCustomObject]@{
Name = 'test'
}
}
Mock Remove-UpdateTargetGroup
Context 'invoking Set-TargetResource' {
It 'Should return $null' {
$props = @{
Ensure = 'Present'
AutomaticUpdateEnabled = $true
AutomaticUpdateOption = 'AutoDownloadAndNotifyForInstall'
UpdateServer = 'https://wsus01:8530'
UpdateTargetGroup = 'test'
}
{ $Result = Set-TargetResource @props } | Should Not Throw
$Result | Should BeNullOrEmpty
}
It 'Should call mock: Get-TargetResource' {
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
}
It 'Should call mock: Set-UpdateOption' {
Assert-MockCalled -CommandName Set-UpdateOption -Exactly 1
}
It 'Should call mock: Set-UpdateServer' {
Assert-MockCalled -CommandName Set-UpdateServer -Exactly 1
}
It 'Should not call all the other mocks' {
Assert-MockCalled -CommandName Set-AutomaticUpdate -Exactly 0
Assert-MockCalled -CommandName Remove-AutomaticUpdate -Exactly 0
Assert-MockCalled -CommandName Remove-UpdateOption -Exactly 0
Assert-MockCalled -CommandName Remove-UpdateServer -Exactly 0
Assert-MockCalled -CommandName Set-UpdateTargetGroup -Exactly 0
Assert-MockCalled -CommandName Remove-UpdateTargetGroup -Exactly 0
}
}
}
Describe "$DSCResourceName\Test-TargetResource" -Tag UnitTest {
Mock Get-TargetResource -MockWith {
[PSCustomObject]@{
Ensure = 'Present'
AutomaticUpdateEnabled = $true
AutomaticUpdateOption = 'NotifyBeforeDownload'
UpdateServer = 'https://wsus01.testdomain.local:8530'
UpdateTargetGroup = 'test'
ScheduledInstallDay = 'Friday'
ScheduledInstallHour = '1'
}
}
Context 'invoking Test-TargetResource with same settings' {
It 'Should return $true' {
$testprops = @{
Ensure = 'Present'
AutomaticUpdateEnabled = $true
AutomaticUpdateOption = 'NotifyBeforeDownload'
UpdateServer = 'https://wsus01.testdomain.local:8530'
UpdateTargetGroup = 'test'
ScheduledInstallDay = 'Friday'
ScheduledInstallHour = '01'
}
$Result = Test-TargetResource @testprops
$Result | Should Be $true
}
It 'Should call Get-TargetResource 1 time' {
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
}
}
Context 'invoking Test-TargetResource with different UpdateServer' {
It 'Should return $false' {
$properties = @{
Ensure = 'Present'
AutomaticUpdateEnabled = $true
AutomaticUpdateOption = 'NotifyBeforeDownload'
UpdateServer = 'https://wsus02:8530'
UpdateTargetGroup = 'test'
ScheduledInstallDay = 'Friday'
ScheduledInstallHour = '01'
}
$Result = Test-TargetResource @properties
$Result | Should Be $false
}
It 'Should call Get-TargetResource 1 time' {
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/UpdateServicesClientDSC/1.1.0.0/Tests/Integration/UpdateServicesClientDSC.Integration.Tests.ps1
|
UpdateServicesClientDSC.Integration.Tests.ps1
|
$DSCModuleName = 'UpdateServicesClientDSC'
$DSCResourceName = 'UpdateServicesClientDSC'
Import-Module "$((Get-Item -LiteralPath "$($PSScriptRoot)").Parent.Parent.FullName)\Misc\KVWindowsUpdate.psm1"
$configfile = Join-Path -Path $PSScriptRoot -ChildPath "$($DSCResourceName).config.ps1"
. $configfile
$workingFolder = "$env:temp\$DSCModuleName\$DSCResourceName"
try {
Describe "$($DSCResourceName)_Integration" -Tag IntegrationTest {
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_config -OutputPath `$workingFolder"
Start-DscConfiguration -Path $workingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'Should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should not throw
}
It 'Should have set the resource and all the params should match' {
$config = Get-DscConfiguration | Where-Object { $_.ConfigurationName -eq "$($DSCResourceName)_config" }
$config.Ensure | Should Be $UpdateServicesClientDSC.Ensure
$config.AutomaticUpdateEnabled | Should Be $UpdateServicesClientDSC.AutomaticUpdateEnabled
$config.AutomaticUpdateOption | Should Be $UpdateServicesClientDSC.AutomaticUpdateOption
$config.UpdateServer | Should Be $UpdateServicesClientDSC.UpdateServer
$config.UpdateTargetGroup | Should Be $UpdateServicesClientDSC.UpdateTargetGroup
}
}
}
finally
{
Stop-DscConfiguration -Force
Remove-DscConfigurationDocument -Stage Current
Remove-DscConfigurationDocument -Stage Pending
Remove-DscConfigurationDocument -Stage Previous
Remove-AutomaticUpdate
Remove-UpdateOption
Remove-UpdateServer
Remove-UpdateTargetGroup
}
|
PowerShellCorpus/PowerShellGallery/UpdateServicesClientDSC/1.1.0.0/Tests/Integration/UpdateServicesClientDSC.config.ps1
|
UpdateServicesClientDSC.config.ps1
|
$UpdateServicesClientDSC = [PSObject]@{
Ensure = 'Present'
AutomaticUpdateEnabled = $true
AutomaticUpdateOption = 'AutoDownloadAndNotifyForInstall'
UpdateServer = 'https://wsus01.dscdomain.local:8530'
UpdateTargetGroup = 'test'
}
configuration UpdateServicesClientDSC_Config {
Import-DscResource -ModuleName UpdateServicesClientDSC
node localhost {
UpdateServicesClientDSC Integration_Test {
Ensure = $UpdateServicesClientDSC.Ensure
AutomaticUpdateEnabled = $UpdateServicesClientDSC.AutomaticUpdateEnabled
AutomaticUpdateOption = $UpdateServicesClientDSC.AutomaticUpdateOption
UpdateServer = $UpdateServicesClientDSC.UpdateServer
UpdateTargetGroup = $UpdateServicesClientDSC.UpdateTargetGroup
}
}
}
|
PowerShellCorpus/PowerShellGallery/NubusTech.CredentialStore/1.0/public/Get-CsEntry.ps1
|
Get-CsEntry.ps1
|
<#
.SYNOPSIS
Get CredentialStore Entries
.DESCRIPTION
The Get-CsEntry cmdlet gets objects that represent the CredentialStore entries for a file.
.PARAMETER FilePath
Specifies the path to the CredentialStore file.
.PARAMETER Name
Specifies the CredentialStore entries names of entries to be retrieved. Wildcards are permitted. By default,
this cmdlet gets all of the entries in the CredentialStore file.
.Example
Get-CsEntry -FilePath CredentialStore.json
This command gets all CredentialStore entries in the CredentialStore.json file.
.Example
Get-CsEntry -FilePath CredentialStore.json -Name "LocalServer"
This command retrieves CredentialStore entry with the name LocalServer.
.Example
Get-CsEntry -FilePath CredentialStore.json -Name "vmm*"
This command retrieves CredentialStore entries with names that begin with vmm.
.LINK
https://github.com/nubustech/NubusTech.CredentialStore
#>
function Get-CsEntry {
[CmdletBinding()]
param(
[ValidateScript( {
if (Test-Path $_) { $true }
else { throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' does not exist." }
})]
[Parameter(Mandatory = $false, Position = 0)]
[Alias("File")]
[string] $FilePath = (Get-CsDefaultStore),
[Parameter(Mandatory = $false)]
[string[]] $Name = "*"
)
$store = Get-Content -Raw -Path $FilePath | ConvertFrom-Json
if ($store.Username -ne $(whoami) -or $store.ComputerName -ne $(hostname)) {
throw "Cannot access CredentialStore, it is encrypted for user $($store.UserName) on Computer $($store.ComputerName)"
}
$entries = @(foreach ($entry in $store.credentials) {
if ( $Name | Where-Object { $entry.Name -like $_ }) {
$entry
}
})
foreach ($entry in $entries) {
$password = ($entry.password | ConvertTo-SecureString)
$cred = New-Object PSCredential($entry.username, $password)
[PsCustomObject]@{
Name = $entry.Name
Description = $entry.Description
Credential = $cred
}
}
}
|
PowerShellCorpus/PowerShellGallery/NubusTech.CredentialStore/1.0/public/Get-CsPassword.ps1
|
Get-CsPassword.ps1
|
<#
.SYNOPSIS
Get CredentialStore Entry Password
.DESCRIPTION
The Get-CsPassword cmdlet gets the credential password for a CredentialStore entry by name.
.PARAMETER FilePath
Specifies the path to the CredentialStore file.
.PARAMETER Name
Specifies the CredentialStore entry name of of the be retrieved. Wildcards are not permitted.
This cmdlet throws an error if no entry with that name exists.
.PARAMETER Raw
Return the Password as a standard unsecure string.
.Example
Get-CsPassword -FilePath CredentialStore.json -Name LocalServer
This command gets the password of the CredentialStore entry named LocalServer in the CredentialStore.json file.
.LINK
https://github.com/nubustech/NubusTech.CredentialStore
#>
function Get-CsPassword {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string] $Name,
[Parameter(Position = 1)]
[switch] $Raw,
[ValidateScript({
if (Test-Path $_) { $true }
else { throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' does not exist." }
})]
[Parameter(Mandatory = $false, Position = 2)]
[Alias("File")]
[string] $FilePath = (Get-CsDefaultStore)
)
$entry = Get-CsEntry -Name $Name -FilePath $FilePath
if ($entry) {
if ($Raw) {
return $entry.Credential.GetNetworkCredential().Password
}
else {
return $entry.Credential.Password
}
}
throw "Get-CsPassword : Cannot find any entry with entry name '$Name'."
}
|
PowerShellCorpus/PowerShellGallery/NubusTech.CredentialStore/1.0/public/Set-CsEntry.ps1
|
Set-CsEntry.ps1
|
<#
.SYNOPSIS
Set CredentialStore Entries
.DESCRIPTION
The Set-CsEntry cmdlet adds or updates CredentialStore entries in a CredentialStore file.
.PARAMETER FilePath
Specifies the path to the CredentialStore file.
.PARAMETER Name
Specifies the CredentialStore entry name of entry to be added or updated.
.PARAMETER Description
A description of the CredentialStore entry.
.PARAMETER Credential
Specifies the PSCredential of the CredentialStore entry.
.Example
Set-CsEntry -FilePath CredentialStore.json -Name LocalServer -Credential $cred
This command sets the CredentialStore entry named LocalServer in the CredentialStore.json file.
.LINK
https://github.com/nubustech/NubusTech.CredentialStore
#>
function Set-CsEntry {
[CmdletBinding(SupportsShouldProcess = $false)]
param(
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
[string] $Name,
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 1)]
[System.Management.Automation.Credential()]
[PSCredential] $Credential,
[Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, Position = 2)]
[string] $Description,
[ValidateScript( {
if (Test-Path $_) { $true }
else { throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' does not exist." }
})]
[Parameter(Mandatory = $false, ValueFromPipeline = $false, Position = 3)]
[Alias("File")]
[string] $FilePath = (Get-CsDefaultStore)
)
begin {
$store = Get-Content -Raw -Path $FilePath | ConvertFrom-Json
if ($store.Username -ne $(whoami) -or $store.ComputerName -ne $(hostname)) {
throw "Cannot access CredentialStore, it is encrypted for user $($store.UserName) on Computer $($store.ComputerName)"
}
}
process {
$entry = $store.credentials | Where-Object {$_.name -eq $Name}
if (-not $entry) {
$store.credentials += @{
name = $Name
description = $Description
username = $Credential.username
password = $($Credential.password | ConvertFrom-SecureString)
}
}
else {
$entry.description = $description
$entry.username = $Credential.username
$entry.password = $($Credential.password | ConvertFrom-SecureString)
}
}
end {
$store | ConvertTo-Json | Out-File -FilePath $FilePath -Force
}
}
|
PowerShellCorpus/PowerShellGallery/NubusTech.CredentialStore/1.0/public/Initialize-CsStore.ps1
|
Initialize-CsStore.ps1
|
<#
.SYNOPSIS
Creates a new CredentialStore
.DESCRIPTION
The Initialize-CsStore cmdlet create a new CredentialStore file.
.PARAMETER FilePath
Specifies the path for the new CredentialStore file.
.Example
Initialize-CsStore -FilePath CredentialStore.json
This command will create a new keysore file called CredentialStore.json.
.LINK
https://github.com/nubustech/NubusTech.CredentialStore
#>
function Initialize-CsStore {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[Alias("File")]
[string] $FilePath
)
if (Test-Path $FilePath) {
throw "File already exists, cannot overwrite"
}
ConvertTo-Json @{
UserName = $(whoami)
ComputerName = $(hostname)
CreatedDate = (Get-Date).ToString()
FileFormatVersion = "1.0"
Credentials = @()
} | Out-File -FilePath $FilePath
}
|
PowerShellCorpus/PowerShellGallery/NubusTech.CredentialStore/1.0/public/Get-CsDefaultStore.ps1
|
Get-CsDefaultStore.ps1
|
<#
.SYNOPSIS
Gets the path to the default CredentialStore
.DESCRIPTION
The Get-CsDefaultStore cmdlet gets the path to the default CredentialStore
.LINK
https://github.com/nubustech/NubusTech.CredentialStore
#>
function Get-CsDefaultStore {
return $Script:DefaultCredentialStore
}
|
PowerShellCorpus/PowerShellGallery/NubusTech.CredentialStore/1.0/public/Get-CsCredential.ps1
|
Get-CsCredential.ps1
|
<#
.SYNOPSIS
Get a CredentialStore Entry Credential
.DESCRIPTION
The Get-CsCredential cmdlet gets the credential for a CredentialStore entry by name.
.PARAMETER FilePath
Specifies the path to the CredentialStore file.
.PARAMETER Name
Specifies the CredentialStore entry name of of the be retrieved. Wildcards are not permitted.
This cmdlet throws an error if no entry with that name exists.
.Example
Get-CsCredential -FilePath CredentialStore.json -Name LocalServer
This command gets the credential of the CredentialStore entry named LocalServer in the CredentialStore.json file.
.LINK
https://github.com/nubustech/NubusTech.CredentialStore
#>
function Get-CsCredential {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string] $Name,
[ValidateScript({
if (Test-Path $_) { $true }
else { throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' does not exist." }
})]
[Parameter(Mandatory = $false, Position = 1)]
[Alias("File")]
[string] $FilePath = (Get-CsDefaultStore)
)
$entry = Get-CsEntry -Name $Name -FilePath $FilePath
if ($entry) {
return $entry.Credential
}
throw "Get-CsCredential : Cannot find any entry with entry name '$Name'."
}
|
PowerShellCorpus/PowerShellGallery/NubusTech.CredentialStore/1.0/public/Set-CsDefaultStore.ps1
|
Set-CsDefaultStore.ps1
|
<#
.SYNOPSIS
Set the path to the default CredentialStore
.DESCRIPTION
The Set-CsDefaultStore cmdlet sets the path to the default CredentialStore.
This path is not persisted across powershell sessions.
.PARAMETER FilePath
Specifies the path to the CredentialStore file.
.LINK
https://github.com/nubustech/NubusTech.CredentialStore
#>
function Set-CsDefaultStore {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[Alias("File")]
[string] $FilePath
)
$Script:DefaultCredentialStore = $FilePath
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/tests/unit/functions/Install-AWP.tests.ps1
|
Install-AWP.tests.ps1
|
InModuleScope awp {
Describe 'Install-AWP' {
$testPath = "TestDrive:\awpInstall.exe"
Set-Content $testPath -value "awpInstLLER"
BeforeEach {
Mock Copy-Item { $null }
}
Context 'General Tests' {
It 'Parameter Tests' {
Mock Test-AWPInstall {}
Mock Invoke-Command { }
{ Install-AWP -path "$TestDrive\awpInstall.exe" } | Should Not Throw
{ Install-AWP -path "$TestDrive\awpInstall.exe" -cred } | Should throw
}
}
Context 'Is Invoke-Command Called Correctly' {
it 'When AWP agent is not installed' {
Mock Test-AWPInstall {
@{
isInstalled = $false
}
}
Mock Invoke-Command { "$TestDrive\awpInstall.exe" }
Install-AWP -path "$TestDrive\awpInstall.exe" | Out-Null
Assert-MockCalled -CommandName Invoke-Command -Exactly 3 -Scope It
}
it 'When AWP agent is installed' {
Mock Test-AWPInstall {
@{
isInstalled = $true
}
}
Mock Start-Process {}
Install-AWP -path "$TestDrive\awpInstall.exe" | Out-Null
Assert-MockCalled -CommandName Start-Process -Exactly 0 -Scope It
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/tests/unit/functions/Test-AWPInstall.tests.ps1
|
Test-AWPInstall.tests.ps1
|
InModuleScope awp {
Describe 'Test-AWPInstall' {
Mock New-PSSession { }
Context 'General Tests' {
Mock Invoke-Command {
@{
UninstallString = '{23478236378hjdfgsdfg78dftsd}'
DisplayVersion = '6.76.5'
}
}
It 'Parameter Tests' {
{ Test-AWPInstall } | Should Not Throw
{ Test-AWPInstall -cred } | Should throw
}
}
Context 'AWP Agent Installed' {
Mock Invoke-Command {
@{
UninstallString = '/x {23478236378hjdfgsdfg78dftsd}'
DisplayVersion = '6.76.5'
}
}
It 'Un-Install string and DisplayVersion exists' {
(Test-AWPInstall).isInstalled | Should Be $true
}
}
Context 'AWP Agent Not Installed' {
Mock Invoke-Command { }
It 'Un-Install string and DisplayVersion does not exists' {
(Test-AWPInstall).isInstalled | Should Be $false
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/tests/unit/functions/Uninstall-AWP.tests.ps1
|
Uninstall-AWP.tests.ps1
|
InModuleScope awp {
Describe 'Uninstall-AWP' {
BeforeEach {
Mock Invoke-Command {}
}
Context 'General Tests' {
It 'Parameter Tests' {
Mock Test-AWPInstall {}
{ Uninstall-AWP } | Should Not Throw
{ Uninstall-AWP -cred } | Should throw
}
}
Context 'Is Invoke-Command Called Correctly' {
it 'When AWP agent is not installed' {
Mock Test-AWPInstall {
@{
isInstalled = $false
}
}
UnInstall-AWP | Out-Null
Assert-MockCalled -CommandName Invoke-Command -Exactly 0 -Scope It
Assert-MockCalled -CommandName Test-AWPInstall -Exactly 1 -Scope It
}
it 'When AWP agent is installed' {
$script:i = 1
Mock Test-AWPInstall {
if ($script:i -ge 2)
{
@{
isInstalled = $false
}
}
else
{
@{
isInstalled = $true
}
}
$script:i++
}
UnInstall-AWP | Out-Null
Assert-MockCalled -CommandName Invoke-Command -Exactly 1 -Scope It
Assert-MockCalled -CommandName Test-AWPInstall -Exactly 2 -Scope It
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/tests/unit/functions/Test-AWPPreReq.tests.ps1
|
Test-AWPPreReq.tests.ps1
|
InModuleScope awp {
Describe 'Test-AWPPreReq' {
Mock New-CimInstance { }
Context 'General Tests' {
Mock Get-CimInstance {
[PSCustomObject]@{
version = [version]8.1
}
} -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' }
Mock Invoke-Command {
[psCustomObject]@{
release = 394802
}
}
It 'Parameter Tests' {
{ Test-AWPPreReq } | Should Not Throw
{ Test-AWPPreReq -cred } | Should throw
}
}
Context 'AWP Agent PreReq Passes' {
Mock Get-CimInstance {
[PSCustomObject]@{
version = [version]8.1
}
} -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' }
Mock Invoke-Command {
[psCustomObject]@{
release = 394802
}
}
It '.net relase and OS version correct' {
(Test-AWPPreReq).preReqPass | Should Be $true
}
}
Context 'AWP Agent PreReq Fails' {
It '.net release incorrect' {
Mock Get-CimInstance {
[PSCustomObject]@{
version = [version]6.1.0
}
} -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' }
Mock Invoke-Command {
[psCustomObject]@{
release = 10000
}
}
(Test-AWPPreReq).preReqPass | Should Be $false
}
It 'OS version incorrect' {
Mock Get-CimInstance { } -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' }
Mock Invoke-Command {
[psCustomObject]@{
release = 394802
}
}
(Test-AWPPreReq).preReqPass | Should Be $false
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/tests/lint/scriptAnalyer.tests.ps1
|
scriptAnalyer.tests.ps1
|
$here = (Split-Path -Parent $MyInvocation.MyCommand.Path).Replace('tests\lint', '')
$scriptsModules = Get-ChildItem $here -Include *.psd1, *.psm1, *.ps1 -Exclude *.tests.ps1 -Recurse
Describe "Enviroment - Testing there is something to test and CMDLETS available." {
Context "Checking files to test exist and Invoke-ScriptAnalyzer cmdLet is available" {
It "Checking files exist to test." {
$scriptsModules.count | Should Not Be 0
}
It "Checking Invoke-ScriptAnalyzer exists." {
{ Get-Command Invoke-ScriptAnalyzer -ErrorAction Stop } | Should Not Throw
}
}
}
Describe "Script\Module - Testing all scripts and modules" {
$scriptAnalyzerRules = Get-ScriptAnalyzerRule
forEach ($scriptModule in $scriptsModules) {
switch -wildCard ($scriptModule) {
'*.psm1' { $typeTesting = 'Module' }
'*.ps1' { $typeTesting = 'Script' }
'*.psd1' { $typeTesting = 'Manifest' }
}
Context "Checking $typeTesting – $($scriptModule) - conforms to Script Analyzer Rules" {
forEach ($scriptAnalyzerRule in $scriptAnalyzerRules) {
It "Script Analyzer Rule $scriptAnalyzerRule" {
(Invoke-ScriptAnalyzer -Path $scriptModule -IncludeRule $scriptAnalyzerRule).count | Should Be 0
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/classes/models/AWPPreReq.ps1
|
AWPPreReq.ps1
|
class AWPPreReq
{
[string] $computerName
[int] $dotNetFourFrameWorkRelease
[version] $dotNetFourFrameWorkVersion
[version] $osVersion
[datetime] $LogTime = (Get-Date)
[bool] $preReqPass
#Constructor Overload All Values
AWPPreReq (
[string] $computerName,
[string] $dotNetFourFrameWorkRelease,
[version] $osVersion
){
$this.computerName = $computerName
$this.dotNetFourFrameWorkRelease = $dotNetFourFrameWorkRelease
$this.osVersion = $osVersion
$this.getdotNetFourFrameWorkVersion()
$this.getPreReqPass()
}
[void] getdotNetFourFrameWorkVersion()
{
$this.dotNetFourFrameWorkVersion = switch -regex ($this.dotNetFourFrameWorkRelease)
{
'378389' { [Version]'4.5' }
'378675|378758' { [Version]'4.5.1' }
'379893' { [Version]'4.5.2' }
'393295|393297' { [Version]'4.6' }
'394254|394271' { [Version]'4.6.1' }
'394802|394806' { [Version]'4.6.2' }
{$_ -gt 394806} { [Version]'100' }
}
}
[void] getPreReqPass()
{
if(($this.dotNetFourFrameWorkVersion -ge [version]'4.6.1') -and ($this.osVersion -ge [Version]6.1))
{
$this.preReqPass = $true
}
else
{
$this.preReqPass = $false
}
}
[void] setLogTime()
{
$this.LogTime = Get-Date
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/classes/models/AWPInstall.ps1
|
AWPInstall.ps1
|
class AWPInstall
{
[string] $computerName
[string] $uninstallString
[bool] $isInstalled = $false
[version] $version
[datetime] $LogTime = (Get-Date)
#Constructor Overload All Values
AWPInstall (
[string] $computerName,
[string] $uninstallString,
[version] $version
){
$this.computerName = $computerName
$this.uninstallString = $uninstallString
$this.Version = $version
$this.setIsInstalled()
}
[void] setIsInstalled()
{
if($this.uninstallString -and $this.version)
{
$this.isInstalled = $true
}
}
[void] setLogTime()
{
$this.LogTime = Get-Date
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/functions/Test-AWPPreReq.ps1
|
Test-AWPPreReq.ps1
|
function Test-AWPPreReq
{
<#
.Synopsis
Checks a computer has the Pre-Reqs to install the Autotask WorkPlace Agent.
.DESCRIPTION
Checks a computer has the Pre-Reqs to install the Autotask WorkPlace Agent. Looks at Windows Version and .Net framework version.
.EXAMPLE
Test-AutoTaskWorkPlacePreReq -computerName 'computerOne', 'computerTwo'
.EXAMPLE
'computerOne', 'computerTwo' | Test-AutoTaskWorkPlacePreReq -credential Get-Credential
.NOTES
Written by Ben Taylor
Version 1.0, 17.11.2016
Maybe should have been a OVT pester test
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType('AWPPreReq')]
Param
(
[Parameter(Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidateNotNullOrEmpty()]
$computerName = $env:COMPUTERNAME,
[Parameter(Mandatory = $false, Position = 1)]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
Begin
{
$cimCommonParams = @{
ErrorAction = 'Stop'
}
If ($PSBoundParameters['Credential'])
{
$cimCommonParams.Credential = $Credential
}
}
Process
{
foreach($computer in $computerName)
{
try
{
$cimCommonParams.ComputerName = $computer
$dotNetRelease = Invoke-Command @cimCommonParams -scriptBlock {
Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full'
}
Write-Verbose 'Getting connection protocol'
try
{
Test-WSMan @cimCommonParams | Out-Null
$ProtocolAuto = 'WsMan'
}
catch
{
$ProtocolAuto = 'DCOM'
}
$cimSession = New-CimSession @cimCommonParams -SessionOption (New-CimSessionOption -Protocol $ProtocolAuto)
$osVersion = Get-CimInstance Win32_OperatingSystem -CimSession $cimSession -ErrorAction Stop | Select-Object -ExpandProperty Version
[AWPPreReq]::new($computer, ($dotNetRelease | Select-Object -ExpandProperty Release), $osVersion)
}
catch
{
Write-Error "$computer - $_"
}
finally
{
if($null -ne $cimSession)
{
Remove-CimSession $cimSession -ErrorAction SilentlyContinue
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/functions/Test-AWPInstall.ps1
|
Test-AWPInstall.ps1
|
function Test-AWPInstall
{
<#
.Synopsis
Checks a computer to see if the Autotask WorkPlace Agent is installed.
.DESCRIPTION
Checks a computer to see if the Autotask WorkPlace Agent is installed. It looks for the uninstall registry key.
.EXAMPLE
Test-AWPInstall -computerName 'computerOne', 'computerTwo'
.EXAMPLE
'computerOne', 'computerTwo' | Test-AWPInstall -credential Get-Credential
.NOTES
Written by Ben Taylor
Version 1.0, 17.11.2016
Maybe should have been a OVT pester test
#>
[CmdletBinding()]
[OutputType('AWPPreReq')]
Param
(
[Parameter(Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidateNotNullOrEmpty()]
$computerName = $env:COMPUTERNAME,
[Parameter(Mandatory = $false, Position = 1)]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
Begin
{
$sessionCommonParams = @{
ErrorAction = 'Stop'
}
If ($PSBoundParameters['Credential'])
{
$sessionCommonParams.Credential = $Credential
}
}
Process
{
foreach($computer in $computerName)
{
try
{
$sessionCommonParams.ComputerName = $computer
$soonRAgent = Invoke-Command @sessionCommonParams -scriptBlock {
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object { $_.displayName -eq 'Soonr Desktop Agent' -and $_.Installed }
}
[AWPInstall]::new($computer, $soonRAgent.UninstallString , $soonRAgent.DisplayVersion)
}
catch
{
Write-Error "$computer - $_"
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/functions/Install-AWP.ps1
|
Install-AWP.ps1
|
function Install-AWP
{
<#
.Synopsis
Installs the SoonR Agent on remote and local computers
.DESCRIPTION
Installs the SoonR Agent on remote and local computers. Assumes C: is the system drive.
.EXAMPLE
Install-AWP -computername 'computer-one' -path 'c:\install\soonRInstaller.exe'
.EXAMPLE
'computer-one', 'computer-two' | Install-AWP -path 'c:\install\soonRInstaller.exe'
.NOTES
Written by Ben Taylor
Version 1.0, 13.11.2016
#>
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Low')]
[OutputType()]
Param
(
[Parameter(Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidateNotNullOrEmpty()]
[string[]]
$computerName = $env:computername,
[Parameter(Mandatory=$true, Position=1)]
[ValidateScript({ Test-Path $_ })]
[string]
$path,
[Parameter(Mandatory=$false)]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
Begin
{
$commonSessionParams = @{
ErrorAction = 'Stop'
}
If ($PSBoundParameters['Credential'])
{
$commonSessionParams.Credential = $Credential
}
}
Process
{
forEach ($computer in $computerName)
{
try
{
if((Test-AWPInstall -ComputerName $computer @commonSessionParams).isInstalled -eq $false)
{
Write-Verbose "[$(Get-Date -Format G)] - $computer - AWP not installed so trying to install"
if ($pscmdlet.ShouldProcess($computer, 'Install-AWP'))
{
Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating remote session"
$psSession = New-PSSession -ComputerName $computer @commonSessionParams
$remoteInstallerpath = Invoke-Command -Session $psSession -ScriptBlock {
Join-Path ([environment]::GetEnvironmentVariable('temp','machine')) soonRAgent.exe
} -ErrorAction Stop
Write-Verbose "[$(Get-Date -Format G)] - $computer - Copying Installer"
Copy-Item -Path $path -Destination ($remoteInstallerpath -replace [regex]::Escape('c:\'), "\\$computer\C$\") -Force @commonSessionParams
Write-Verbose "[$(Get-Date -Format G)] - $computer - Installing SoonR agent"
Invoke-Command -Session $psSession -ScriptBlock {
$args = @(
'/install'
'/quiet'
'/norestart'
)
Start-Process $USING:remoteInstallerpath -ArgumentList $args -Wait -Verbose
} -ErrorAction Stop
}
}
else
{
Write-Verbose "[$(Get-Date -Format G)] - $computer - AWP allready installed. Skipping on this computer"
}
}
catch
{
Write-Error $_
}
finally
{
Write-Verbose "[$(Get-Date -Format G)] - $computer - Tidying up install files\sessions if needed"
if($null -ne $psSession)
{
try
{
Invoke-Command -Session $pssession -ScriptBlock {
# Check if file exists and if so remove
if(Test-Path $USING:remoteInstallerpath)
{
Remove-Item $USING:remoteInstallerpath -force -Confirm:$false -WhatIf:$false
}
} -ErrorAction Stop
}
catch
{
Write-Error $_
}
Remove-PSSession $psSession -Confirm:$false -WhatIf:$false
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/awp/1.0.0.0/functions/Uninstall-AWP.ps1
|
Uninstall-AWP.ps1
|
function Uninstall-AWP
{
<#
.Synopsis
Un-installs an AWP agent on remote computers.
.DESCRIPTION
Un-installs an AWP agent on remote computers.
.EXAMPLE
Uninstall-AWP -computerName 'computer1', 'computer2' -Verbose
.NOTES
Written by Ben Taylor
Version 1.0, 18.11.2016
#>
[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Low')]
[OutputType()]
Param (
[Parameter(Mandatory = $false, ValueFromPipeline=$True, valuefrompipelinebypropertyname=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[Alias('IPAddress', 'Name')]
[string[]]
$computerName = $env:COMPUTERNAME,
[Parameter()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
Begin
{
$commonSessionParams = @{
ErrorAction = 'Stop'
}
If ($PSBoundParameters['Credential'])
{
$commonSessionParams.Credential = $Credential
}
}
Process
{
forEach ($computer in $computerName)
{
$commonSessionParams.Computer = $computer
try
{
Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session"
$psSession = New-PSSession @commonSessionParams
Write-Verbose "[$(Get-Date -Format G)] - $computer - Checking if OMS is Installed"
$awpInstall = Test-AWPInstall @commonSessionParams
if($awpInstall.isInstalled -eq $true)
{
Write-Verbose "[$(Get-Date -Format G)] - $computer - OMS is installed so will try to uninstall"
If ($Pscmdlet.ShouldProcess($computer, 'Uninstall OMS Agent'))
{
Invoke-Command -Session $psSession -ScriptBlock {
$uninstallExe = ($USING:awpInstall.uninstallString).ToLower().Replace('"', '').Replace("/uninstall", "").trim()
Start-Process $uninstallExe -ArgumentList '/uninstall /quiet' -Wait
} -ErrorAction Stop
$awpInstallStatus = Test-AWPInstall @commonSessionParams
if($awpInstallStatus.isInstalled -eq $false)
{
Write-Verbose "[$(Get-Date -Format G)] - $computer - OMS uninstalled correctly"
}
else
{
Write-Error "[$(Get-Date -Format G)] - $computer - OMS didn't uninstall correctly based registry check"
}
}
}
else
{
Write-Verbose "[$(Get-Date -Format G)] - $computer - OMS not installed so skipping uninstall process"
}
}
catch
{
Write-Error $_
}
finally
{
if($null -ne $psSession)
{
Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session"
Remove-PSSession $psSession -WhatIf:$false -Confirm:$false
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/posh-dcos/0.0.2/BuildPackage.ps1
|
BuildPackage.ps1
|
.\tools\NuGet.exe pack posh-dcos.nuspec
|
PowerShellCorpus/PowerShellGallery/posh-dcos/0.0.2/posh-dcos.ps1
|
posh-dcos.ps1
|
function PascalName($name){
$parts = $name.Split(" ")
for($i = 0 ; $i -lt $parts.Length ; $i++){
$parts[$i] = [char]::ToUpper($parts[$i][0]) + $parts[$i].SubString(1).ToLower();
}
$parts -join ""
}
function GetHeaderBreak($headerRow, $startPoint=0){
$i = $startPoint
while( $i + 1 -lt $headerRow.Length)
{
if ([char]::IsWhiteSpace($headerRow[$i]) -and [char]::IsWhiteSpace($headerRow[$i+1])){
return $i
break
}
$i += 1
}
return -1
}
function GetHeaderNonBreak($headerRow, $startPoint=0){
$i = $startPoint
while( $i + 1 -lt $headerRow.Length)
{
if (-not [char]::IsWhiteSpace($headerRow[$i])){
return $i
break
}
$i += 1
}
return -1
}
function GetColumnInfo($headerRow){
$lastIndex = 0
$i = 0
while ($i -lt $headerRow.Length -and $lastIndex -ge 0){
$i = GetHeaderBreak $headerRow $lastIndex
if ($i -lt 0){
$name = $headerRow.Substring($lastIndex)
New-Object PSObject -Property @{ HeaderName = $name; Name = PascalName $name; Start=$lastIndex; End=-1}
break
} else {
$name = $headerRow.Substring($lastIndex, $i-$lastIndex)
$temp = $lastIndex
$lastIndex = GetHeaderNonBreak $headerRow $i
New-Object PSObject -Property @{ HeaderName = $name; Name = PascalName $name; Start=$temp; End=$lastIndex}
}
}
}
function ParseRow($row, $columnInfo) {
$values = @{}
$columnInfo | ForEach-Object {
if ($_.End -lt 0) {
$len = $row.Length - $_.Start
} else {
$len = $_.End - $_.Start
}
$values[$_.Name] = $row.SubString($_.Start, $len).Trim()
}
New-Object PSObject -Property $values
}
function ConvertFrom-Cli(){
begin{
$positions = $null;
}
process {
if($positions -eq $null) {
# header row => determine column positions
$positions = GetColumnInfo -headerRow $_ #-propertyNames $propertyNames
} else {
# data row => output!
ParseRow -row $_ -columnInfo $positions
}
}
end {
}
}
#
# .SYNOPSIS
#
# Complete parameters and arguments to dcos cli
#
function DcosExeCompletion
{
param($wordToComplete, $commandAst)
$commandTree = Get-CompletionPrivateData -Key DcosExeCompletionCommandTree
if ($null -eq $commandTree)
{
Set-Alias -Name nct -Value New-CommandTree
$commandTree = & {
nct auth "Authenticate to DC/OS cluster" {
nct -Argument 'login' "log in"
nct -Argument 'logout' "log out"
nct -Argument '--help' "help"
nct -Argument '--info' "info"
}
nct config "Manage the DC/OS configuration file" {
nct set "set <name> <value>"
nct show "show [<name>]" # TODO - add completion of names
nct unset "unset <name>" # TODO - add completion of names
nct validate "validate"
nct -Argument '--help' "help"
nct -Argument '--info' "info"
}
nct help "Display help information about DC/OS"
nct job "Deploy and manage jobs in DC/OS" {
nct add "add <job-file>"
nct remove "remove <job-id> [--stop-current-job-runs]" {
nct -Argument "--stop-current-job-runs" "stop-current-job-runs"
# TODO - complete ids, add switch
}
nct show "show <job-id>"
nct update "update <job-file>"
nct kill "kill <job-id> [run-id][--all]" {
nct -Argument "--all" "all"
}
nct run "run <job-id>"
nct list "list [--json]" {
nct -Argument "--json" "json"
}
nct schedule "schedule" {
nct add "add <job-id> <schedule-file>"
nct show "show <job-id> [--json]" {
nct -Argument "--json" "json"
}
nct remove "remove <job-id> <schedule-id>"
nct update "update <job-id> <schedule-file>"
}
nct show "show" {
nct runs "runs <job-id> [--run-id <run-id>][--json][--q]" {
nct -Argument "--run-id" "run-id"
nct -Argument "--json" "json"
nct -Argument "--q" "q"
}
}
nct history "history <job-id> [--json][--show-failures]" {
nct -Argument "--json" "json"
nct -Argument "--show-failures" "show-failures"
}
nct -Argument '--help' "help"
nct -Argument '--version' "version"
nct -Argument '--config-schema' "config schema"
nct -Argument '--info' "info"
}
nct marathon "Deploy and manage applications to DC/OS" {
nct -Argument '--help' "help"
nct -Argument '--config-schema' "config schema"
nct -Argument '--info' "info"
nct about "about"
nct app "application" {
nct add "add [<app-resource>]"
nct list "list" {
nct -Argument '--json' "json"
}
nct remove "remove" {
nct -Argument '--force' "force"
nct {
param($wordToComplete, $commandAst)
dcos marathon app list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "AppId: $($_.Id)"}
}
}
nct restart "restart" {
nct -Argument '--force' "force"
nct {
param($wordToComplete, $commandAst)
dcos marathon app list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "AppId: $($_.Id)"}
}
}
nct show "show" {
nct -Argument '--app-version=' "appversion" # TODO complete version number
nct {
param($wordToComplete, $commandAst)
dcos marathon app list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "AppId: $($_.Id)"}
}
}
nct start "start [--force] <app-id> [<instances>]" {
nct -Argument '--force' "force"
nct {
param($wordToComplete, $commandAst)
dcos marathon app list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "AppId: $($_.Id)"}
}
}
nct stop "stop" {
nct -Argument '--force' "force"
nct {
param($wordToComplete, $commandAst)
dcos marathon app list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "AppId: $($_.Id)"}
}
}
nct kill "kill" {
nct -Argument '--scale' "scale"
nct -Argument '--host=' "host" ## TODO complete host
nct {
param($wordToComplete, $commandAst)
dcos marathon app list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "AppId: $($_.Id)"}
}
}
nct update "update [--force] <app-id> [<properties>...]" {
nct -Argument '--force' "force"
nct {
param($wordToComplete, $commandAst)
dcos marathon app list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "AppId: $($_.Id)"}
}
}
nct version "version" {
nct list "list [--max-count=<maxcount>] <app-id>" {
nct -Argument '--max-count=' "max-count"
nct {
param($wordToComplete, $commandAst)
dcos marathon app list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "AppId: $($_.Id)"}
}
}
}
}
nct deployment "deployment" {
nct list "list" {
nct -Argument "--json" "json"
}
nct rollback "rollback" {
nct {
param($wordToComplete, $commandAst)
dcos marathon deployment list | ConvertFrom-cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "DeploymentId: $($_.Id)"}
}
}
nct stop "stop" {
nct {
param($wordToComplete, $commandAst)
dcos marathon deployment list | ConvertFrom-cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "DeploymentId: $($_.Id)"}
}
}
nct watch "watch" {
nct -Argument '--max-count=' "max-count"
nct -Argument '--interval=' "interval"
nct {
param($wordToComplete, $commandAst)
dcos marathon deployment list | ConvertFrom-cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "DeploymentId: $($_.Id)"}
}
}
}
nct group "group"{
nct add "add [<group-resource>]"
nct list "list" {
nct -Argument '--json' "json"
}
nct scale "scale" {
nct -Argument '--force' "force"
nct {
param($wordToComplete, $commandAst)
dcos marathon group list | ConvertFrom-cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "GroupId: $($_.Id)"}
}
}
nct show "show" {
nct -Argument '--group-version=' "group-version" ## TODO complete version number
nct {
param($wordToComplete, $commandAst)
dcos marathon group list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "GroupId: $($_.Id)"}
}
}
nct remove "remove" {
nct -Argument '--force' "force"
nct {
param($wordToComplete, $commandAst)
dcos marathon group list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "AppId: $($_.Id)"}
}
}
nct update "update [--force] <group-id> [<properties>...]" {
nct -Argument '--force' "force"
nct {
param($wordToComplete, $commandAst)
dcos marathon group list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "GroupId: $($_.Id)"}
}
}
}
# TODO add pod-id completion
nct pod "pod"{
nct add "add [<pod-resource>]"
nct kill "kill <pod-id> [<instance-ids>...]"
nct list "list [--json]" {
nct -Argument "--json" "json"
}
nct remove "remove [--force] <pod-id>" {
nct -Argument "--force" "force"
}
nct show "show <pod-id>"
nct update "update [--force] <pod-id>" {
nct -Argument "--force" "force"
}
}
nct task "task" {
nct list "list [--json]" {
nct -Argument "--json" "json"
}
nct stop "stop [--wipe] <task-id>" {
nct -Argument '--wipe' "wipe"
nct {
param($wordToComplete, $commandAst)
dcos marathon task list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "TaskId: $($_.Id)"}
}
}
nct show "show <task-id>" {
nct {
param($wordToComplete, $commandAst)
dcos marathon task list | ConvertFrom-Cli | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object { New-CompletionResult $_.Id -ToolTip "TaskId: $($_.Id)"}
}
}
}
}
nct node "Administer and manage DC/OS cluster nodes" {
nct -Argument '--help' "help"
nct -Argument '--info' "info"
nct -Argument '--json' "json"
nct log "log [--follow --lines=N --leader --master --mesos-id=<mesos-id> --slave=<slave-id>]"{
nct -Argument '--follow' "follow"
nct -Argument '--lines=' "lines=N"
nct -Argument '--master' "master"
nct -Argument '--mesos-id' "mesos-id=<mesos-id>"
nct -Argument '--slave' "slave-id=<slave-id>"
}
nct ssh " ssh [--option SSHOPT=VAL ...] [--config-file=<path>] [--user=<user>] [--master-proxy] (--leader | --master | --mesos-id=<mesos-id> | --slave=<slave-id>) [<command>]" {
nct -Argument '--option' "options SSHOPT=VAL..."
nct -Argument '--config-file=' "config-file=<path>"
nct -Argument '--user=' "user=<user>"
nct -Argument '--master-proxy' "master-proxy"
nct -Argument '--leader' "leader"
nct -Argument '--master' "master"
nct -Argument '--mesos-id' "mesos-id=<mesos-id>"
nct -Argument '--slave' "slave-id=<slave-id>"
}
nct diagnostics "diagnostics" {
nct create "create (<nodes>)..." #TODO complete nodes
nct delete "delete <bundle>" #TODO complete bundle
nct download "download <bundle> [--location=<location>]" {
nct -Argument "--location=" "location=<location>"
}
nct -Argument "--list" "list"
nct -Argument "--status" "status"
nct -Argument "--cancel" "cancel"
nct -Argument '--json' "json"
}
}
nct package "Install and manage DC/OS software packages" {
nct -Argument '--help' "help"
nct -Argument '--config-schema' "config schema"
nct -Argument '--info' "info"
nct decribe "describe [--app --cli --config] [--render] [--package-versions] [--options=<file>] [--package-version=<package-version>] <package-name>" {
nct -Argument "--app" "app"
nct -Argument "--cli" "cli"
nct -Argument "--config" "config"
nct -Argument "--render" "render"
nct -Argument "--package-versions" "package-versions"
nct -Argument "--options=" "options=<file>"
nct -Argument "--package-version=" "package-version=<package-version>"
#TODO complete package-name
}
nct install "install [--cli | [--app --app-id=<app-id>]] [--package-version=<package-version>] [--options=<file>] [--yes] <package-name>" {
nct -Argument '--cli' "cli"
nct -Argument '--app' "app"
nct -Argument '--app-id=' "app-id=<app-id>"
nct -Argument '--package-version=' "package-version=<package-version>"
nct -Argument '--options=' "options=<file>"
nct -Argument '--yes' "yes"
#TODO complete package-name
}
nct list "list [--json --app-id=<app-id> --cli <package-name>]" {
nct -Argument '--json' "json"
nct -Argument '--cli' "cli"
nct -Argument '--app-id=' "app-id=<app-id>"
#TODO complete package-name
}
nct search "search [--json <query>]" {
nct -Argument '--json' "json"
}
nct repo {
nct add "add [--index=<index>] <repo-name> <repo-url>" {
nct -Argument "--index=" "index=<index>"
}
nct remove "remove <repo-name>" # TODO complete repo-name
nct list "list [--json]" {
nct -Argument '--json' "json"
}
}
nct uninstall "uninstall [--cli | [--app --app-id=<app-id> --all]] <package-name>" {
nct -Argument '--cli' "cli"
nct -Argument '--app' "app"
nct -Argument '--app-id=' "app-id=<app-id>"
nct -Argument '--all' "all"
#TODO complete package-name
}
nct update "update"
}
nct service "Manage DC/OS services"{
nct -Argument '--help' "help"
nct -Argument '--info' "info"
nct -Argument '--completed' "completed"
nct -Argument '--inactive' "inactive"
nct -Argument '--json' "json"
nct log "log [--follow --lines=N --ssh-config-file=<path>] <service> [<file>]"{
nct -Argument '--follow' "follow"
nct -Argument '--lines=' "lines=N"
nct -Argument '--ssh-config-file' "ssh-config-file=<path>"
# TODO complete service
# TODO complete file
}
nct shutdown "shutdown <service-id>" # TODO complete service-id
}
nct task "Manage DC/OS tasks" {
nct -Argument '--help' "help"
nct -Argument '--info' "info"
nct -Argument '--completed' "completed"
nct -Argument '--json' "json"
nct log "log" {
nct -Argument '--completed' "--completed"
nct -Argument '--follow' "--follow"
nct -Argument '--lines=' "--lines=N"
nct {
param($wordToComplete, $commandAst)
# handle output with task ids in "===>.... <===" form (with other lines interspersed)
dcos task ls | `
Where-Object { $_.StartsWith("===>")} | `
ForEach-Object {$_.SubString(5, $_.IndexOf("<===", 7) - 6)} | `
Where-Object { $_ -like "$wordToComplete*" } | `
ForEach-Object { New-CompletionResult $_ -ToolTip "TaskId: $_"}
}
# TODO handle file completion
}
nct ls "ls [--long --completed] [<task>] [<path>]" {
nct -Argument "--long" "--long"
nct -Argument "--completed" "--completed"
nct {
param($wordToComplete, $commandAst)
# handle output with task ids in "===>.... <===" form (with other lines interspersed)
dcos task ls | `
Where-Object { $_.StartsWith("===>")} | `
ForEach-Object {$_.SubString(5, $_.IndexOf("<===", 7) - 6)} | `
Where-Object { $_ -like "$wordToComplete*" } | `
ForEach-Object { New-CompletionResult $_ -ToolTip "TaskId: $_"}
}
# TODO handle path completion
}
}
}
Set-CompletionPrivateData -Key DcosExeCompletionCommandTree -Value $commandTree
}
Get-CommandTreeCompletion $wordToComplete $commandAst $commandTree
}
Register-ArgumentCompleter `
-Command 'dcos' `
-Native `
-Description 'Complete arguments to dcos.exe' `
-ScriptBlock $function:DcosExeCompletion
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/CommonFunctions.ps1
|
CommonFunctions.ps1
|
function Set_Type {
param(
[Parameter(ValueFromPipeline=$true)]
[psobject[]]$InputObject,
[string]$TypeName
)
process {
foreach ($object in $InputObject) {
if ($TypeName) {
$object.psobject.TypeNames.Insert(0, $TypeName)
}
$object
}
}
}
function Invoke-SessionCommand {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ScriptBlock]$ScriptBlock,
[Parameter()]
[Object[]]$ArgumentList,
[Parameter()]
[System.Management.Automation.Runspaces.PSSession]$Session
)
if ($Session) {
Write-Verbose "Executing remotely from '$($Session.ComputerName)'.."
Invoke-Command -Session $Session -ArgumentList $ArgumentList -ScriptBlock $ScriptBlock |
Add-Member -NotePropertyName Session -NotePropertyValue $Session -Force -PassThru
} else {
Write-Verbose 'Executig locally..'
Invoke-Command -ArgumentList $ArgumentList -ScriptBlock $ScriptBlock
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/CommonAliases.ps1
|
CommonAliases.ps1
|
# IISAdministration and WebAdministration compatible aliases
New-Alias -Name Test-WebConfigFile -Value Test-PSWebConfig -Scope Script
# Common aliases for application config scenarios
New-Alias -Name Get-PSAppConfig -Value Get-PSWebConfig -Scope Script
New-Alias -Name Test-PSAppConfig -Value Test-PSWebConfig -Scope Script
New-Alias -Name Decrypt-PSWebConfig -Value Unprotect-PSWebConfig -Scope Script
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSWebConfig/Test-PSWebConfig.ps1
|
Test-PSWebConfig.ps1
|
<#
.SYNOPSIS
Tests all URI and ConnectionStrings from web or application configuration.
.DESCRIPTION
The cmdlet fetches all ConnectionString and service endpoint URIs
from a configuration xml and executes a test against them on a
local or remote machine.
If -IncludeAppSettings switch is defined, it will include any URI or
ConnectionStrings to the tests.
.PARAMETER InputObject
Mandatory - Parameter to pass a PSWebConfig object
.PARAMETER Session
Optional - PSSession to execute configuration test
.PARAMETER IncludeAppSettings
Optional - Switch to include URIs and ConnectionStrings from appSettings
sections
.EXAMPLE
Get-PSWebConfig -Path 'c:\intepub\wwwroot\testapp\' | Test-PSWebConfig
.EXAMPLE
Get-WebSite | Get-PSWebConfig -Recurse | Test-PSWebConfig
#>
function Test-PSWebConfig {
[CmdletBinding(DefaultParameterSetName="FromPipeLine")]
param(
[Parameter(
ParameterSetName="FromPipeLine",
ValueFromPipeLine=$true,
Position=0,
Mandatory=$true)]
[psobject[]]$ConfigXml,
[switch]$IncludeAppSettings,
[System.Management.Automation.Runspaces.PSSession]$Session
)
process {
Write-Verbose "Executing Test-PSWebConfig"
if (-Not $ConfigXml.configuration) {
Write-Verbose "InputObject is not a valid XML configuration, trying to get config XML."
$ConfigXml = Get-PSWebConfig -InputObject $ConfigXml
}
Get-PSUri -ConfigXml $ConfigXml -IncludeAppSettings:$IncludeAppSettings |
Test-PSUri -Session $Session
Get-PSConnectionString -ConfigXml $ConfigXml -IncludeAppSettings:$IncludeAppSettings |
Test-PSConnectionString -Session $Session
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSWebConfig/Unprotect-PSWebConfig.ps1
|
Unprotect-PSWebConfig.ps1
|
<#
.SYNOPSIS
Decrypts and saves inplace a web.config file
.DESCRIPTION
Takes a Path or a WebAdministration object as an input, creates a
backup of the original file and overrides the configuration with its
decrypted version.
The cmdlet prompts for clarification on the override, unless -Confirm
is set to false.
.PARAMETER InputObject
Mandatory - Parameter to pass the Application or WebSite from pipeline
.PARAMETER Path
Mandatory - Parameter to pass the path for the target application
.PARAMETER Recurse
Optional - Switch to look for multiple web.config files in sub-folders for
web applications
.PARAMETER Confirm
Optional - Boolean to disable override confirmation (default -Confirm:$true)
.PARAMETER Session
Optional - PSSession to execute the action
.EXAMPLE
Unprotect-PSWebConfig -Path 'c:\intepub\wwwroot\testapp\'
.EXAMPLE
$server1 = New-PSSession 'server1.local.domain'
Unprotect-PSWebConfig -Path 'c:\intepub\wwwroot\testapp\' -Session $server1
.EXAMPLE
Get-WebSite | Unprotect-PSWebConfig
#>
function Unprotect-PSWebConfig {
[CmdletBinding(DefaultParameterSetName="FromPipeLine")]
param(
[Parameter(ParameterSetName="FromPipeLine",Position=0)]
[Parameter(ValueFromPipeLine=$true)]
[psobject[]]$InputObject,
[Parameter(ParameterSetName="FromPath",Position=0,Mandatory=$true)]
[Alias('physicalPath')]
[string]$Path,
[switch]$Recurse,
[bool]$Confirm=$true,
[System.Management.Automation.Runspaces.PSSession]$Session
)
process {
Write-Verbose "Executing Unprotect-PSWebConfig"
if ($Path) {
Write-Verbose "Processing by Path"
$InputObject = New-Object -TypeName PsObject -Property @{
physicalPath = $Path
Session = $Session
}
}
if ($InputObject) {
Write-Verbose "Processing by InputObject"
foreach ($entry in $InputObject) {
# Setting Remote Session
$EntrySession = $entry.Session
if ($Session) {
Write-Verbose "Overriding session from -Session Parameter"
$EntrySession = $Session
}
elseif ($entry | Get-Member -Name RunspaceId) {
Write-Verbose "Getting Session from RunspaceId '$($entry.RunspaceId)'"
$EntrySession = Get-PSSession -InstanceId $entry.RunspaceId
}
Write-Verbose "Getting config files..."
$configs = $entry | Get-PSWebConfig -AsFileInfo -Recurse:$Recurse -Session:$EntrySession
foreach ($config in $configs) {
$configFile = $config.FullName
$backupFile = [string]::Join('.',@($configFile,((Get-Date -Format s) -replace ':','-'),'config'))
$decryptedConfig = Get-PSWebConfig -AsText -Path $configFile -Session:$EntrySession
$BackupAndOverride = {
param(
[string]$configFile,
[string]$backupFile,
[string]$decryptedConfig,
[bool]$Confirm
)
Write-Verbose "Creating backup to '$backupFile'.."
Copy-Item -Path $configFile -Destination $backupFile -Force
Write-Verbose "Overriding '$configFile' with decrypted content ..."
Set-Content -Path $configFile -Value $decryptedConfig -Confirm:$Confirm
}
Invoke-SessionCommand -Session:$EntrySession -ArgumentList $configFile,$backupFile,$decryptedConfig,$Confirm -ScriptBlock $BackupAndOverride
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSWebConfig/Get_ConfigFile.ps1
|
Get_ConfigFile.ps1
|
function Get_ConfigFile {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Path,
[Parameter(Position=1)]
[bool]$AsFileInfo=$false,
[Parameter(Position=2)]
[bool]$AsText=$false,
[Parameter(Position=3)]
[bool]$Recurse=$false
)
function Copy_WebConfig([string]$config) {
if (-Not (Test-Path $config)) {
Write-Warning "Could not find '$config'"
return $null
}
# Copy the original file to temp for non-intrusive decryptions
$tempFolder = [System.IO.Path]::GetTempPath()
$appGuid = [guid]::NewGuid().Guid
$tempAppFolder = Join-Path $tempFolder $appGuid
$tempAppConfig = Join-Path $tempAppFolder 'web.config'
Write-Verbose "Creating $tempAppFolder"
mkdir $tempAppFolder -Force | Out-Null
Write-Verbose "Copying $c to $tempAppFolder"
Copy-Item -Path $config -Destination $tempAppFolder
return $tempAppConfig
}
function Detect_AspNetRegIIS {
$paths = @(
"$($env:SystemRoot)\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe"
"$($env:SystemRoot)\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe"
)
foreach ($path in $paths) {
if (Test-Path -Path $path) {
Write-Verbose "$paths is found"
return $path
}
}
Write-Warning "Cannot find aspnet_regiis.exe in any known folders"
return $null
}
function IsAdministrator {
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
function Decypt_WebConfig {
param(
[string]$folder,
[string]$aspnet_regiis = $(Detect_AspNetRegIIS)
)
$webConfigFile = Join-Path $folder 'web.config'
if (Test-Path $webConfigFile) {
$xmlContent = [xml](Get-Content $webConfigFile)
if (-Not $xmlContent) {
Write-Error "'$webConfigFile' is not a valid XML file."
return
}
$alreadyWarned=$false
$sections = $xmlContent.configuration | Get-Member -MemberType Property | Select-Object -ExpandProperty Name
foreach ($s in $sections) {
$encryptedSection = ($xmlContent -and ($xmlContent.configuration.$s.EncryptedData))
if ($encryptedSection -and $aspnet_regiis) {
if (-Not $alreadyWarned -And -Not (IsAdministrator)) {
Write-Warning "You are not in an Administrator context. You may not be able to decrypt configuration sections."
$alreadyWarned = $true
}
$cryptArgs = "-pdf $s $folder"
Write-Verbose "Decrypting > $aspnet_regiis $cryptArgs"
Start-Process -FilePath $aspnet_regiis -ArgumentList $cryptArgs -WindowStyle Hidden -Wait
} else {
Write-Verbose "Skipping decryption of '$s' section"
}
}
}
}
# Expand and Test Path
$Path = [Environment]::ExpandEnvironmentVariables($Path)
if ([String]::IsNullOrEmpty($Path) -or -Not (Test-Path $Path)) {
Write-Verbose "Path '$Path' is not found."
return
}
Write-Verbose "Looking for config files at '$Path'.."
$configs = $()
foreach ($f in @("web.config","*.exe.config")) {
$found = $null
$found = Get-ChildItem $Path -Filter $f -Recurse:$Recurse -ErrorAction SilentlyContinue
if ($found) { $configs += @($found) }
}
$configs = $configs | Select-Object -Unique
if ($AsFileInfo) { $configs }
else {
foreach ($c in ($configs | Select-Object -Unique)) {
$content = $null
Write-Verbose "File '$($c.FullName)'.."
$isWebConfig = ($c.Name -eq 'web.config')
if ($isWebConfig) {
# Create a copy of web.config's and decrypt it
$tempAppFolder = $null
Write-Verbose "Cloning $($c.FullName) ..."
$tempAppConfig = Copy_WebConfig -config $c.FullName
$tempAppFolder = Split-Path $tempAppConfig -Parent
if (Test-Path $tempAppConfig) {
Decypt_WebConfig -folder $tempAppFolder
Write-Verbose "Reading web.config content"
$content = Get-Content $tempAppConfig | Out-String
}
Write-Verbose "Deleting $tempAppFolder"
Remove-Item $tempAppFolder -Force -Recurse
} else {
# App.config
Write-Verbose "Reading app config content"
$content = Get-Content $c.FullName | Out-String
}
if (!$AsText) {
$content = [xml]$content
$content | Add-Member -NotePropertyName File -NotePropertyValue $c.FullName
$content | Add-Member -NotePropertyName ComputerName -NotePropertyValue ([System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName)
$content
}
else { $content }
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSWebConfig/Get-PSWebConfig.ps1
|
Get-PSWebConfig.ps1
|
<#
.SYNOPSIS
Returns a decrypted configurations from websites or applications
.DESCRIPTION
The cmdlet finds the relevant web and app configs for the passed applications
or websites and returns it in an XML/Text or File list format.
It accepts either Path or an InputObject to discover the configuration files
and if -Recurse is specified it discovers all sub-configuration too.
Remote configurations can be fetched by setting -Session parameter.
If the input object is received from a PSSession instance, it will try to
use the session's InstanceId to fetch the configuration remotely.
.PARAMETER InputObject
Mandatory - Parameter to pass the Application or WebSite from pipeline
.PARAMETER Path
Mandatory - Parameter to pass the path for the target application
.PARAMETER Recurse
Optional - Switch to look for multiple web.config files in sub-folders for
web applications
.PARAMETER Session
Optional - PSSession to execute configuration file lookup
.PARAMETER AsXml
Optional - Switch to return configuration as an unencypted and parsed
XML object output (default behavior)
.PARAMETER AsText
Optional - Switch to return configfiles as unencrypted plain text output
.PARAMETER AsFile
Optional - Switch to return found configfile names as an output
.EXAMPLE
Get-PSWebConfig -Path 'c:\intepub\wwwroot\testapp\'
.EXAMPLE
$server1 = New-PSSession 'server1.local.domain'
Get-PSWebConfig -Path 'c:\intepub\wwwroot\testapp\' -Session $server1
.EXAMPLE
Get-WebSite | Get-PSWebConfig -AsText -Recurse
#>
function Get-PSWebConfig {
[CmdletBinding(DefaultParameterSetName="FromPipeLine")]
param(
[Parameter(ParameterSetName="FromPipeLine",Position=0)]
[Parameter(ValueFromPipeLine=$true)]
[psobject[]]$InputObject,
[Parameter(ParameterSetName="FromPath",Position=0,Mandatory=$true)]
[Alias('physicalPath')]
[string]$Path,
[Parameter(ParameterSetName="FromPath")]
[Parameter(ParameterSetName="FromPipeLine")]
[Parameter(ParameterSetName="AsFileInfo")]
[switch]$AsFileInfo,
[Parameter(ParameterSetName="FromPath")]
[Parameter(ParameterSetName="FromPipeLine")]
[Parameter(ParameterSetName="AsText")]
[switch]$AsText,
[Parameter(ParameterSetName="FromPath")]
[Parameter(ParameterSetName="FromPipeLine")]
[Parameter(ParameterSetName="AsXml")]
[switch]$AsXml,
[Parameter(ParameterSetName="FromPath")]
[Parameter(ParameterSetName="FromPipeLine")]
[Parameter(ParameterSetName="AsXml")]
[switch]$Recurse,
[System.Management.Automation.Runspaces.PSSession]$Session
)
process {
Write-Verbose "Executing Get-PSWebConfig"
if (!$AsText -and !$AsFileInfo) {
Write-Verbose "Defaulting output-format to XML object"
$AsXml = $true
}
if ($Path) {
Write-Verbose "Processing by Path"
$InputObject = New-Object -TypeName PsObject -Property @{
physicalPath = $Path
Session = $Session
}
}
if ($InputObject) {
Write-Verbose "Processing by InputObject"
foreach ($entry in $InputObject) {
# Setting Remote Session
$EntrySession = $entry.Session
if ($Session) {
Write-Verbose "Overriding session from -Session Parameter"
$EntrySession = $Session
}
elseif ($entry | Get-Member -Name RunspaceId) {
Write-Verbose "Getting Session from RunspaceId '$($entry.RunspaceId)'"
$EntrySession = Get-PSSession -InstanceId $entry.RunspaceId
}
if ($entry -is [System.IO.FileInfo] -or $entry.psobject.TypeNames -icontains 'Deserialized.System.IO.FileInfo') {
Write-Verbose "Adding physicalPath alias for [System.IO.FileInfo] FullName"
$entry = $entry | Add-Member -MemberType AliasProperty -Name physicalPath -Value FullName -PassThru
}
if ($entry | Get-Member -Name physicalPath) {
if ($EntrySession) {
Write-Verbose "Remote configuration fetch from '$($EntrySession.ComputerName + " " + $entry.physicalPath)'"
$response = Invoke-Command `
-Session $EntrySession `
-ArgumentList @($entry.physicalPath, $AsFileInfo, $AsText, $Recurse) `
-ScriptBlock ${function:Get_ConfigFile} |
Add-Member -NotePropertyName Session -NotePropertyValue $EntrySession -Force -PassThru
} else {
Write-Verbose "Local configuration fetch from '$($entry.physicalPath)'"
$response = Invoke-Command `
-ArgumentList @($entry.physicalPath, $AsFileInfo, $AsText, $Recurse) `
-ScriptBlock ${function:Get_ConfigFile}
}
if ($AsXml) {
$response | Set_Type -TypeName "PSWebConfig.WebConfig"
} else {
$response
}
} else {
Write-Warning "Cannot get path from InputObject '$entry'"
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSAppSetting/Get-PSAppSetting.ps1
|
Get-PSAppSetting.ps1
|
<#
.SYNOPSIS
Returns the appSettings from an or application/web config
.DESCRIPTION
The cmdlet takes an application/web configuration as an input and returns
all applicationsettings from it.
.PARAMETER ConfigXml
Mandatory - Pipeline input for Configuration XML
.EXAMPLE
Get-PSWebConfig -Path 'C:\inetpub\wwwroot\myapp' | Get-PSAppSetting
.EXAMPLE
Get-WebSite mysite | Get-PSWebConfig | Get-PSAppSetting
#>
function Get-PSAppSetting {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeLine=$true)]
[psobject[]]$ConfigXml
)
process {
Write-Verbose "Executing Get-PSAppSetting"
foreach ($config in $ConfigXml) {
Write-Verbose "Processing configuration '$($config.ComputerName + " " + $config.File)'"
if ($config -is [string]) { $config = [xml]$config }
if ($config | Get-Member -Name configuration) {
if ($config.configuration.appSettings.EncryptedData) {
Write-Warning "appSettings section is encrypted. You may not see all relevant entries."
Write-Warning "Execute this command as an administrator for automatic decryption."
}
foreach ($appSetting in $config.configuration.appSettings.add) {
$appSetting |
Add-Member -NotePropertyName Session -NotePropertyValue $config.Session -Force -PassThru |
Add-Member -NotePropertyName ComputerName -NotePropertyValue $config.ComputerName -Force -PassThru |
Add-Member -NotePropertyName File -NotePropertyValue $config.File -Force -PassThru |
Add-Member -NotePropertyName SectionPath -NotePropertyValue "appSettings" -Force -PassThru |
Set_Type -TypeName "PSWebConfig.AppSetting"
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSConnectionString/Test_ConnectionString.ps1
|
Test_ConnectionString.ps1
|
function Test_ConnectionString {
param(
[Parameter(Mandatory, Position=0)]
[string]$ConnectionString,
[Parameter(Position=1)]
[hashtable]$ReplaceRules,
[Parameter(Position=2)]
[bool]$ShowPassword=$false
)
$result = New-Object PsObject -Property @{
ComputerName = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName
TestType='SqlTest'
Test=$ConnectionString
Passed = $false
Result = $null
Status = $null
ConnectionString=$ConnectionString
ReplaceRules = $ReplaceRules
SqlQuery= $null
}
try {
# Transform ConnectionString
if ($ReplaceRules) {
$ReplaceRules.GetEnumerator() | ForEach-Object {
$result.ConnectionString = $result.ConnectionString -replace $_.Key,$_.Value
}
}
# Figure target database to check
$DbToCheck = 'tempdb'
$builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder $result.ConnectionString
if ($builder.'Initial Catalog') {
$DbToCheck = $builder.'Initial Catalog'
}
$result.SqlQuery="SELECT name FROM sysdatabases WHERE LOWER(name) = LOWER('$DbToCheck')"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection -ErrorAction Stop
$SqlConnection.ConnectionString = $result.ConnectionString
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $result.SqlQuery
$SqlCmd.Connection = $SqlConnection
$result.Result = $SqlCmd.ExecuteScalar()
$result.Status = "Passed: '$DbToCheck'"
$result.Passed = $true
} catch {
$result.Result = $_
$result.Status = "Failed: '$DbToCheck'"
$result.Passed = $false
Write-Error $_
} finally {
if ($SqlConnection) { $SqlConnection.Close() }
}
if (!$ShowPassword) {
Write-Verbose "Masking password due to ShowPassword:false .."
$maskRule = ';\s*password=(\S+)\s*(;|$)',';password=***;'
$result.ConnectionString = $result.ConnectionString -ireplace $maskRule
$result.Test = $result.Test -ireplace $maskRule
}
return $result
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSConnectionString/Test-PSConnectionString.ps1
|
Test-PSConnectionString.ps1
|
<#
.SYNOPSIS
Tests a ConnectionStrings from a local or remote machine
.DESCRIPTION
The cmdlet takes a ConnectionString as an input object or as a direct
parameter then it tries to connect to the database.
If Initial Catalog is specified, it queries the server for the specified
database otherwise it checks whether it can access the tempdb.
If a Session Property is passed via InputObject or directly with -Session
parameter, the ConnectionString test will be executed against it.
If -ReplaceRules hashtable is specified it will replace hash-keys with it's
values in the ConnectionString to be tested.
Passwords in the ConnectionString are masked by default, use -ShowPassword
switch if you need to show passwords in test-results.
.PARAMETER InputObject
Mandatory - Pipeline input of PsConnectionString
.PARAMETER ConnectionString
Mandatory - Parameter to pass a ConnectionString as a string
.PARAMETER ReplaceRules
Optional - Hashtable that replaces hash-keys with it's values in the
ConnectionString to be tested.
.PARAMETER ShowPassword
Optional - Switch to disable password masking for the test result.
.PARAMETER Session
Optional - PSSession to execute the test-against it.
.EXAMPLE
Test-PSConnectionString -ConnectionString 'Server=address;Database=db;User Id=uname;Password=***;'
.EXAMPLE
Get-WebSite mysite | Get-PSWebConfig | Get-PSConnectionString | Test-PSConnectionString
#>
function Test-PSConnectionString {
[CmdletBinding(DefaultParameterSetName='InputObject')]
param(
[Parameter(ParameterSetName="InputObject",ValueFromPipeLine=$true)]
[psobject[]]$InputObject,
[Parameter(ParameterSetName="ConnectionString",ValueFromPipeLine=$true)]
[string]$ConnectionString,
[hashtable]$ReplaceRules,
[System.Management.Automation.Runspaces.PSSession[]]$Session,
[switch]$ShowPassword
)
process {
Write-Verbose "Executing Test-PSConnectionString"
if ($ConnectionString) {
$InputObject = New-Object -TypeName PsObject -Property @{
ConnectionString = $ConnectionString
Session = $Session
}
}
foreach ($entry in $InputObject) {
if ($entry | Get-Member -Name ConnectionString) {
$EntrySession = $entry.Session
if ($Session) { $EntrySession = $Session }
$ArgumentList = $entry.ConnectionString,$ReplaceRules,$ShowPassword
if ($EntrySession) {
Write-Verbose "Remote Test execution from '$($EntrySession.ComputerName)'"
Invoke-Command `
-Session $EntrySession `
-ArgumentList $ArgumentList `
-ScriptBlock $Function:Test_ConnectionString |
Add-Member -NotePropertyName Session -NotePropertyValue $EntrySession -Force -PassThru |
Set_Type -TypeName 'PSWebConfig.TestResult'
} else {
Write-Verbose "Local Test execution"
Invoke-Command `
-ArgumentList $ArgumentList `
-ScriptBlock $Function:Test_ConnectionString |
Set_Type -TypeName 'PSWebConfig.TestResult'
}
} else {
Write-Verbose "InputObject doesn't contain ConnectionString property"
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSConnectionString/Get-PSConnectionString.ps1
|
Get-PSConnectionString.ps1
|
<#
.SYNOPSIS
Returns ConnectionStrings from an or application/web config
.DESCRIPTION
The cmdlet takes an application/web configuration as an input and returns
the connectionstrings from it.
If -IncludeAppSettings is specified it will try to match any ConnectionString from the
appSettings sections too.
.PARAMETER ConfigXml
Mandatory - Pipeline input for Configuration XML
.PARAMETER IncludeAppSettings
Optional - Parameter to find any connectionStrings from application Settings
.EXAMPLE
Get-PSWebConfig -Path 'C:\inetpub\wwwroot\myapp' | Get-PSConnectionString
.EXAMPLE
Get-WebSite mysite | Get-PSWebConfig | Get-PSConnectionString
.EXAMPLE
Get-WebSite mysite | Get-PSWebConfig | Get-PSConnectionString -IncludeAppSettings
#>
function Get-PSConnectionString {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeLine=$true)]
[psobject[]]$ConfigXml,
[switch]$IncludeAppSettings
)
process {
Write-Verbose "Executing Get-PSConnectionString"
foreach ($config in $ConfigXml) {
if ($config -is [string]) { $config = [xml]$config }
if ($config | Get-Member -Name configuration) {
Write-Verbose "Processing configuration '$($config.ComputerName + " " + $config.File)'"
if ($config.configuration.connectionStrings.EncryptedData) {
Write-Warning "ConnectionStrings section is encrypted. You may not see all relevant entries."
Write-Warning "Execute this command as an administrator for automatic decryption."
}
foreach ($connectionString in $config.configuration.connectionStrings.add) {
$connectionString |
Add-Member -NotePropertyName Session -NotePropertyValue $config.Session -Force -PassThru |
Add-Member -NotePropertyName ComputerName -NotePropertyValue $config.ComputerName -Force -PassThru |
Add-Member -NotePropertyName File -NotePropertyValue $config.File -Force -PassThru |
Add-Member -NotePropertyName SectionPath -NotePropertyValue "connectionStrings" -Force -PassThru |
Set_Type -TypeName "PSWebConfig.ConnectionString"
}
if (-Not $IncludeAppSettings) {
Write-Verbose "Appsettings are not included in ConnectionString processing."
continue
}
Write-Verbose "Looking for ConnectionStrings in appsettings.."
$config | Get-PSAppSetting | ForEach-Object {
if ($_.value -match 'data source=') {
$_ |
Add-Member -MemberType AliasProperty -Name ConnectionString -Value value -Force -PassThru |
Add-Member -MemberType AliasProperty -Name Name -Value key -Force -PassThru |
Set_Type -TypeName "PSWebConfig.ConnectionString"
}
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSUri/Test-PSUri.ps1
|
Test-PSUri.ps1
|
<#
.SYNOPSIS
Tests any HTTP/HTTPS URIs from a remote or local machine.
.DESCRIPTION
The cmdlet takes a URI as an input object or as a direct
parameter then it tries to connect to it with Invoke-WebRequest with
-UseBasicParsing switch and returns the result as a test object.
You can specify a regular-expression for accepting various HTTP status
codes with -AllowedStatusCodeRegexp parameter.
Use -DisableSSLValidation switch to allow any HTTPs certificactes accepted
for the tests.
If a Session Property is passed via InputObject or directly with -Session
parameter, the URI test will be executed against that.
If -ReplaceRules hashtable is specified it will replace hash-keys with it's
values in the URI to be tested. This could be useful, when you need to
override the test Uri with dynamic values.
.PARAMETER InputObject
Mandatory - Pipeline input of PSUri
.PARAMETER Uri
Mandatory - Parameter to pass a URI as a string
.PARAMETER AllowedStatusCodeRegexp
Optional - Regxep string to set which HTTP Response Code should be accepted.
.PARAMETER TimeOutSeconds
Optional - TimeOut Seconds to be used for Invoke-WebRequest
.PARAMETER DisableSSLValidation
Optional - Switch to accept any SSL certificate for HTTPS URI tests.
.PARAMETER ReplaceRules
Optional - Hashtable that replaces hash-keys with it's values in the
URI to be tested.
.PARAMETER Session
Optional - PSSession to execute the test-against it.
.EXAMPLE
Test-PSUri -Uri 'http://murati.hu'
.EXAMPLE
Get-WebSite mysite | Get-PSWebConfig | Get-PSUri | Test-PSUri
#>
function Test-PSUri {
[CmdletBinding(DefaultParameterSetName='ByInputObject')]
param(
[Parameter(ParameterSetName="ByInputObject",ValueFromPipeLine=$true)]
[psobject[]]$InputObject,
[Parameter(ParameterSetName="ByUri",ValueFromPipeLine=$true)]
[Parameter(Position=0)]
[Alias('Address','Url')]
[string[]]$Uri,
[string]$AllowedStatusCodeRegexp = '^20[0-9]|^401|^403|^50[0-9]',
[ValidateRange(0,3600)]
[Int32]$TimeOutSeconds=5,
[switch]$DisableSSLValidation,
[hashtable]$ReplaceRules,
[System.Management.Automation.Runspaces.PSSession[]]$Session
)
process {
Write-Verbose "Executing Test-PSUri"
if ($Uri) {
$InputObject = $Uri | Foreach-Object {
New-Object -TypeName PsObject -Property @{
Uri = $_
Session = $Session
}
}
}
foreach ($entry in $InputObject) {
if ($entry | Get-Member -Name Uri) {
$EntrySession = $entry.Session
if ($Session) { $EntrySession = $Session }
$argumentList = $entry.Uri,$DisableSSLValidation,$AllowedStatusCodeRegexp,$TimeOutSeconds,$ReplaceRules
if ($EntrySession) {
Invoke-Command `
-Session $EntrySession `
-ArgumentList $argumentList `
-ScriptBlock $Function:Test_Uri |
Add-Member -NotePropertyName Session -NotePropertyValue $EntrySession -Force -PassThru |
Set_Type -TypeName 'PSWebConfig.TestResult'
} else {
Invoke-Command `
-ArgumentList $argumentList `
-ScriptBlock $Function:Test_Uri |
Set_Type -TypeName 'PSWebConfig.TestResult'
}
} else {
Write-Verbose "InputObject doesn't contain Uri property"
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSUri/Get-PSUri.ps1
|
Get-PSUri.ps1
|
<#
.SYNOPSIS
Returns any URIs from application or web configuration.
.DESCRIPTION
It accepts configuration XMLs and returns any URIs found in appSettings and
from client endpoint addresses.
The cmdlet filters PSAppSettings for URIs and also returns PSEndpoint results.
.PARAMETER ConfigXml
Mandatory - Pipeline input for Configuration XML
.PARAMETER IncludeAppSettings
Optional - Switch to include http/s URIs from appsettings
.EXAMPLE
Get-PSWebConfig -Path 'C:\inetpub\wwwroot\myapp' | Get-PSUri
.EXAMPLE
Get-WebSite mysite | Get-PSWebConfig | Get-PSUri
#>
function Get-PSUri {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeLine=$true)]
[psobject[]]$ConfigXml,
[switch]$IncludeAppSettings
)
process {
Write-Verbose "Executing Get-PSUri"
Write-Verbose "Looking for service-endpoint addresses..."
Get-PSEndpoint -ConfigXml $configXml
if (-Not $IncludeAppSettings) {
Write-Verbose "Appsettings are not included in URI processing."
return
} else {
Write-Verbose "Looking for any http URLs from appSettings..."
Get-PSAppSetting -ConfigXml $configXml |
Where-Object value -imatch '^http[s]*:' |
Add-Member -MemberType AliasProperty -Name name -Value key -Force -PassThru |
Add-Member -MemberType AliasProperty -Name address -Value value -Force -PassThru |
Add-Member -MemberType AliasProperty -Name Uri -Value value -Force -PassThru |
Set_Type -TypeName 'PSWebConfig.Uri'
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSUri/Get-PSEndpoint.ps1
|
Get-PSEndpoint.ps1
|
<#
.SYNOPSIS
Returns endpoint addresses from application or web configuration
.DESCRIPTION
It accepts configuration XMLs and returns \client endpoint addresses from
system.serviceModel section.
.PARAMETER ConfigXml
Mandatory - Pipeline input for Configuration XML
.EXAMPLE
Get-PSWebConfig -Path 'C:\inetpub\wwwroot\myapp' | Get-PSEndpoint
.EXAMPLE
Get-WebSite mysite | Get-PSWebConfig | Get-PSEndpoint
#>
function Get-PSEndpoint {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeLine=$true)]
[psobject[]]$ConfigXml
)
process {
Write-Verbose "Executing Get-PSEndpoint"
foreach ($config in $ConfigXml) {
Write-Verbose "Processing configuration '$($config.ComputerName + " " + $config.File)'"
if ($config | Get-Member -Name configuration) {
foreach ($endpoint in $config.configuration.'system.serviceModel'.client.endpoint) {
$endpoint |
Add-Member -NotePropertyName Session -NotePropertyValue $config.Session -Force -PassThru |
Add-Member -NotePropertyName ComputerName -NotePropertyValue $config.ComputerName -Force -PassThru |
Add-Member -NotePropertyName File -NotePropertyValue $config.File -Force -PassThru |
Add-Member -NotePropertyName SectionPath -NotePropertyValue 'system.serviceModel/client/endpoint' -Force -PassThru |
Add-Member -MemberType AliasProperty -Name Uri -Value address -Force -PassThru |
Set_Type -TypeName 'PSWebConfig.Uri'
}
} else {
Write-Warning "Skipping invalid configuration: $config"
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.