Using a Variable (PowerShell) inside of a command - powershell

$computer = gc env:computername
# Argument /RU '$computer'\admin isn't working.
SchTasks /create /SC Daily /tn "Image Verification" /ST 18:00:00 /TR C:\bdr\ImageVerification\ImageVerification.exe /RU '$computer'\admin /RP password
Basically I need to provide the computer name in the scheduled task...
Thank you in advance!

Single quoted strings will not expand variables in PowerShell. Try a double quoted string e.g.:
"$computer\admin"

To complement Keith Hill's helpful answer with additional information:
Both "$computer\admin" and the unquoted form, $computer\admin, would work, because unquoted string arguments are implicitly treated as if they were "..."-enclosed (double-quoted), i.e. as expandable strings that perform string interpolation (replace embedded variable references and expressions with their values), as opposed to verbatim strings ('...', single-quoted) that do not interpret their content.
When in doubt, use "..." explicitly, notably when the string contains metacharacters such as | and <
For the complete rules on how unquoted tokens are parsed as command arguments, see this answer.
Pitfalls:
The partial quoting you attempted:
'$computer'\admin
even if corrected to "$computer"\admin to make interpolation work, would not work, because PowerShell - perhaps surprisingly - then passes the value of $computer and verbatim string \admin as two arguments. Only if a compound string with partial quoting starts with an unquoted string is it recognized as a single argument (e.g. $computer"\admin" would work) - see this answer for more information.
Another notable pitfall is that only stand-alone variable references such as $computer and $env:COMPUTERNAME can be embedded as-is in "..."; to embed an expression - which includes property access and indexed access - or a command, you need to enclose them in $(...), the subexpression operator. E.g., to embed the value of expression $someArray[0] or $someObj.someProp in an expandable string, you must use "$($someArray[0])" or "$($someObj.someProp)" - see this answer for the complete rules.

Related

pass $var to remote session [duplicate]

$computer = gc env:computername
# Argument /RU '$computer'\admin isn't working.
SchTasks /create /SC Daily /tn "Image Verification" /ST 18:00:00 /TR C:\bdr\ImageVerification\ImageVerification.exe /RU '$computer'\admin /RP password
Basically I need to provide the computer name in the scheduled task...
Thank you in advance!
Single quoted strings will not expand variables in PowerShell. Try a double quoted string e.g.:
"$computer\admin"
To complement Keith Hill's helpful answer with additional information:
Both "$computer\admin" and the unquoted form, $computer\admin, would work, because unquoted string arguments are implicitly treated as if they were "..."-enclosed (double-quoted), i.e. as expandable strings that perform string interpolation (replace embedded variable references and expressions with their values), as opposed to verbatim strings ('...', single-quoted) that do not interpret their content.
When in doubt, use "..." explicitly, notably when the string contains metacharacters such as | and <
For the complete rules on how unquoted tokens are parsed as command arguments, see this answer.
Pitfalls:
The partial quoting you attempted:
'$computer'\admin
even if corrected to "$computer"\admin to make interpolation work, would not work, because PowerShell - perhaps surprisingly - then passes the value of $computer and verbatim string \admin as two arguments. Only if a compound string with partial quoting starts with an unquoted string is it recognized as a single argument (e.g. $computer"\admin" would work) - see this answer for more information.
Another notable pitfall is that only stand-alone variable references such as $computer and $env:COMPUTERNAME can be embedded as-is in "..."; to embed an expression - which includes property access and indexed access - or a command, you need to enclose them in $(...), the subexpression operator. E.g., to embed the value of expression $someArray[0] or $someObj.someProp in an expandable string, you must use "$($someArray[0])" or "$($someObj.someProp)" - see this answer for the complete rules.

MSIEXEC - Argumentlist with Variable

I am trying to start an installation via msiexec.
The following parameters are available and if I use this on that way, the installation will be correct.
This is the example from the vendor:
msiexec.exe /i ApexOne.msi MyServer="win2016-x64:8080|4343" MyDomain="Workgroup\Subdomain" /Lv+ "c:\temp\MSI.log"
This is my code:
Start-Process -FilePath "$env:systemroot\system32\msiexec.exe" -ArgumentList #('/i ".\agent.msi" MyServer="servername:8080|4344" MyDomain="999-Test"') -wait
But for automation I have to use the variable $domain to generate the correct domain.
I tried different codes, but nothing helped:
This is the code for my variable $domain
$domain='999-Test'
Example:
Start-Process -FilePath "$env:systemroot\system32\msiexec.exe" -ArgumentList #('/i ".\agent.msi" MyServer="servername:8080|4344" MyDomain=**"$domain"'**) -wait
I tried that also, but I don't know how to fix this failure.
I think the interpration of the variable is false, but I can not fix it.
-ArgumentList #('/i ".\agent.msi"','MyServer="servername:8080|4344"','MyDomain='$domain'')
Maybe someone can help me to fix this error?
Due to a long-standing bug in Start-Process, it is actually preferable to always pass all arguments for the target process encoded in a single string passed to -ArgumentList (-Args), rather than individually, as elements of an array - see this answer.
Doing so requires two things:
To incorporate variable values, you must use an expandable string, i.e. a double-quoted string, "...".
Any embedded quoting inside this overall "..." string must itself use double-quoting only, as CLIs on Windows generally only understand " (double quotes) and not also ' (single quotes) to have syntactic function. To embed " characters in a "..." string, escape them as `" (or as ""; inside a '...' string, you needn't escape them at all).
While this is somewhat cumbersome, it does have the advantage of allowing you to directly control the exact command line that the target process will see - and that enables you satisfy msiexec's picky syntax requirements where PROP="value with spaces" must be passed exactly with this value-only double-quoting (whereas PowerShell - justifiably - turns this argument into "PROP=value with spaces" behind the scenes, when it - of necessity - re-quotes arguments to synthesize the actual command line to use).
Therefore, use the following (using positional argument binding to -FilePath and -ArgumentList, respectively):
Start-Process -Wait $env:systemroot\system32\msiexec.exe "/i .\agent.msi MyServer=`"servername:8080|4344`" MyDomain=`"999-Test`""
Note: Strictly speaking, you do not need the embedded `"...`" quoting in your case, given that your property values have no embedded spaces.
The msiexec.exe program seems to have some peculiarities in its command-line parser. I recommend an approach like the following:
$msiFileName = ".\agent.msi"
$myServer = "servername:8080|4344"
$myDomain = "999-Test"
$argumentList = #(
'/i'
'"{0}"' -f $msiFileName
'MyServer="{0}"' -f $myServer
'MyDomain="{0}"' -f $myDomain
)
$startArgs = #{
"FilePath" = "msiexec.exe"
"ArgumentList" = $argumentList
"Wait" = $true
}
Start-Process #startArgs
This example creates an array of string arguments for the -ArgumentList parameter using single quotes (') and string formatting (-f). In the above example, each element in the $argumentList array is a separate string and contains the following elements:
/i
".\agent.msi"
MyServer="servername:8080|4344"
MyDomain="999-Test"
(Note that in the content of the array we are preserving the " characters.)
Next, we create a hashtable for the Start-Process cmdlet and call it using the # operator. (Creating a hashtable for a cmdlet's parameters is known as splatting and is a convenient way to build a large number of parameters for a cmdlet in a more readable and maintainable way.)

Powershell variable replacement with Start-Process and ArgumentList

I have this bit of powershell code that gets the FQDN and saves it to a variable...works great:
$FQDN=(Get-WmiObject win32_computersystem).DNSHostName.ToLower()+"."+(Get-WmiObject win32_computersystem).Domain
LogWrite "[+] The system fully qualified hostname has been detected as: $FQDN"
However, when I go to insert the string of the FQDN variable, I can not get it to work correctly. I have tried back ticks, double and single quotes with no success:
Start-Process -Wait $OUTPATH64 -ArgumentList '/s /v"/qn INSTALLDIR=\"C:\Program Files\IBM\WinCollect\" LOG_SOURCE_AUTO_CREATION_ENABLED=TRUE LOG_SOURCE_AUTO_CREATION_PARAMETERS=""Component1.AgentDevice=DeviceWindowsLog&Component1.Action=create&Component1.LogSourceName=REPLACEME&Component1.LogSourceIdentifier=REPLACEME&Component1.Dest.Name=test.domain.com&Component1.Dest.Hostname=test.domain.com&Component1.Dest.Port=514&Component1.Dest.Protocol=TCP&Component1.Log.Security=true&Component1.Log.System=true&Component1.Log.Application=true&Component1.Log.DNS+Server=false&Component1.Log.File+Replication+Service=false&Component1.Log.Directory+Service=false&Component1.RemoteMachinePollInterval=3000&Component1.EventRateTuningProfile=Default+(Endpoint)&Component1.MinLogsToProcessPerPass=100&Component1.MaxLogsToProcessPerPass=150"""'
Where you see the "REPLACEME" string, I need that replaced with the $FQDN variable string. Whenever I use backticks $FQDN or with double quotes"$FQDN" or even single quotes '$FQDN' I get the literal string of "$FQDN" and the snippet of code does not actually do the variable replacement.
What am I missing here? I have also even tried backticks double quotes "$FQDN". I want the REPLACEME string to be replaced with something like the actual hostname + domain like hostname.domain.com or what is set in the $FQDN variable. The ArgumentList quotes need to stay the same as I can only get my command to work correctly by quoting the ArgumentList the way it is starting with a ' and ending with """'. Any help would be greatly appreciated.
This is how it should work using back ticks:
Start-Process -Wait $OUTPATH64 -ArgumentList "/s /v /qn INSTALLDIR=`"C:\Program Files\IBM\WinCollect\`" LOG_SOURCE_AUTO_CREATION_ENABLED=TRUE LOG_SOURCE_AUTO_CREATION_PARAMETERS=`"Component1.AgentDevice=DeviceWindowsLog&Component1.Action=create&Component1.LogSourceName=$FQDN&Component1.LogSourceIdentifier=$FQDN&Component1.Dest.Name=test.domain.com&Component1.Dest.Hostname=test.domain.com&Component1.Dest.Port=514&Component1.Dest.Protocol=TCP&Component1.Log.Security=true&Component1.Log.System=true&Component1.Log.Application=true&Component1.Log.DNS+Server=false&Component1.Log.File+Replication+Service=false&Component1.Log.Directory+Service=false&Component1.RemoteMachinePollInterval=3000&Component1.EventRateTuningProfile=Default+(Endpoint)&Component1.MinLogsToProcessPerPass=100&Component1.MaxLogsToProcessPerPass=150`""
Single-quoted strings ('...') in PowerShell are verbatim (literal) strings in PowerShell - by design, no expansion (interpolation) of embedded variable references or expression is performed.
To get the latter, you must use an expandable string, which is double-quoted ("..."); e.g.,
"...SourceName=$FQDN&Component1... "
Since your string contains embedded " characters, it is simplest to us the here-string variant of an expandable string (#"<newline>...<newline>"#):
Start-Process -Wait $OUTPATH64 -ArgumentList #"
/s /v"/qn INSTALLDIR=\"C:\Program Files\IBM\WinCollect\" LOG_SOURCE_AUTO_CREATION_ENABLED=TRUE LOG_SOURCE_AUTO_CREATION_PARAMETERS=""Component1.AgentDevice=DeviceWindowsLog&Component1.Action=create&Component1.LogSourceName=$FQDN&Component1.LogSourceIdentifier=$FQDN&Component1.Dest.Name=test.domain.com&Component1.Dest.Hostname=test.domain.com&Component1.Dest.Port=514&Component1.Dest.Protocol=TCP&Component1.Log.Security=true&Component1.Log.System=true&Component1.Log.Application=true&Component1.Log.DNS+Server=false&Component1.Log.File+Replication+Service=false&Component1.Log.Directory+Service=false&Component1.RemoteMachinePollInterval=3000&Component1.EventRateTuningProfile=Default+(Endpoint)&Component1.MinLogsToProcessPerPass=100&Component1.MaxLogsToProcessPerPass=150"""
"#
If you used a regular double-quoted string ("..."), you'd have to escape the embedded " characters as `" (or "").
See the bottom section of this answer for more information about PowerShell's string literals; the official help topic is about_Quoting_Rules.

Powershell indexing for creating user logon name

I'm trying to make a user creation script for my company to make things more automated.
I want the script to take the Firstname + Lastname[0] to make the users logon name, but i can't get the syntax right,
I have tried writing {} and () but no luck there.
that's the original peace from my script
New-ADuser...........-UserPrincipalName $fname+$lname[0]
any tips?
Gabriel Luci's helpful answer provides an effective solution and helpful pointers, but it's worth digging deeper:
Your problem is that you're trying to pass expression $fname+$lname[0] as an argument, which requires enclosing (...):
New-ADuser ... -UserPrincipalName ($fname+$lname[0])
PowerShell has two distinct parsing modes, and when a command (such as New-ADUser) is called, PowerShell operates in argument mode, as opposed to expression mode.
Enclosing an argument in (...) forces a new parsing context, which in the case of $fname+$lname[0] causes it to be parsed in expression mode, which performs the desired string concatenation.
In argument mode, unquoted arguments are implicitly treated as if they were enclosed in "...", i.e., as expandable strings under the following circumstances:
If they don't start with (, #, $( or #(.
If they either do not start with a variable reference (e.g., $var) or do start with one, but are followed by other characters that are considered part of the same argument (e.g., $var+$otherVar).
Therefore, $fname+$lname[0] is evaluated as if "$fname+$lname[0]" had been passed:
The + become part of the resulting string.
Additionally, given that inside "..." you can only use variable references by themselves (e.g., $fname), not expressions (e.g., $lname[0]), $lname[0] won't work as intended either, because the [0] part is simply treated as a literal.
Embedding an expression (or a command or even multiple expressions or commands) in "..." requires enclosing it in $(...), the subexpression operator, as in Gabriel's answer.
For an overview of PowerShell's string expansion rules, see this answer.
The following examples use the Write-Output cmdlet to illustrate the different behaviors:
$fname = 'Jane'
$lname = 'Doe', 'Smith'
# WRONG: Same as: "$fname+$lname[0]", which
# * retains the "+"
# * expands array $lname to a space-separated list
# * treats "[0]" as a literal
PS> Write-Output -InputObject $fname+$lname[0]
Jane+Doe Smith[0]
# OK: Use an expression via (...)
PS> Write-Output -InputObject ($fname+$lname[0])
JaneDoe
# OK: Use an (implicit or explicit) expandable string.
PS> Write-Output -InputObject $fname$($lname[0]) # or: "$fname$($lname[0])"
JaneDoe
# OK: Use an intermediate variable:
PS> $userName = $fname + $lname[0]; Write-Output -InputObject $userName
Use a string for the UserPrincipalName, with the variables in the string:
New-ADuser -UserPrincipalName "$fname$($lname[0])"
PowerShell can usually figure out when you put a variable inside a string. When it can't, like in the case of $lname[0], you enclose it in $().
This is called "variable expansion" (other languages, like C#, call it "string interpolation"). Here's a good article that describes it in more detail: https://powershellexplained.com/2017-01-13-powershell-variable-substitution-in-strings/
i just saw the answers and a minute before i realized that i should actually set it up as another variable, $logon = $fname+lname[0]
and pass it as -userPrincipalName $logon.
Thanks for the help, you guy are the best!

Run PowerShell custom function in new window

Function Check-PC
{
$PC = Read-Host "PC Name"
If($PC -eq "exit"){EXIT}
Else{
Write-Host "Pinging $PC to confirm status..."
PING -n 1 $PC
}
This is a snippet of a function I have written into a PowerShell script. I would like the function to run in a new instance of PowerShell, not in the main window.
Is it possible to run this in a separate process of PowerShell without writing it as a separate script and calling the script? Something like this:
$x= Start-Process powershell | Check-PC
I need to keep everything in one script if possible.
Note: It is the involvement of Start-Process that complicates the solution significantly - see below. If powershell were invoked directly from PowerShell, you could safely pass a script block as follows:
powershell ${function:Check-PC} # !! Does NOT work with Start-Process
${function:Check-PC} is an instance of variable namespace notation: it returns the function's body as a script block ([scriptblock] instance); it is the more concise and faster equivalent of Get-Content Function:Check-PC.
If you needed to pass (positional-only) arguments to the script block, you'd have to append -Args, followed by the arguments as an array (,-separated).
Start-Process solution with an auxiliary self-deleting temporary file:
See the bottom half of this answer to a related question.
Start-Process solution with -EncodedCommand and Base64 encoding:
Start-Process powershell -args '-noprofile', '-noexit', '-EncodedCommand',
([Convert]::ToBase64String(
[Text.Encoding]::Unicode.GetBytes(
(Get-Command -Type Function Check-PC).Definition
)
))
The new powershell instance will not see your current session's definitions (unless they're defined in your profiles), so you must pass the body of your function to it (the source code to execute).
(Get-Command -Type Function Check-PC).Definition returns the body of your function definition as a string.
The string needs escaping, however, in order to be passed to the new Powershell process unmodified.
" instances embedded in the string are stripped, unless they are either represented as \" or tripled (""").
(\" rather than the usual `" is needed to escape double quotes in this case, because PowerShell expects \" when passing a command to the powershell.exe executable.)
Similarly, if the string as a whole or a double-quoted string inside the function body ends in (a non-empty run of) \, that \ would be interpreted as an escape character, so the \ must be doubled.Thanks, PetSerAl.
The most robust way to bypass these quoting (escaping) headaches is to use a Base64-encoded string in combination with the -EncodedCommand parameter:
[Convert]::ToBase64String() creates a Base64-encoded string from a [byte[]] array.
[Text.Encoding]::Unicode.GetBytes() converts the (internally UTF-16 -
"Unicode") string to a [byte[]] array.
Note: To also pass arguments, you have two options:
You can "bake" them into the -EncodedCommand argument, assuming you can call a command to pass them to there - see below, which shows how to define your function as such in the new session, so you can call it by name with arguments.Thanks, Abraham Zinala
The advantage of this approach is that you can pass named arguments this way. The disadvantage is that you are limited to arguments that have string-literal representations.
You can use the (currently undocumented) -EncodedArguments parameter, to which you must similarly pass a Base64-encoded string, albeit based on the CLIXML representation of the array of arguments to pass
The advantage of this approach is that you can pass a wider array of data types, within the limits of the type fidelity that CLIXML serialization can provide - see this answer; the disadvantage is that only positional arguments are supported this way (although you could work around that by passing a hashtable that the target code then uses for splatting with the ultimate target command).
Here's a simplified, self-contained example, which uses Write-Output to echo the (invariably positional) arguments received:
$command = 'Write-Output $args'
$argList = 'foo', 42
Start-Process powershell -args '-noprofile', '-noexit',
'-EncodedCommand',
([Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))),
'-EncodedArguments',
([Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes(
[System.Management.Automation.PSSerializer]::Serialize($argList)
)))
In case you want to pass the complete function, so it can be called by name in order to pass arguments as part of the command string, a little more work is needed.
# Simply wrapping the body in `function <name> { ... }` is enough.
$func = (Get-Command -Type Function Check-PC)
$wholeFuncDef = 'Function ' + $func.Name + " {`n" + $func.Definition + "`n}"
Start-Process powershell -args '-noprofile', '-noexit', '-EncodedCommand', `
([Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes("$wholeFuncDef; Check-PC")))
As stated above, you can "bake" any arguments to pass to your function - assuming they can be represented as string literals - into the -EncodedCommand argument, simply by appending them inside the "$wholeFuncDef; Check-PC" string above; e.g.,
"$wholeFuncDef; Check-PC -Foo Bar -Baz Quux"
Start-Process solution with regex-based escaping of the source code to pass:
PetSerAl suggests the following alternative, which uses a regex to perform the escaping.
The solution is more concise, but somewhat mind-bending:
Start-Process powershell -args '-noprofile', '-noexit', '-Command', `
('"' +
((Get-Command -Type Function Check-PC).Definition -replace '"|\\(?=\\*("|$))', '\$&') +
'"')
"|\\(?=\\*("|$)) matches every " instance and every nonempty run of \ chars. - character by character - that directly precedes a " char. or the very end of the string.
\\ is needed in the context of a regex to escape a single, literal \.
(?=\\*("|$)) is a positive look-ahead assertion that matches \ only if followed by " or the end of the string ($), either directly, or with further \ instances in between (\\*). Note that since assertions do not contribute to the match, the \ chars., if there are multiple ones, are still matched one by one.
\$& replaces each matched character with a \ followed by the character itself ($&) - see this answer for the constructs you can use in the replacement string of a -replace expression.
Enclosing the result in "..." ('"' + ... + '"') is needed to prevent whitespace normalization; without it, any run of more than one space char. and/or tab char. would be normalized to a single space, because the entire string wouldn't be recognized as a single argument.
Note that if you were to invoke powershell directly, PowerShell would generally automatically enclose the string in "..." behind the scenes, because it does so for arguments that contain whitespace when calling an external utility (a native command-line application), which is what powershell.exe is - unlike the Start-Process cmdlet.
PetSerAl points out that the automatic double-quoting mechanism is not quite that simple, however (the specific content of the string matters with respect to whether automatic double-quoting is applied), and that the specific behavior changed in v5, and again (slightly) in v6.