简体   繁体   中英

Basic Windows 10 Powershell question on variable initializaton and passing arguments

I am currently learning about Powershell and how to write a script to launch an application. The following snippet of code I borrowed and have modified to learn how to launch notepad. The question I have is what does $args.Clone() do or derive from? (It is from the original code which had a different path and executable program being defined/called.) I realize that the variable $myArgs is being initialized to the left of the equal sign by the function on the right. However, I have not been successful finding resources about what can you can do with .Clone() so I thought I would try and ask here.

BTW, the script works as it launchs notepad.exe and names the text file 'pp'. If the file has not previously been created, it asks me if I want to name the text file 'pp'.

$exePath = $env:NOTEPAD_HOME + '/Windows/notepad.exe'
$myArgs = $args.Clone()
$myArgs += '-pp'
$myArgs += $env:NOTEPAD_HOME
& $exePath $myArgs

tl;dr

Your modification of $myArgs can be simplified as follows:

$myArgs = $args + '-pp' + $env:NOTEPAD_HOME

With an array as the LHS, operator + performs concatenation , ie, it appends to the array, though note that appending means that a new array is created in the process, given that arrays are fixed-size data structures in .NET.

The fact that a new array is implicitly created anyway makes the call to .Clone() in your code unnecessary.


Background Information

Typically - and in the case of the automatic $args variable - the .Clone() method is an implementation of the System.ICloneable interface .

The purpose of .Clone() is to create a copy (clone) of an object, but - as the answer linked to by BACON explains - the semantics of this operation - shallow (see below) vs. deep copying - aren't prescribed, which is why use of System.ICloneable is generally discouraged .

$args is an array ( System.Array ), and for arrays, .Clone() creates a so-called shallow copy. That is, how the elements of the array are copied depends on whether they are instances of value types or reference types:

  • for value-type elements, the new array will have an independent copy of the data of the original array's elements.

  • for reference-type elements, the new array will have a copy of the reference of the original array's elements, which means that elements of both arrays point to same data (objects).

For more information about value types vs. reference types, see this answer .

PowerShell implicitly clones arrays in the way described when you use += and + .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM