Local Powershell script to trigger VBS script inside Citrix instance - powershell

I am trying to get a local powershell script to trigger a VBS script inside a citrix instance. The events should be this:
Citrix Instance opening Windows Explorer ----> Network Path of script typed into the windows explorer session
I'm using the WfIcaLib.dll (ICOSDK) that came with the Citrix receiver install. Documentation PDF for the Citrix ICOSDK is available here
So this is the code I'm using, which works PERFECTLY in Powershell command line, but when I use the 32-bit ISE, it does nothing other than telling me the DLL has been loaded. I get no errors, but the Citrix Client never actually opens like it does when I run the same exact commands through Powershell command line.
#load Citrix ICA Client SDK
[System.Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Citrix\ICA Client\WfIcaLib.dll")
$ICA = New-Object WFICALib.ICAClientClass
$ICA.Address = "***.***.***.***:****"
$ICA.Application = "Windows ExplorerFED6"
$ICA.Username = "******"
$ICA.Domain = "**"
$ICA.Launch = $true
$ICA.Outputmode = [WfIcaLib.OutputMode]::OutputModeNormal
$ICA.SetProp("Password", "*********")
$ICA.TWIMode=$true
$ICA.Connect()
Any ideas?
EDIT: SOLVED - after reopening under 32-bit ISE and getting code to work, I could not run the .ps1 file since it kept defaulting to 64-bit (even if using Open With on 32-bit powershell version). Running the script via command prompt or 32-bit powershell console both worked.
Using any method suggested by Mike Garuccio worked just fine. I will most likely end up using a Task Scheduler to run the script.

It looks like the problem is a versioning one, which you can deal with using start-job (was originally going to do this with a runspace but that's a lot more code for no real benefit). This will start a job to run your code under 32-bit powershell, it should still place any GUI elements or popups on screen but if you need to get any data out from the script later you'll need to receive the job. code would look something like below.
$SB = {
[System.Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Citrix\ICA Client\WfIcaLib.dll")
$ICA = New-Object WFICALib.ICAClientClass
$ICA.Address = "***.***.***.***:****"
$ICA.Application = "Windows ExplorerFED6"
$ICA.Username = "******"
$ICA.Domain = "**"
$ICA.Launch = $true
$ICA.Outputmode = [WfIcaLib.OutputMode]::OutputModeNormal
$ICA.SetProp("Password", "*********")
$ICA.TWIMode=$true
$ICA.Connect()
}
Start-Job -ScriptBlock $SB -RunAs32
get-job | Receive-Job
Alternatively, you could also use a simple .bat file as a launcher with something like C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -file yourscript.ps1
or if you need everything to be wrapped in powershell and the job does not work you can use the solution Here that basically does the same thing but from within powershell (drop the if statement they use tho, just use the stuff contained inside it like below, with any changes you need to make wrt the profile and interactive settings.)
&"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -noninteractive -noprofile -file "C:\Path o\script.ps1" -executionpolicy bypass
hope one of those works for you!

Related

Jenkins PowerShell: Start-Process with Passthru returns a different process ID when executed in Jenkins but not on PowerShell

I'm experiencing a weird scenario where I want to open a .rdp file and get its Process ID on a Jenkins Pipeline.
My PowerShell Script (which based from this answer):
$app = Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "C:\Users\AzureUser\Desktop\MyRDP.rdp /h:900 /w:1600" -WindowStyle Minimized -PassThru
Write-Host $app.id
When I ran this on PowerShell it works as expected. However, when I tried to execute this script on a Jenkins Pipeline, it opens the .rdp file but returns a different process ID.
Here's the screenshot of the result.
I also tried enclosing it in an Invoke-Command to make sure that it runs on a 64-bit Powershell but it did not change a thing.
I'm wondering what might be the other possible cause of this. Any help is going to be appreciated. :)
The solution is just simple. I will post my answer anyway incase anyone might encounter the same problem I have. You just need to make sure that Jenkins runs on 64-bit. That's all and worked like a charm.

Powershell function call causes missing function error using powershell v7 on windows 10

I wrote a script to build all .net projects in a folder.
Issue
The issue is I am getting a missing function error when I call Build-Sollution.
What I tried
I made sure that function was declared before I used it so I am not really sure why it saids that it is not defined.
I am new to powershell but I would think a function calling another functions should work like this?
Thanks in advance!
Please see below for the error message and code.
Error Message
Line |
3 | Build-Sollution $_
| ~~~~~~~~~~~~~~~
The term 'Build-Sollution' 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.
Build-Sollution:
Code
param (
#[Parameter(Mandatory=$true)][string]$plugin_path,
[string]$depth = 5
)
$plugin_path = 'path/to/sollutions/'
function Get-Sollutions {
Get-ChildItem -File -Path $plugin_path -Include *.sln -Recurse
}
function Build-Sollution($solution) {
dotnet build $solution.fullname
}
function Build-Sollutions($solutions) {
$solutions | ForEach-Object -Parallel {
Build-Sollution $_
}
}
$solutions_temp = Get-Sollutions
Build-Sollutions $solutions_temp
From PowerShell ForEach-Object Parallel Feature | PowerShell
Script blocks run in a context called a PowerShell runspace. The runspace context contains all of the defined variables, functions and loaded modules.
...
And each runspace must load whatever module is needed and have any variable be explicitly passed in from the calling script.
So in this case, the easiest solution is to define Build-Sollution inside Build-Sollutions
As for this...
I am new to powershell but I would think a function calling another
functions should work like this?
... you cannot use the functions until you load your code into memory. You need to run the code before the functions are available.
If you are in the ISE or VSCode, if the script is not saved, Select All and hit use the key to run. In the ISE use F8 Selected, F5 run all. In VSCode, F8 run selected, crtl+F5 run all. YOu can just click the menu options as well.
If you are doing this from the consolehost, the run the script using dot sourcing.
. .\UncToYourScript.ps1
It's ok to be new, we all started somewhere, but it's vital that you get ramped up first. so, beyond what I address here, be sure to spend time on Youtube and search for Beginning, Intermediate, Advanced PowerShell for videos to consume. There are tons of free training resources all over the web and using the built-in help files would have given you the answer as well.
about_Scripts
SCRIPT SCOPE AND DOT SOURCING Each script runs in its own scope. The
functions, variables, aliases, and drives that are created in the
script exist only in the script scope. You cannot access these items
or their values in the scope in which the script runs.
To run a script in a different scope, you can specify a scope, such as
Global or Local, or you can dot source the script.
The dot sourcing feature lets you run a script in the current scope
instead of in the script scope. When you run a script that is dot
sourced, the commands in the script run as though you had typed them
at the command prompt. The functions, variables, aliases, and drives
that the script creates are created in the scope in which you are
working. After the script runs, you can use the created items and
access their values in your session.
To dot source a script, type a dot (.) and a space before the script
path.
See also:
'powershell .net projects build run scripts'
'powershell build all .net projects in a folder'
Simple build script using Power Shell
Update
As per your comments below:
Sure the script should be saved, using whatever editor you choose.
The ISE does not use PSv7 by design, it uses WPSv5x and earlier.
The editor for PSv7 is VSCode. If you run a function that contains another function, you have explicitly loaded everything in that call, and as such it's available.
However, you are saying, you are using PSv7, so, you need to run your code in the PSv7 consolehost or VSCode, not the ISE.
Windows PowerShell (powershell.exe and powershell_ise.exe) and PowerShell Core (pwsh.exe) are two different environments, with two different executables, designed to run side-by-side on Windows, but you do have to explicitly choose which to use or write your code to branch to a code segment to execute relative to the host you started.
For example, let's say I wanted to run a console command and I am in the ISE, but I need to run that in Pwsh. I use a function like this that I have in a custom module autoloaded via my PowerShell profiles:
# Call code by console executable
Function Start-ConsoleCommand
{
[CmdletBinding(SupportsShouldProcess)]
[Alias('scc')]
Param
(
[string]$ConsoleCommand,
[switch]$PoSHCore
)
If ($PoSHCore)
{Start-Process pwsh -ArgumentList "-NoExit","-Command &{ $ConsoleCommand }" -PassThru -Wait}
Else {Start-Process powershell -ArgumentList "-NoExit","-Command &{ $ConsoleCommand }" -PassThru -Wait}
}
All this code is doing is taking whatever command I send it and if I use the PoSHCore switch...
scc -ConsoleCommand 'SomeCommand' -PoSHCore
... it will shell out to PSCore, run the code, otherwise, it just runs from the ISE>
If you want to use the ISE with PSv7 adn not do the shell out thing, you need to force the ISE to use PSv7 to run code. See:
Using PowerShell Core 6 and 7 in the Windows PowerShell ISE

Powershell running a cmdlet from a called script

I have a script that calls another script (with arguments). The called script contains the Install-WindowsFeature cmdlet. When I run the script, the called script runs, but returns the following error:
Install-WindowsFeature : The term 'Install-WindowsFeature' 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
Of course, I can run the cmdlet just fine from a PowerShell console. I can also run the called script from a PowerShell console and Install-WindowsFeature works fine. So, is it something to do with calling a script from a script that runs a cmdlet? Here is my calling code:
$script = "C:\Path\script.ps1"
$argumentList = #()
$argumentlist += ("-Arg1", "value")
$argumentlist += ("-Arg2", "value")
$argumentlist += ("-Arg3", "value")
Invoke-Expression "$script $argumentList"
In the called script, I called Install-WindowsFeature as below:
if ($someValue) { Invoke-Command -ScriptBlock {Install-WindowsFeature -Name RSAT-AD-Tools} }
I've also tried it as below:
if ($someValue) { Install-WindowsFeature -Name RSAT-AD-Tools }
12/16/16 EDIT: This script is running in a GUI built with Sapien PowerShell Studio. When I change the build type to "Native" it works. I have to reset my lab to check, but I suspect it will also run if I just run it in the x64 context. This article explains why I think this matters.
Running on Windows Server 2012 R2
Unless you've got a compelling reason for it, let's see if we can clean up your calling pattern a bit - and hopefully make your other issues go away by avoiding the contortionism.
Rather than creating your parameter list as a string, take advantage of parameter splatting. It's good to get out of the habit of treating PowerShell like other scripting languages that don't work with objects.
$splat = #{
Arg1 = "value1";
Arg2 = "value2";
Arg3 = "value3"
}
& c:\path\script.ps1 #splat
Using that on a script.ps1 something like this:
param(
$Arg1,
$Arg2,
$Arg3
)
Write-Host "Arg1 = $Arg1, Arg2 = $Arg2, Arg3 = $Arg3
You'll get an expected output of:
Arg1 = value1, Arg2 = value2, Arg3 = value3
Once you've got that, there's probably no reason to use Invoke-Command on the call to Install-WindowsFeature, unless you're leaving out details like invoking remotely to a server. Invoke-Command { Install-WindowsFeature } still works fine for me on Server 2012R2 with PowerShell 5, and there's no reason it shouldn't.
This assumes you're running this script on a Server that support Install-WindowsFeature, as the other comments point out. Client Windows doesn't support Install-WindowsFeature, and the RSAT tools are installed via a stand-alone RSAT .MSU package, which you manage differently.
Install-WindowsFeature is natively provided with Server Manager on Server 2012R2 - there's no need to Import-Module... unless you've done something to your profile or fouled up your modules folders. One of the earlier versions of Windows Server needed it - but that was a couple versions back. Likewise, Add-WindowsFeature was the old name - and it's still available as an alias for Install-WindowsFeature.
I'm assuming you've tried Install-WindowsFeature directly from the command line to ensure it's in working order, and Get-Module Install-WindowsFeature looks reasonable.
PS C:\Windows\system32> get-module ServerManager
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 2.0.0.0 ServerManager {Get-WindowsFeature, Install-WindowsFeature, Uninstall-Win...
While we're on the topic, there's very little reason to drop to DISM on Server that supports Install-WindowsFeature, and a number of reasons not to.
Server Manager and several other tools (including Win32_ServerFeature) rely on the feature states parsed and understood by the WMI provider used by Install-WindowsFeature. It's possible to enable the right set of features using DISM, but needs attention and detail. Enabling only "part" of a role and feature may get the functionality you want for specific cases, but the role or feature may not show up as installed in Get-WindowsFeature, may not be uninstallable via Remove-WindowsFeature, and may not offer relevant UI features in Server Manager like monitoring health of the role, viewing relevant events, or offering tools for administering it.
Install-WindowsFeature integrates with additional code from the role & features you're installing, and may run additional health and pre-requisite checks to ensure your correctly configured.
DISM featurenames tend to change more often than the role & feature name of Server Manager, so your script portability will be better.
There are other points, but I won't go into them since DISM was primarily a comment fork.
You are probably right, it seems like the script gets executed with x86 PowerShell. I want to share a snippet with you which I use for scripts that needs to run in a specific environment (e. g. x64 PowerShell).
The script restarts itself in a x64 PowerShell if its started as x86 process. Just put this at the top of your script:
# Reinvoke the script as x64 if its called from a x86 process.
if ($env:Processor_Architecture -eq "x86")
{
&"$env:windir\sysnative\WindowsPowerShell\v1.0\powershell.exe" -noprofile -file $myinvocation.Mycommand.path -executionpolicy bypass
exit
}
Also note that the Install-WindowsFeature cmdlet doesn't work on all windows versions so consider to use dism instead:
$featuresToInstall = #('RSAT-AD-Tools')
$dismParameter = #('/online', '/Enable-Feature', ($featuresToInstall | % { '/FeatureName:{0}' -f $_ }), '/NoRestart')
dism #dismParameter
The running environment determines what modules you have access to. When I created this project in PowerShell Studio, it took the default of x86 (a 32 bit environment). This worked but because I was running it on Windows Server 2012 R2 (a 64-bit environment) I did not have access to the powershell modules such as Import-Module and Install-WindowsFeature. Changing this to a x64 project resolved my issue.
In order to avoid this scenario, it is important to make sure you run PowerShell scripts and modules in the architecture that is native to the OS. You can do this by setting the project correctly (if using a tool like PowerShell Studio) or by verifying that you are running in the native mode for that OS with the code Martin Brandl provided.

Module returns different result from the script version [Test-Path]

introduction
I've written my first PowerShell script aimed for retrieving detailed information from a Windows Setup ISO file. Once the basic features achieved, I've started to convert the ps1 script into a psm1 module. I hoped the result would be the module just work like the script but I'm facing issue I'm not able to solve.
You can download my work here, script version and module (roughly translated to English from French).
I successfully installed the module in PSModulePath in:
[Environment]::GetFolderPath("mydocuments")\WindowsPowerShell\Modules
Command usage is very simple. You call it like that:
WinIsoInfo [[-Path] <String>] [<CommonParameters>]
Help is provided by module: man WinIsoInfo
Usage Example:
WinIsoInfo -Path "E:\Win 10\Installation\ISO\Windows 10 x64 fr.iso"
The ps1 script version is the exact same code as the psm1 module but there are commands examples at the end of the file that you can un-comment and edit before running the script.
Current Status
All the tests are and need to be run as admin, in console or PowerShell ISE.
The ps1 script works as expected but the psm1 module doesn't produce the same result.
At line 108 of the code, there is a Test-Path in a Switch statement:
{(Test-Path "$wimPath\sources\install.wim") -or (Test-Path "$wimPath\sources\install.esd")}
In the ps1 script, this Test-Path return True and user get the expected info.
But in the psm1, it seems to return False since Switch statement jump to the next test after this one. So at the end the user gets that the ISO doesn't contain windows setup. I can assure that the Test-Path should return True because I manually checked it while the function was paused by breakpoints.
Hint and lead
There are 2 cases where I manage to get the module work as expected. But only using in PowerShell ISE, NOT in console.
Using Automatic Variable $? in console pane while debugging module
Step to reproduce:
PowerShell ISE is not running.
Open PowerShell ISE as admin.
In console pane, run import-module Get-WinIsoInfo -Force -Global -Verbose or import-module -path X:\Path\To\Modules\Get-WinIsoInfo -Force -Global -Verbose
In console pane, run WinIsoInfo -Path "X:\path\to\AnyWindowsSetup.iso"
In my case, at this point, the command returns there is no Windows Setup in ISO file.
Now open the Get-WinIsoInfo.psm1 and put a breakpoints anywhere between line 90-108.
do step 4 again
While the script is paused at breakpoints, run $? in the console pane then press F10 then F5
And "voilĂ  !" the module return the expected result and will keep working but only during PowerShell ISE session and inside PowerShell ISE. Command run in console still won't work. And the next time I run PowerShell ISE, the module won't find the setup image path again.
Previously run the ps1 script version in PowerShell ISE
Step to reproduce:
PowerShell ISE is not running.
Open PowerShell ISE as admin.
In console pane, run import-module Get-WinIsoInfo -Force -Global -Verbose or import-module -path X:\Path\To\Modules\Get-WinIsoInfo -Force -Global -Verbose
In console pane, run WinIsoInfo -Path "X:\path\to\AnyWindowsSetup.iso"
In my case, at this point, the command returns there is no Windows Setup in ISO file.
Now open the Get-WinIsoInfo.ps1 script, edit a valid command at the end of the code then press F5 to run it.
Note: Since the command in script has the same name as the module previously imported, at this point I don't know if the triggered function is the one from the ps1 script or the one from the module. Tell me if you know.
The script returns the expected result as Windows Setup info.
Close the ps1 file (it is no longer needed in PowerShell ISE for the next to work)
do step 4 again
And "voilĂ  !" the module return the expected result and will keep working but only during PowerShell ISE session and inside PowerShell ISE. Command run in console still won't work. And the next time I run PowerShell ISE, the module won't find the setup image path again.
Conclusion
After the Hint and lead tests, I found out that they were some differences from modules imported in session before and after success. These key modules loaded by PowerShell ISE are Storage and Microsoft.WSMan.Management. I thought I found the solution and added this line to manifest:
RequiredModules = #("Storage";"Microsoft.PowerShell.Management";"Microsoft.PowerShell.Security";"Microsoft.PowerShell.Utility";"Microsoft.WSMan.Management")
I added all the modules that was present after the module works as expected, just to be sure.
I did the same for assemblies but 2 of them could not be imported: Microsoft.Management.Infrastructure.UserFilteredExceptionHandling and Microsoft.Management.Infrastructure.resources
Resulting in this new manifest line:
RequiredAssemblies = #("Microsoft.Management.Infrastructure.Native";"Microsoft.WSMan.Runtime";"System.Security")
Unfortunately, it seems it is not enough to solve the issue.
Maybe other things has to be imported or it's a wrong lead.
I really hope you could reproduce the bug or at least I hope the Hint and lead section will lead you to find the cause and a solution. I'm too novice to understand why this happens on my system.
My setup uses PowerShell v5.0 with Win 8.1 Pro.

How to get command prompt's output into a variable with PowerShell

I'm using PowerShell v3.0 to start a new cmd.exe process, in which I then load up the Visual Studio Command Prompt to perform a build, like so:
Start-Process cmd.exe -ArgumentList $cmdArgumentsToRunMsBuildInVsCommandPrompt -WindowStyle $windowStyle -Wait
This works, and it opens a new command prompt window and I can see the build happen, and then when the build is finished the command prompt window closes. I would like to be able to get the text that is written to the command prompt window and store it in a variable, in order to inspect if the build passed or not. I tried using this, but it doesn't work; the $buildOutput variable is empty:
Start-Process cmd.exe -ArgumentList $cmdArgumentsToRunMsBuildInVsCommandPrompt -WindowStyle $windowStyle -Wait -OutVariable buildOutput
Write-Host "Build output = $buildOutput"
This makes sense since the cmd.exe process isn't returning any text; it is just writing it to it's own window. Is there a way for me to be able to store that text in a variable for the original powershell script to use? I know that I can provide a parameter to MsBuild to have it write the build log to a file, but I'm looking for a solution that doesn't involve writing to a log file and having to delete it later.
Any suggestions are appreciated. Thanks!
<# EDIT #>
Thanks for all of the responses so far! A popular suggestion has been to just call MsBuild.exe directly without using cmd.exe. The reason I need to go through cmd.exe is some projects don't build successfully if called directly from MsBuild.exe (e.g. XNA projects). Instead I need to call MsBuild.exe from the Visual Studio Command Prompt so that (I assume) all of the required environmental variables are set. I guess I could just call the VS Command Prompt directly, but it will have the same problem as calling cmd.exe too. If I can't find the VS Command Prompt I fallback to calling MsBuild.exe directly, so those answers are still appreciated.
You can always capture the output of console programs this way:
$output = [string](nuget.exe)
Here I used nuget ($output will contain the available commands list), but you can of course use msbuild.exe with the appropriate arguments.
I've solved my problem using a suggestion from the first comment on my question, which was to write the build output to a log file, consume it, then delete it. This allows me to still show the user the cmd window with the build progress if they need, as well inspect the build output once the build completes. It also still allows me to run the build in another process, so we can use PassThru if we don't want our script to wait for the build to complete before continuing execution.
I've created an Invoke-MsBuild powershell module to make building with MsBuild a snap while providing lots of parameters for additional functionality (returns if build succeeded or failed, can show/hide build window, can wait/not wait for build to finish, can automatically show build log on failed builds, etc.). You can view and download the script from my blog.
$process = New-Object System.Diagnostics.Process;
$process.StartInfo.UseShellExecute = $false;
$process.StartInfo.RedirectStandardOutput = $true;
$process.StartInfo.FileName = "cmd.exe";
$process.StartInfo.Arguments = $cmdArgumentsToRunMsBuildInVsCommandPrompt;
$process.Start();
$outputStream = $process.StandardOutput;
$outputStream.ReadToEnd();
You could also redirect StandardError.
edit: I ended up using #David Brabant's answer
I ran into this problem and created an echo function
function echo()
{
$input
}
which let me do this
$output = &"cmd.exe" $args | echo