Powershell concat double black-slash with variable (dollar sign) - powershell

I want to substitute the variable into computer path..
Write-Host \\$store.storeIp\$Global:config.dest
Expected
\\127.0.0.1\D$\foo
Actual
\\#{storeNumber=1111; storeName=CAT; storeIp=127.0.0.1; status=FAILED}.storeIp\#{inputFile=./store-deployment-inp
ut.csv; src=.\foo; dest=D$\foo; destDir=D:; installerFileName=xxx.exe; po=; serviceName=xxx; forceDeploy=False; legacyScript=}.dest
Somehow, look like the powershell output all the object instead of output the select value when in conjuction with \$.

You could do this like this:
Write-Host ("\\{0}\{1}" -f $store.storeIp, $Global:config.dest)
Or since it's a path:
Join-Path $store.storeIp $Global:config.dest

Related

Pass string value having space to another powershell file

I have a powershell script which calls another powershell file passing a string argument.
param (
[string]$strVal = "Hello World"
)
$params = #{
message = "$strVal"
}
$sb = [scriptblock]::create(".{$(get-content $ps1file -Raw)} $(&{$args} #params)")
Somehow the script passes message variable without double quotes so the powershell file receives only the first part of the message variable (before space) i.e. "Hello".
How can I pass the strVal variable with space (i.e. "Hello World")?
A double quote pair signals PowerShell to perform string expansion. If you want double quotes to output literally, you need to escape them (prevent expansion) or surround them with single quotes. However, a single quote pair signals PowerShell to treat everything inside literally so your variables will not interpolate. Given the situation, you want string expansion, variable interpolation, and literal double quotes.
You can do the following:
# Double Double Quote Escape
#{message = """$strVal"""}
Name Value
---- -----
message "Hello World"
# Backtick Escape
#{message = "`"$strVal`""}
Name Value
---- -----
message "Hello World"
Quote resolution works from left to right, which means the leftmost quote type takes precedence. So '"$strVal"' will just print everything literally due to the outside single quote pair. "'$strVal'" will print single quotes and the value of $strVal.

Powershell color formatting with format operator

I'm using a format operator inside a script with a following example:
$current = 1
$total = 1250
$userCN = "contoso.com/CONTOSO/Users/Adam Smith"
"{0, -35}: {1}" -f "SUCCESS: Updated user $current/$total", $userCN
This excpectedly shows the following output:
SUCCESS: Updated user 1/1250 : contoso.com/CONTOSO/Users/Adam Smith
The format operator is there to keep the targeted output text in place with current / total running numbers varying between 1-99999. Without the format operator I could highlight the success line like this:
Write-Host -BackgroundColor Black -ForegroundColor Green "SUCCESS: Updated user $current/$total: $userCN"
But the question is how could I use the highlight-colors combined with the format operator? There's only the -f parameter and it doesn't allow the color parameters because, well, it's not the same thing as Write-Host in the first place.
Unlike other shells, PowerShell allows you to pass commands and expressions as command arguments simply by enclosing them in parentheses, i.e by using (...), the grouping operator.
When calling PowerShell commands (cmdlets, scripts, functions), the output is passed as-is as an argument, as its original output type.
Therefore, Theo's solution from a comment is correct:
Write-Host -BackgroundColor Black -ForegroundColor Green `
("{0, -35}: {1}" -f "SUCCESS: Updated user $current/$total", $userCN)
That is, the -f expression inside (...) is executed and its output - a single string in this case - is passed as a positional argument to Write-Host (implicitly binds to the -Object parameter).
Note that you do not need, $(...), the subexpression operator, in this case:
(...) is sufficient to enclose an expression or command.
In fact, in certain cases $(...) can inadvertently modify your argument, because it acts like the pipeline; that is, it enumerates and rebuilds array expressions as regular PowerShell arrays (potentially losing strong typing) and unwraps single-element arrays:
# Pass a single-element array to a script block (which acts like a function).
# (...) preserves the array as-is.
PS> & { param($array) $array.GetType().Name } -array ([array] 1)
Object[] # OK - single-element array was passed as-is
# $(...) unwraps it.
PS> & { param($array) $array.GetType().Name } -array $([array] 1)
Int32 # !! Single-element array was unwrapped.
# Strongly-typed array example:
PS> & { param($array) $array.GetType().Name } ([int[]] (1..10))
Int32[] # OK - strongly typed array was passed as-is.
# Strongly-typed array example:
PS> & { param($array) $array.GetType().Name } $([int[]] (1..10))
Object[] # !! Array was *enumerated and *rebuilt* as regular PowerShell array.
The primary use of $(...) is:
expanding the output from expressions or commands inside expandable strings (string interpolation)
To send the output from compound statements such as foreach (...) { ... } and if (...) { ... } or multiple statements directly through the pipeline, after collecting the output up front (which (...) does as well); however, you can alternatively wrap such statements & { ... } (or . { ... } in order to execute directly in the caller's scope rather than a child scope) in order to get the usual streaming behavior (one-by-one passing of output) in the pipeline.
Taking a step back: Given that you already can use compound statements as expressions in variable assignments - e.g., $evenNums = foreach ($num in 1..3) { $num * 2 } - and expressions generally are accepted as the first segment of a pipeline - e.g., 'hi' | Write-Host -Fore Yellow - it is surprising that that currently doesn't work with compound statements; this GitHub issue asks if this limitation can be lifted.
In the context of passing arguments to commands:
Use $(...), the subexpression operator only if you want to pass the output from multiple commands or (one or more) compound statements as an argument and/or, if the output happens to be a single object, you want that object to be used as-is or, if it happens to be a single-element array (enumerable), you want it to be unwrapped (pass the element itself, not the array.
Of course, if you're constructing a string argument, $(...) can be useful inside that string, for string interpolation - e.g., Write-Host "1 + 1 = $(1 + 1)"
Use #(...), the array subexpression operator only if you want to pass the output from multiple commands as an argument and/or you want to ensure that the output becomes a array; that is, the output is returned as a (regular PowerShell) array, of type [object[]], even if it happens to comprise just one object. In a manner of speaking it is the inverse of $(...)'s behavior in the single-object output case: it ensures that single-object output too becomes an array.

Powershell - remove currency formatting from a number

can you please tell me how to remove currency formatting from a variable (which is probably treated as a string).
How do I strip out currency formatting from a variable and convert it to a true number?
Thank you.
example
PS C:\Users\abc> $a=($464.00)
PS C:\Users\abc> "{0:N2}" -f $a
<- returns blank
However
PS C:\Users\abc> $a=-464
PS C:\Users\abc> "{0:C2}" -f $a
($464.00) <- this works
PowerShell, the programming language, does not "know" what money or currency is - everything PowerShell sees is a variable name ($464) and a property reference (.00) that doesn't exist, so $a ends up with no value.
If you have a string in the form: $00.00, what you can do programmatically is:
# Here is my currency amount
$mySalary = '$500.45'
# Remove anything that's not either a dot (`.`), a digit, or parentheses:
$mySalary = $mySalary -replace '[^\d\.\(\)]'
# Check if input string has parentheses around it
if($mySalary -match '^\(.*\)$')
{
# remove the parentheses and add a `-` instead
$mySalary = '-' + $mySalary.Trim('()')
}
So far so good, now we have the string 500.45 (or -500.45 if input was ($500.45)).
Now, there's a couple of things you can do to convert a string to a numerical type.
You could explicitly convert it to a [double] with the Parse() method:
$mySalaryNumber = [double]::Parse($mySalary)
Or you could rely on PowerShell performing an implicit conversion to an appropriate numerical type with a unary +:
$mySalaryNumber = +$mySalary

Getting Double Quotation Marks in Write-Host Output

I need to get some double quotations around the GUID=$ntds output. I have tried encompassing the entire string in double quotes to no avail. Single quotes won't work because of the variable.
$Site=Read-Host "ENTER SITE NAME"
$Server=Read-Host "ENTER SERVER NAME"
$NTDS=Get-ADObject -Identity "CN=NTDS Settings,CN=$server,CN=Servers,CN=$site,CN=Sites,CN=Configuration,$((Get-ADDomain).DistinguishedName)" |foreach {$_.objectguid}
write-host "Repadmin /showobjmeta" * "<GUID=$ntds>"
You can use another pair of double quotes to escape like
Write-Host "hello ""200mg"""
Which will output hello "200mg"
Your case it would be
write-host "Repadmin /showobjmeta""<GUID=$ntds>"""
I do not know powershell, but from other languages, you can try:
you can try using double-double quote "" where you want to have ".
"<GUID=""$ntds"">"
or you can try single quotes if permitted on the outside
'<GUID="$ntds">'
or you can try the backslash as escape character before the " making it
"<GUID=\"$ntds\">"
Just try and let me know if you succeeded.

PowerShell Script Arguments Passed as Array

EDIT: I've changed the code here to a simple test case, rather than the full implementation where this problem is arising.
I am trying to call one Powershell script from another, but things aren't working out as I'm expecting. As I understand things, the "&" operator is supposed to expand arrays into distinct parameters. That's not happening for me.
caller.ps1
$scriptfile = ".\callee.ps1"
$scriptargs = #(
"a",
"b",
"c"
)
& $scriptfile $scriptargs
callee.ps1
Param (
[string]$one,
[string]$two,
[string]$three
)
"Parameter one: $one"
"Parameter two: $two"
"Parameter three: $three"
Running .\caller.ps1 results in the following output:
Parameter one: a b c
Parameter two:
Parameter three:
I think that the problem I'm experiencing is $scriptargs array is not expanded, and is rather passed as a parameter. I'm using PowerShell 2.
How can I get caller.ps1 to run callee.ps1 with an array of arguments?
When invoking a native command, a call like & $program $programargs will correctly escape the array of arguments so that it is parsed correctly by the executable. However, for a PowerShell cmdlet, script, or function, there is no external programming requiring a serialize/parse round-trip, so the array is passed as-is as a single value.
Instead, you can use splatting to pass the elements of an array (or hashtable) to a script:
& $scriptfile #scriptargs
The # in & $scriptfile #scriptargs causes the values in $scriptargs to be applied to the parameters of the script.
You're passing the variables as a single object, you need ot pass them independently.
This here works:
$scriptfile = ".\callee.ps1"
& $scriptfile a b c
So does this:
$scriptfile = ".\callee.ps1"
$scriptargs = #(
"a",
"b",
"c"
)
& $scriptfile $scriptargs[0] $scriptargs[1] $scriptargs[2]
If you need to pass it as a single object, like an array, then you can have the callee script split it; the specific code for that would depend on the type of data you're passing.
Use Invoke-Expression cmdlet:
Invoke-Expression ".\callee.ps1 $scriptargs"
As the result you'll get :
PS > Invoke-Expression ".\callee.ps1 $scriptargs"
Parameter one: a
Parameter two: b
Parameter three: c
PS >