AzureDevops Pipelines Powershell Script New-PsSession Error - powershell

I'm trying to use a simple powershell script. I have such a script file like test.ps1 and its content is as follows.
$Session = New-PSSession -ComputerName MYPRSNLCMPTR
Copy-Item "C:\MyFolder" -Destination "C:\" -ToSession -Recursive
When I right click the test.ps1 and run with the powershell. The script is working. Copying folder on my local computer to remote computer.
When I add this script as a task in azuredevops pipeline this script gives me such an error like this:
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-
PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Does anyone have any idea what could be the cause? What am I missing?

Related

invoke-command with a parameter accessing UNC

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.

Execute a file remotely with powershell

I am trying to run a batch file remotely using Invoke-Command
PS C:\Users\ale> Invoke-Command -ComputerName SERVER -ScriptBlock { Invoke-Expression -Command:"cmd.exe /c 'C:\Test\Extract.bat'" }
The batch file is supposed to output 3 files in C:\Test\ and is running fine locally.
When I execute the command above, here's the output I receive in powershell
NotSpecified: (:String) [], RemoteException
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : SERVER
1_03102021.csv
2_03102021.csv
3_03102021.csv
As I check there was no file in the remote directory. Any advice please?
To call a bat file in powershell where the path has no spaces you can call it directly
PS C:\> c:\temp\bat.bat
If the path/name contains spaces, quote the path and use the command invoke operator &
PS C:\> & "c:\temp\bat with spaces.bat"
So for your command it would be just
Invoke-Command -ComputerName SERVER -ScriptBlock { C:\Test\Extract.bat }

powershell remote script execution errors

I notice an error " Connecting to remote server usa-chicago failed with the following error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic
CategoryInfo : OpenError: (usa-chicago:String) [], PSRemotingTransportException
FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
". Below is the snippet used. Any suggestions?
All the machines are inside a workgroup.
$computers = gc "C:\servers.txt"
$source = "\\usa-chicago\c$\temp\one.jar"
$destination = "c$\july1\folder1\"
foreach ($computer in $computers) {
Invoke-Command -Computername $computer -ScriptBlock { & Copy-Item $using:source -Destination \\$using:computer\$using:destination -Force }
}
Does your user account have access both to the computer and also the share you try to copy something to? It could be that you hit the dreaded 'second hop' problem with PowerShell Remoting: https://learn.microsoft.com/en-us/powershell/scripting/learn/remoting/ps-remoting-second-hop?view=powershell-7
If this is the problem, there are some workarounds for that. What i like to do is:
In the Invoke Command, create a Scheduled Task with the commands you'd like to execute and pass the credentials into it, execute it, and delete it after.

Run Remote PS script to deploy software

I am trying to run a powershell script to deploy an MS Access solution to multiple desktops. I have my script on a server share and I have tried to run it with out success. I have used the invoke-command to try and run the script and get this error message
Access is denied
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException
+ PSComputerName : TESTVM-PC
I have also run all the psremoting commands and also tried the "Multi-hop" command. All with no success.
I have also tried to run the actual code in the script and it does not work.
Invoke-Command -Computer Dpierson-pc -Credential (get-credential) -ScriptBlock {
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force -Verbose
Copy-Item "\\Some\Bogus\Place\Access\*" C:\ -Recurse -Force -Verbose
Start-Process -FilePath "C:\Setup.exe" -PassThru -Verbose
Start-Sleep 30
Stop-Process -name Ninite -Force -Verbose
}
All I get is that the file setup could not be run because it does not exist. and the process then of course cannot be stopped as it does not exist. The credentials are my own and I am a domain admin. Any help would be appreciated. I have thought of making it batch file that I run via a group policy but that is the last thing I want to try as I plan on having more of these in the future.
P.S. I ran the " Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force -Verbose" on the machine locally as well.

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...