Home > Enterprise >  How to pass an If statement to the Argumentlist of Start-process for PowerShell?
How to pass an If statement to the Argumentlist of Start-process for PowerShell?

Time:12-26

if ($PSVersionTable.PSVersion.Major,$PSVersionTable.PSVersion.Minor -join "." -gt 5.1) {   
    
Start-Process -FilePath "PowerShell.exe" -ArgumentList 'if((get-WindowsOptionalFeature -Online -FeatureName SmbDirect).state -eq "disabled"){Enable-WindowsOptionalFeature -Online -FeatureName SmbDirect -norestart}'
}

else
{
if((get-WindowsOptionalFeature -Online -FeatureName SmbDirect).state -eq "disabled"){Enable-WindowsOptionalFeature -Online -FeatureName SmbDirect -norestart}
}

even though I made it a one-liner, It still won't work. the result is a new PowerShell window opening for a split second and closing.

how can I make it work?

I studied the Argumentlist but couldn't find a way.

CodePudding user response:

Addressing the title of the question, this works ok for me. "powershell -command" is implied.

start-process powershell "if(1 -eq 1) {echo hi} ; pause"

hi
Press Enter to continue...:

This looks like a "losing the doublequotes problem". See also PowerShell stripping double quotes from command line arguments

powershell '"a"'

a : The term 'a' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.

Swap the single and doublequotes.

Start-Process -FilePath "PowerShell.exe" -ArgumentList "if((get-WindowsOptionalFeature -Online -FeatureName SmbDirect).state -eq 'disabled'){Enable-WindowsOptionalFeature -Online -FeatureName SmbDirect -norestart}"

Not that start-process is needed.

PowerShell.exe "if((get-WindowsOptionalFeature -Online -FeatureName SmbDirect).state -eq 'disabled'){Enable-WindowsOptionalFeature -Online -FeatureName SmbDirect -norestart}"

That Enable-WindowsOptionalFeature command works for me in powershell 7.2.8.

  • Related