Ссылочная переменная power shell

apiVersions :
capabilities : {@{name=MaxResourceVolumeMB; value=256000}, @{name=OSVhdSizeMB; value=1047552}, @{name=vCPUs; value=8}, @{name=MemoryPreservingMaintenanceSupported; value=False}…}
capacity :
costs :
family : standardMSFamily
kind :
locationInfo : {@{location=australiasoutheast; zoneDetails=System.Object[]; zones=System.Object[]}}
locations : {australiasoutheast}
name : Standard_M8-4ms
resourceType : virtualMachines
restrictions : {}
size : M8-4ms
tier : Standard

The capabilities and locatioinfo objects in the variable look like hashtables.

name capabilities
---- ------------
Aligned {@{name=MaximumPlatformFaultDomainCount; value=2}}
Classic {@{name=MaximumPlatformFaultDomainCount; value=3}}
Premium_LRS {@{name=MaxSizeGiB; value=4}, @{name=MinSizeGiB; value=0}, @{name=MaxIOps; value=120}, @{name=MinIOps; value=120}…}
Premium_LRS {@{name=MaxSizeGiB; value=128}, @{name=MinSizeGiB; value=64}, @{name=MaxIOps; value=500}, @{name=MinIOps; value=500}…}
Premium_LRS {@{name=MaxSizeGiB; value=256}, @{name=MinSizeGiB; value=128}, @{name=MaxIOps; value=1100}, @{name=MinIOps; value=1100}…}

How can I get to and extract the data I need from those hashtables?

[ref]$refString = 'Test'
$string = $refString
$refString.Value = 'NotTest'
$string
[ref]$a = 'test'
[ref]$b = 'foo'
[ref]$c = 'bar'
$arguments= "?arg1=" + $a.value + "&arg2=" + $b.value + "&arg3=" + $c.value
$a.Value = 'no'
$b.Value = 'change'
$c.Value = 'Happens'
$arguments

Is there a way to correctly reference the new values?

asked Aug 5, 2023 at 0:13

Philosophene's user avatar

In your first example $string holds the same reference as $refString (a mutable type) whereas in your second example you’re constructing a string (an immutable type) by concatenating strings with the values (also immutable strings) of your PSReferences, meaning that $arguments is immutable. Updating the values of the PSReference will not affect the already constructed string.

By the looks of what you have and a bit of guessing, I think UriBuilder and HttpUtility.ParseQueryString is what you’re after:

if (-not $IsCoreCLR) { Add-Type -AssemblyName System.Web
}
$builder = [System.UriBuilder]::new('myurlhere')
$query = [System.Web.HttpUtility]::ParseQueryString('')
$query['args1'] = 'test'
$query['args2'] = 'foo'
$query['args3'] = 'bar'
$builder.Query = $query.ToString()
$builder.Uri.ToString()
# Outputs: http://myurlhere/?args1=test&args2=foo&args3=bar
$query['args1'] = 'changes'
$query['args2'] = 'happen'
$query['args3'] = 'here'
$builder.Query = $query.ToString()
$builder.Uri.ToString()
# Outputs: http://myurlhere/?args1=changes&args2=happen&args3=here

answered Aug 5, 2023 at 2:35

Santiago Squarzon's user avatar

When you store data in a variable, PowerShell can store it how you want it to be if you use the correct data type. This blog post will show you how that works and which data types I mostly use for my scripts.

Ссылочная переменная power shell

What are data or reference types?

There are two ways in which you can find the types being referenced: data or reference. The Microsoft Learn documents refer to it like this:

Other articles refer to it as data types, for example, this article from ScriptRunner: https://support.scriptrunner.com/articles/#!coding/powershell-data-types

But what can you do with it?

In PowerShell, you can store data in a Variable. Depending on what you try to store, it might not be in the correct format for further use in your script. In the chapters below, I will show you the types that I usually use to get things done 😉

[array]

[array]$array=Get-ChildItem 

[datetime]

PS C:\Users\HarmVeenstra> $datetime=get-date
PS C:\Users\HarmVeenstra> $datetime.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DateTime System.ValueType

Because it’s in this format, you can use things like:

PS C:\Users\HarmVeenstra> $datetime.DayOfWeek
Thursday
PS C:\Users\HarmVeenstra> $datetime.Hour
14
PS C:\Users\HarmVeenstra> $datetime.AddHours(-1)
donderdag 11 april 2024 13:59:08

[string]

The simplest one is just a simple line of text without any carriage return. For example:

C:\Users\HarmVeenstra> $string="This is just a simple line of text"
C:\Users\HarmVeenstra> $string
This is just a simple line of text
C:\Users\HarmVeenstra> $string.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object

Using “.GetType()” behind the variable will show that the BaseType is System.Object with a String type.

[version]

This is something that I use to compare versions of applications or PowerShell modules. For example:

PS C:\Users\HarmVeenstra> $version='2.3.2'
PS C:\Users\HarmVeenstra> $version.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PS C:\Users\HarmVeenstra> $version
2.3.2
PS C:\Users\HarmVeenstra> [version]$version='2.3.2'
PS C:\Users\HarmVeenstra> $version.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Version System.Object
PS C:\Users\HarmVeenstra> $version
Major Minor Build Revision
----- ----- ----- --------
2 3 2 -1

[xml]

PS C:\Users\HarmVeenstra> $xml=Get-Content C:\temp\example.xml
PS C:\Users\HarmVeenstra> $xml
<Configuration ID="1ea22db9-fbc6-4254-aea8-7c5fa6b96b07"> <Add OfficeClientEdition="64" Channel="MonthlyEnterprise" SourcePath="\\test.local\data\software\microsoft\m365" AllowCdnFallback="TRUE"> <Product ID="O365ProPlusRetail"> <Language ID="MatchOS" /> <Language ID="zh-cn" /> <Language ID="hr-hr" />
.....
PS C:\Users\HarmVeenstra> [xml]$xml=Get-Content C:\temp\example.xml
PS C:\Users\HarmVeenstra> $xml.getType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False XmlDocument System.Xml.XmlNode
PS C:\Users\HarmVeenstra> $xml
Configuration
-------------
Configuration
PS C:\Users\HarmVeenstra> $xml.Configuration
ID : 1ea22db9-fbc6-4254-aea8-7c5fa6b96b07
Add : Add
Property : {SharedComputerLicensing, PinIconsToTaskbar, SCLCacheOverride, AUTOACTIVATE…}
Updates : Updates
RemoveMSI : RemoveMSI
AppSettings : AppSettings
Display : Display
Logging : Logging
PS C:\Users\HarmVeenstra> $xml.Configuration.RemoveMSI.IgnoreProduct
ID
--
InfoPath
InfoPathR
PrjPro
PrjStd
SharePointDesigner
VisPro
VisStd
PS C:\Users\HarmVeenstra>

In this Section

PowerShell on Windows
Explains what is necessary to set up a PowerShell environment for using NCache.

:/>  Получение свойств сайта с использованием power shell

Add-BackingSource
Discusses how to add backing source using Command Line.

Add-BridgeCache
Discusses how to add a clustered cache to a registered bridge.

Add-BridgeNode
Discusses how to add a bridge server node to a registered bridge.

Add-ClientNode
Discusses how to add a client node to a cache.

Add-ClientNodeSecurity
Discusses how to add client node security.

Add-CompactType
Discusses how to add compact serialization to the cache.

Add-CustomDependency
Discusses how to add custom dependency.

Add-LoaderDataset
Discusses how to add a loader dataset.

Add-Node
Discusses how to add a server node to an existing cache.

Add-PortableType
Discusses how to enable data sharing for different classes.

Add-QueryIndex
Discusses how to add query indexes for the objects to be added in a cache.

Add-StartupLoader
Discusses how to configure startup loader provider for a cache.

Add-TestData
Discusses how to add some test data to a cache.

Clear-Cache
Discusses how to clear a cache.

Disable-NCacheSecurity
Discusses how to disable NCache security on the specified server.

Disable-NCacheTLS
Discusses how to disable TLS encryption on specified nodes.

Enable-NCacheSecurity
Discusses how to enable NCache security on the specified server.

Enable-NCacheTLS
Discusses how to enable TLS encryption on specified nodes.

Export-CacheConfiguration
Discusses how to export the cache configuration to the specified path.

Export-CacheData
Discuesses how to export cache data to the specified path.

Export-CacheKeys
Discusses how to export the cache keys to the specified path.

Get-CacheClientStatistics
Discusses how to fetch the client statistics for a specified cache.

Get-CacheCount
Discusses how to get the total cache count of a particular cache.

Get-CacheLogs
Discusses how to fetch particular log file(s) from NCache repository to the local machine.

Get-CacheLogsList
Discusses how to get a list of cache logs for a particular cache.

Get-Caches
Discusses how to get the total number of caches registered on a server.

Get-CacheServerStatistics
Discusses how to fetch the server statistics for a specified cache.

Get-ClusterHealth
Discusses how to display the cluster health of a specific cache.

Get-ConnectedClients
Discusses how to list connected clients for server based licensing.

Get-MemoryDumpList
Discusses how to get a list of all memory dumps generated on a server.

Get-NCacheVersion
Discusses how to get the details about the NCache version installed.

Get-Topics
Discusses how to get the list of all the topics registered on a cache.

Import-CacheData
Discusses how to get the cache data from the backup.

Import-DistributedLuceneIndex
Discusses how to get the distributed lucene index.

Import-LuceneIndex
Discusses how to get the lucene index.

Install-Module
Discusses how to deploy provider assemblies.

Invoke-RefresherDataset
Discusses how to enable refresher dataset.

Invoke-ServerLogger
Discusses how to enable detailed logging.

New-Bridge
Discusses how to create a new bridge.

New-Cache
Discusses how to create a new cache.

New-ClientCache
Discusses how to create a new client cache.

New-MemoryDump
Discusses how to generate a memory dump on a server for a cache or process.

Register-NCache
Discusses activation/reactivation of NCache license.

Register-NCacheEvaluation
Discusses registration of NCache evaluation.

Register-NCacheOpenSource
Discusses registration of NCache evaluation.

Remove-Backing Source
Discusses how to remove preconfigured backing source providers.

Remove-Bridge
Discusses how to remove an already registered bridge.

Remove-BridgeCache
Discusses how to remove an existing clustered cache from a registered bridge.

Remove-BridgeNode
Discusses how to remove an existing bridge server node from a registered bridge.

:/>  Получить элементы по методу имя тега

Remove-Cache
Discusses how to remove an already existing cache.

Remove-ClientCache
Discusses how to remove an already existing client cache.

Remove-ClientNode
Discusses how to remove client node(s) from a cluster.

Remove-CompactType
Discusses how to remove serializable objects.

Remove-CustomDependency
Discusses how to remove custom dependency.

Remove-LoaderDataset
Discusses how to remove a loader dataset.

Remove-MemoryDump
Discusses how to delete a memory dump file generated on a server.

Remove-Node
Discusses how to remove a server node from a cache.

Remove-PortableType
Discusses how to remove data sharing.

Remove-QueryIndex
Discusses how to remove query indexes for objects to be added in the cache.

Remove-StartupLoader
Discusses how to remove a preconfigured startup loader provider for a cache.

Resume-NCacheDataPersistence
Discusses how to resume NCache data persistence for a cache.

Set-BridgeCacheMode
Discusses how to start a bridge on a server.

Set-CacheConfiguration
Discusses how to configure a cache on a server.

Start-Bridge
Discusses how to start a bridge on a server.

Start-BridgeStateTransfer
Discusses how to manually start the state transfer process from a source to target cache on bridge.

Start-Cache
Discusses how to start a cache on a server.

Start-NCacheManagementCenter
Explains how to start the NCache Management Center.

Start-NCachePlaygroundProcess
Explains how to start the NCache Playground.

Stop-Bridge
Discusses how to stop a bridge on a server.

Stop-Cache
Discusses how to stop a cache on a server.

Stop-NCacheManagementCenter
Explains how to stop the NCache Management Center.

Stop-NCachePlaygroundProcess
Explains how to stop the NCache Playground.

Suspend-CacheDataPersistence
Explains how to suspend the NCache data persistence.

Test-Stress
Discusses how to simulate stress to test NCache performance.

Unregister-NCache
Discusses the deactivation of NCache licenses.

Write-BackingSourceConfig
Explains how to display the configuration for backing source implementation.

Write-QueryIndexConfig
Discusses how to display the configuration for query-indexing implementation.

In this PowerShell tutorial, I will explain the PowerShell reference variable. First, we will understand what is a reference variable in PowerShell, how to create and use PowerShell reference variables, and how to use a reference variable in functions in PowerShell.

In programming, a reference variable is a pointer to another variable. It means that instead of holding the actual value, the reference variable holds the address in memory where the value is stored. This is particularly useful when you want to allow a function to modify the actual value of a variable.

PowerShell allows the creation and use of reference type variables through a feature known as ref. By using a reference variable, you can permit a function or cmdlet to change the value of a variable directly.

Create Reference Variables in PowerShell

# Define a variable with an initial value
$originalValue = "Old Value"
# Create a reference to the variable
$referenceToOriginal = [ref]$originalValue
# Display the value via reference
$referenceToOriginal.Value

In this example, $referenceToOriginal is a reference to $originalValue. Any changes made to this reference will affect the $originalValue variable.

Here you can see the output in the screenshot below:

powershell reference variable

How to Use PowerShell Reference Variables with Functions

PowerShell Reference variables become particularly useful when passing parameters to functions. By default, when you pass a variable to a function in PowerShell, you are passing a copy of the value (pass by value). However, if you want the function to modify the original variable, you need to pass it by reference.

Let’s look at an example:

function Update-Value { param ([ref]$data) $data.Value = "New Value"
}
# Define a variable
$myData = "Initial Value"
# Pass the variable by reference to the function
Update-Value ([ref]$myData)
# Display the updated value
$myData

In this script, the Update-Value function takes a parameter by reference. Inside the function, we change the value of the parameter using $data.Value. After the function is called, the original $myData variable reflects the change.

:/>  CHKDSK /F /R где хранит лог windows 7

Here is the output you can see:

powershell function reference parameter

When to Use Reference Variables in PowerShell

Reference variables are not commonly used for every scenario. They are best suited for situations where you need to:

  • Allow a function to modify one or more variables that are passed to it.
  • Work with large data structures that would be inefficient to copy.
  • Implement certain data structures or algorithms that require direct manipulation of variable addresses.

PowerShell Pass by Reference

Passing by reference in PowerShell is a concept that allows a function to modify the actual content of a variable, rather than working on a copy of the variable’s value. This is particularly useful when you want to ensure that any changes made to a variable within a function are reflected in the original variable outside the function.

When you pass a variable by reference, you are essentially passing a pointer to the memory location where the data is stored. As a result, if the function modifies the variable, it modifies the variable’s memory content, and the change is visible outside the function as well.

Here’s how you can pass variables by reference in PowerShell:

function Swap-Values ([ref]$first, [ref]$second) { $temp = $first.Value $first.Value = $second.Value $second.Value = $temp
}
# Define two variables
$a = 1
$b = 2
# Pass the variables by reference to the Swap-Values function
Swap-Values ([ref]$a) ([ref]$b)
# Output the results
Write-Host "a is now $a"
Write-Host "b is now $b"

In the Swap-Values function, we accept two parameters as references. Inside the function, we swap the values using the .Value property of the reference variables. After calling Swap-Values, the values of $a and $b are swapped, demonstrating that the variables were indeed passed by reference.

Using pass by reference should be done with care, as it can lead to side effects that are harder to track within your scripts. However, when used correctly, it can be a powerful tool for certain tasks, such as updating multiple variables, working with large objects without the performance hit of copying them, or when interfacing with .NET methods that require objects to be passed by reference.

PowerShell reference type is expected in argument

While working with this PowerShell reference type I got the below error:

And here I was writing the code like below:

Function Calculate([ref]$number)
{ $number.Value = 50
}
$var = 100
Calculate -number [ref]$var
Write-Host $var

The error was because of the way I was passing reference parameters to the function.

Calculate -number ([ref]$var)

Conclusion

PowerShell reference variables are powerful and allow you to directly manipulate the value of a variable in memory. This can be particularly useful when you need to ensure that changes made within a function are reflected in the original variable. You can write more efficient and effective PowerShell scripts by understanding how to create and use reference variables.

Here we learned:

  • What is a reference variable in PowerShell?
  • How to create and use PowerShell reference variable
  • PowerShell ref parameter
  • PowerShell Reference Variables with Functions
  • PowerShell pass by reference

You may also like:

Bijay Kumar