invoke-command with a parameter accessing UNC - powershell

I am trying to generate some IDs using a adobe tool called adobe-licensing-toolkit.exe.
I need to run the command remotely in 100 computers.
Executing the command manually works flawless
C:\temp\adobe-licensing-toolkit.exe -c -f \\XXXXXXX\c$\temp\IDs.csv
Adobe Licensing Toolkit (1.1.0.98)
Operation Successfully Completed
Now I tried to replicate that using remote PS without success. I think it is a matter of parameters.
The following command ends correctly but it generates the file locally in the remote computer.
Invoke-Command -ComputerName $comp -ScriptBlock { param($whatToDo,$targetCSV) &('C:\TEMP\adobe-licensing-toolkit.exe') --$whatToDo --$targetCSV "C:\temp\ID.csv"} -ArgumentList "generateChallengeKey","filepath"
If I try to use the UNC in the parameter, the result is Operation failed.
Invoke-Command -ComputerName $comp -ScriptBlock { param($whatToDo,$targetCSV) &('\\XXXXXXXX\c$\TEMP\adobe-licensing-toolkit.exe') --$whatToDo --$targetCSV "C:\temp\ID.csv"} -ArgumentList "generateChallengeKey","filepath"
I also tried to add path in the parameter. In that case is powershell who complains.
Invoke-Command -Session $Server01 -ScriptBlock { param($whatToDo,$targetCSV) &('C:\TEMP\FRL\adobe-licensing-toolkit.exe') --$whatToDo --$targetCSV } -ArgumentList #("generateChallengeKey","filepath \\XXXXXXX\c$\temp\ID.csv")
unknown option -- filepath \\XXXXX\c$\temp\ID.csv
+ CategoryInfo : NotSpecified: (unknown option ...c$\temp\ID.csv:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : XXXXXXX
I have the feeling that the issue is in the way parameter is passed but I haven't managed to find the solution.
The exe file is already present in all target computers.
Any suggestion?
Thanks

I would presume you have toolkit present in all remote computer in path: "C:\TEMP\adobe-licensing-toolkit.exe". You can simply use
Invoke-Command -ComputerName $comp -ScriptBlock { & "C:\TEMP\adobe-licensing-toolkit.exe" -c -f \\XXXXX\$env:Computername-IDs.csv}
Adding $env:Computername in share path would generate unique file for each computer.

Related

Powershell VSCode invoke-command from localhost different user for SCCM

Because VSCode is not able to run a powershell console and debug it as a different user i am trying to get arround it with invoked credentials like this:
Start-Service -Name "WinRM"
$cred = Get-Credential -Credential domain\myuser
Invoke-command -Credential $cred -Computer "localhost" -scriptblock {
Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
Set-Location 'XXX:' # my sccm site code
Import-CMComputerInformation -CollectionName "All Systems" -ComputerName "TestComputer" -MacAddress "00:00:00:00:00:69"
}
If i start it in the debugger of VSCode (F5) it starts but cant connect then to the SCCM Server infrastructure. Could someone help me to solve this issue?
Error:
Cannot find drive. A drive with the name 'XXX' does not exist.
+ CategoryInfo : ObjectNotFound: (XXX:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
+ PSComputerName : localhost
This command cannot be run from the current drive. To run this command you must first connect to a Configuration Manager drive.
+ CategoryInfo : DeviceError: (Microsoft.Confi...ormationCommand:ImportComputerInformationCommand) [Import-CMComputerInformation], InvalidOperationException
+ FullyQualifiedErrorId : CommandCannotExecuteFromCurrentDrive,Microsoft.ConfigurationManagement.Cmdlets.Oob.Commands.ImportComputerInformationCommand
+ PSComputerName : localhost
If i logoff from my machine and login with my admin credentials and execute everything in the invoke-command scriptblock it works.
As i am not allowed to work like this by our company policy's is there maybe a alternative way or something i can do to use the visual studio code debugger?
Have you logged onto the SCCM site server interactively with the credentials you are using and opened the console at least once? I believe this initial first opening is required before the drive is accessible remotely...

Running a Setup.exe from a network share, via Invoke-Command in Powershell

PSEXEC started to give me some trouble, and I decided to recode in PowerShell.
This batch command used to work for me, before PSEXEC started messing things up:
psexec -accepteula \\<ServerToBeUpdated> -u <User> -p <Password> cmd /c "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe /silent /Update"
I'm trying to do this with Invoke-Command in Powershell, but with no luck so far.
I've tried many combinations, and googled a lot, and overall it seems that PowerShell is not fond of the UNC path I'm trying to install from.
Here is what I've got:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Start-Process -FilePath "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe" -ArgumentList "/update /silent" -wait }
I get this error message:
This command cannot be run due to the error: Access is denied.
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
+ PSComputerName : DE5441
Some people say that the setup.exe has be copied locally on the remote server. But this does not seem to be an option for me, mainly for two reasons.
My setup.exe identifies that it is not in the right path, then it kills the local the setup.exe process, and automatically starts a new setup.exe from the UNC path.
I also need the ExitCode from my setup.exe, which gets lost when the "killing" starts as mentioned in reason number 1.
As a final note, I did grant access for PowerShell to run remotely with the Enable-PSRemoting command, and I also get expected results from this simple test:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Hostname }
You are experiencing a so called double-hop authentication issue. If using normal authentication you will not be able to authenticate to a second computer from the machine you are invoking the command on.
To solve this you can use CredSSP.
To enable CredSSP on the machine that is being called:
Enable-WSManCredSSP -Role Server -force
To enable CredSSP on the client:
Enable-WSManCredSSP -Role Client -DelegateComputer server.domain.com -force
The -delegateComputer parameter expects a FQDN but also takes wildcards.
After enabling CredSSP you can use it to invoke your command with the parameter -authentication CredSSP

Can I start a remote powershell session from a remote session?

I am able to successfully remote into one of the machines (ComputerA) in our enterprise at work using the following command
Enter-PSSession
Now can i start a new Enter-PSSession within this session to ComputerB? I am not able to do it. I get the following error:
Remote host method PushRunspace is not implemented.
+ CategoryInfo :
+ FullyQualifiedErrorId : System.Management.Automation.Remoting.PSRemotingDataStructureException,Microsoft.PowerSh
ell.Commands.EnterPSSessionCommand
I am able to start a session from a powershell prompt on ComputerA to ComputerB.
Is this even possible?
Thanks.
Enter-PSSession inside another interactive session is not supported. Instead, try Invoke-Command to run commands on a remote computer while being in an interactive session.
PS C:\> Enter-PSSession -ComputerName Server-02
[Server-02]: PS C:\> Invoke-Command -ComputerName Server-03 -ScriptBlock { GCI C:\ } -Credential (Get-Credential)

Uninstall program from Remote Computer

I'd like to uninstall a program from a remote computer. I know the location of the MSI that was used for the install, it's on the remote server and the path can be seen in the variable $MSIPathFile below.
When I run the following script:
$TargetServer = "d-vasbiz01"
$MSIPathFile = "c:\biztalkdeployment\x.Int.MIS-3.0.0.msi"
Invoke-Command -Computer $TargetServer -ScriptBlock {Param($MSIPathFile, $UninstallFlag, $QuietFlag) Start-Process msiexec.exe "/x" $MSIPathFile "/qn"} -ArgumentList "$MSIPathFile", "/x", "/qn"
I get the following error:
Invoke-Command -Computer $TargetServer -ScriptBlock {Param($MSIPathFile, $UninstallFlag, $QuietFlag) Start-Process msiexec.exe "/x" $MSIPathFile "/qn"} -ArgumentList "$MSIPathFile", "/x", "/qn"
A positional parameter cannot be found that accepts argument 'c:\biztalkdeployment\x.Int.MIS-3.0.0.msi'.
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand
Can anyone please advise what I'm doing wrong?
This is not really an answer to my question but it solves my problem of remotely uninstalling an MSI. I hope this can help someone else as I've spent the last 3 hours trying various techniques!
It turns out this can be achieved with a single line of code!
(Get-WmiObject -Class Win32_Product -Filter "Name='x.Int.MIS for BizTalk 2010 3.0.0'" -ComputerName $TargetServer ).Uninstall()
Courtesy of the following technet page: http://technet.microsoft.com/en-us/library/dd347651.aspx
Sorry for the late edit by pc crashed as I was replying so it half updated.
The problem is that the start Start-Process does not seem to expand the variable and execute it with the command. So what I do to get it to work is build up a string containing path to the executable and then another to parameters I would like to use. I then use the Invoke-expression command to execute it .
Here is an example below if you like I can edit your code ,but I thought you might like an example and explanation.
$MSIPathFile = "c:\biztalkdeployment\x.Int.MIS-3.0.0.msi"
$msiexec = "C:\Windows\System32\msiexec.exe"
$arguments = '/x' + $MSIPathFile + " /qn"
Invoke-Expression -Command "$msiexec $arguments"

Batch file has an error that when called from a Powershell script does not allow the batch file to finish

In the script below I am calling a batch file to break mirroring between some dbs. The batch file has a user prompt to start the script but the PS script races right past it. When I call the batch file directly from the powershell console it works fine. How can I keep the script from move past the invoke command block with until the batch file is complete?
$session = New-PSSession -computerName xssqlk02 -credential $cred
Invoke-Command -Session $session -Scriptblock {c:\MSSQL\DBMaintenance\Mirroring\SERVER_Remove_Mirroring.bat xssqlk02 ossqlk02}
Remove-PSSession $session
edit: I trimmed up just the part of the code that I am having problems with. When this is run from a ps script I just noticed (it's been a long day....) I am getting the following error and it runs through the user prompt at that point.
PS C:\Users\dans> C:\Tools\Scripts\test5.ps1
A subdirectory or file c:\MSSQL\DBMaintenance\Mirroring\Common already exists.
+ CategoryInfo : NotSpecified: (A subdirectory ...already exists.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Invalid drive specification
Remove Mirroring for RCM databases between xssqlk02 and ossqlk02: Continue? y/n 0 File(s) copied
Here is what the output is when I just run the batchfile directly from the PS console on the local machine.
PS C:\Documents and Settings\DanS> c:\MSSQL\DBMaintenance\Mirroring\SERVER_Remove_Mirroring.bat xssqlk02 ossqlk02
Remove Mirroring for RCM databases between xssqlk02 and ossqlk02: Continue? y/n y
A subdirectory or file c:\MSSQL\DBMaintenance\Mirroring\Common already exists.
\OPFLSK02\SQLBackupsForTape\DBMaintenance\Mirroring\Common\DB_Create_Snapshots.bat
\OPFLSK02\SQLBackupsForTape\DBMaintenance\Mirroring\Common\DB_Force_Mirror_To_Principal.bat
.......
18 File(s) copied
The error occurs because the batch file does not have a check to see if the directory already exists. How do I handle this is from the invoke command block to allow the script to continue? For the moment I am not able to change the batch file itself.
If Alexey's solution doesn't work, you can try this one:
$job = Invoke-Command -Session $session -Scriptblock { Start-Process -FilePath "C:\MSSQL\DBMaintenance\Mirroring\SERVER_Remove_Mirroring.bat" -ArgumentList "xssqlk02", "ossqlk02" -Wait } -AsJob
$job | Wait-Job
You can try so
Invoke-Command -Session $session -Scriptblock {start c:\MSSQL\DBMaintenance\Mirroring\SERVER_Remove_Mirroring.bat xssqlk02 ossqlk02 -wait}
The idea is that the cmdlet will wait until you finish the bat file.
"Invalid drive specification Remove Mirroring for RCM databases between xssqlk02 and ossqlk02:"
it may indicate that $session dont have access to ossqlk02.
Try appoint yourself an admin on all computers and run script under admin. If it does not help, you can to use utility - PsExec link PsExec support