I'm trying to deploy a Windows Service using msdeploy.exe. In here I'm using hashtables to make it clear and readable.
For this example, I use the following variables
$WIN_SERVICE_NAME="myService"
$SERVICE_APP_FILE="C:\Users\My User\Desktop\myService.exe"
# Hashtable for the windows service
$params = @{
Name = "$WIN_SERVICE_NAME"
BinaryPathName = "$SERVICE_APP_FILE"
StartupType = "Automatic"
Description = "Release Management Service"
}
In order to make sure I can get correct values using the splatting operator, I used the following command and it returns expected output.
Command: Write-Host @params
Output: -DisplayName: myService -StartupType: Automatic -Description: Release Management Service -Name: myService -BinaryPathName: C:\Users\My User\Desktop\myService.exe
But, when I try to use splatting operator inside double quotes like this:
Write-Host "@params"
It returns @params
as the output without expanding it.
In summary, that's the same thing happening inside my function. I'm using double quotes and splatting operator could not expand.
# Deploying windows service using msdeploy.exe
& "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe" `
-- AVOIDING UNNECESSARY LINES--
-postSync:runCommand="`"powershell if (Get-Service $WIN_SERVICE_NAME -ErrorAction SilentlyContinue){ sc.exe delete $WIN_SERVICE_NAME; New-Service @params; Start-Service $WIN_SERVICE_NAME } else { New-Service @params; Start-Service $WIN_SERVICE_NAME }`""
Could you please help me to fix this issue? I want to expand the splatting operator inside double quotes or need another solution without adding all parameters in a single line. Thanks in advance!
You can't pre-expand a splat variable inside a string. It's directly interpreted by the PowerShell command parser.
Also, the command you are sending to msdeploy is ultimately starting its own PowerShell session. So if you want to use a variable (such as a splat variable), it has to be defined within the code you've written for that session.
So you'd have to add the
$params = @{<blah>}
code within that runCommand string. So something like this:Notice the escaped quotes in the hashtable declaration. You need this because your current PowerShell session will expand the variables like
$WIN_SERVICE_NAME
in the string you're creating. But you still need quotes around the value for the future PowerShell session that will actually be running the code in the command.Rather than using a splat in this case, I suggest just putting the parameters in a single string variable. If you really want to use a slat for clarity or reasons, then make a string variable populated by the splat.
For example: