Powershell Invoke-Command causes different result - powershell

I have a function that is used to purge a message queue on a machine but I'm looking to adapt it and make it a little more robust. I'd like to be able to fire the command to a machine even if the current machine doesn't have MSMQ installed.
The local command works without issue but when the invoke-command is called, the check to see if the queue exists returns false (even though the queue does exist). Has anyone run into anything like this before? Any suggestions?
This is my function:
Function Purge-MessageQueue
{
<#
.Synopsis
Use hostname to purge message queue
.DESCRIPTION
Checks if MSMQ is locally installed otherwise fire the purge
command to the machine you are purging
.EXAMPLE
Purge-MessageQueue -targetMachine $env:computername -queueName 'test'
#>
Param
(
[Parameter(Mandatory=$true)]
[String]$targetMachine,
[Parameter(Mandatory=$true)]
[string]$queueName
)
Write-Verbose "Purging $queueName queue on: $targetMachine"
$queueName = "$targetMachine\$queueName"
$error.clear()
[void] [Reflection.Assembly]::LoadWithPartialName("System.Messaging")
try {[void][System.Messaging.MessageQueue]::Exists($queueName)}
catch
{
if ($_.exception.ToString() -like '*Message Queuing has not been installed on this computer.*')
{
#push command to machine
$RemoteSuccess = Invoke-Command -ComputerName $targetMachine -ScriptBlock { Param($queueName)
[void] [Reflection.Assembly]::LoadWithPartialName("System.Messaging")
If([System.Messaging.MessageQueue]::Exists($queueName))
{
$queue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queueName
Try{$queue.Purge()}
Catch{$error}
}
} -ArgumentList $queueName
}
}
If(!$error)
{
If([System.Messaging.MessageQueue]::Exists($queueName))
{
$queue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queueName
$queue.Purge()
}
}
If(!$Error -and !$RemoteSuccess)
{
Write-Host "$queueName queue on $targetMachine cleared"
}
Else
{
Write-Warning "Failed locating queue $queueName on $targetMachine"
}
}
NOTES:
In order to identify what exactly is going on, I used write-host on the exists statement and it returns false. The queue is not being found when I pass the scriptblock. It is executing on the other machine (tested writing a file which succeeded). When I run:
Write-Host "$([System.Messaging.MessageQueue]::Exists($queueName))`n$queueName"
$objqueue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queueName
I get the false, the correct queue name, and the following error:
Exception calling "Purge" with "0" argument(s): "The queue does not
exist or you do not have sufficient permissions to perform the
operation."
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : MessageQueueException
+ PSComputerName : XXXXXX
Running the same command directly on the machine works without issue.
I also found someone else trying to do something similar on serverfault:
https://serverfault.com/questions/399178/how-to-retrieve-names-of-all-private-msmq-queues-efficiently
And when I try this:
Invoke-Command -ComputerName $targetMachine -ScriptBlock { Get-MsmqQueue }
I get the following result:
Cannot find specified machine.
+ CategoryInfo : ObjectNotFound: (:) [Get-MsmqQueue], MessageQueueException
+ FullyQualifiedErrorId : MachineNotFound,Microsoft.Msmq.PowerShell.Commands.GetMSMQQueueCommand
This following command does return the data, but it doesn't allow me to send a purge command:
Invoke-Command -ComputerName $targetMachine -ScriptBlock {Get-WmiObject -class Win32_PerfRawData_MSMQ_MSMQQueue}
I also tried to write the content to a script file and then call the file, which when run on the machine, works without issue but not when called via invoke-command:
$filewriter = #"
[Reflection.Assembly]::LoadWithPartialName("System.Messaging")
If([System.Messaging.MessageQueue]::Exists('$queueName'))
{
`$objqueue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queueName
Try{`$objqueue.Purge()}
Catch{`$error}
}
"#
$session = New-PSSession -ComputerName $targetMachine
Invoke-Command -Session $session -ScriptBlock {Param($FileWriter)
$FileWriter | Out-File "C:\Temp\PurgeQueue.ps1"
} -ArgumentList $filewriter
$test = Invoke-Command -Session $session -scriptblock {Pushd "C:\Temp\"
.\PurgeQueue.ps1}

I have not found the cause for this, but I will summarize what I have found and my workaround
Summary:
When invoking msmq commands via invoke-command, only private queues appear and can be manipulated.
Workaround:
I've build a function to deal with purging and adding message to queues by creating scheduled tasks on the remote machine to call the script created by the command.
Function Push-MSMQRemoteCommand
{
Param(
[Parameter(Mandatory=$true)]
$targetMachine,
[Parameter(Mandatory=$true)]
$password,
[Parameter(Mandatory=$true)]
$queueName,
[Switch]$purge,
$user,
$message)
Begin
{
If(!$user){$user = "$env:USERDOMAIN\$env:USERNAME"}
If($purge -and $message.Length -ne 0){Write-Error "Choose to purge or add... not both" -ErrorAction Stop}
$queuepath = "$targetMachine\$queueName"
#build commands to push
If($purge)
{
$scriptblock = #"
[void] [Reflection.Assembly]::LoadWithPartialName("System.Messaging")
If ([System.Messaging.MessageQueue]::Exists('$queuePath')) {
`$queue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queuePath
`$queue.Purge()
}
"#
}
ElseIf($message)
{
If($message.Length -eq 0){Write-Error "No message provided to add message" -ErrorAction Stop}
$scriptblock = #"
[void] [Reflection.Assembly]::LoadWithPartialName("System.Messaging")
`$queue = new-object System.Messaging.MessageQueue "$queuepath"
`$utf8 = new-object System.Text.UTF8Encoding
`$msgBytes = `$utf8.GetBytes('$message')
`$msgStream = new-object System.IO.MemoryStream
`$msgStream.Write(`$msgBytes, 0, `$msgBytes.Length)
`$msg = new-object System.Messaging.Message
`$msg.BodyStream = `$msgStream
`$msg.Label = "RemoteQueueManagerPowershell"
`$queue.Send(`$msg)
"#
}
#Push Commands
Invoke-Command -ComputerName $targetMachine -ScriptBlock {
Param($user,$password,$scriptblock)
$scriptblock | Out-file -FilePath "C:\temp\ManageQueue.ps1" -Force
$action = New-ScheduledTaskAction -execute 'powershell.exe' -Argument '-File "C:\temp\ManageQueue.ps1"'
#scheudling action to start 2 seconds from now
$trigger = New-ScheduledTaskTrigger -Once -At ((Get-Date)+(New-TimeSpan -Seconds 2))
Register-ScheduledTask -TaskName RemoteQueueManager `
-Action $action `
-Trigger $trigger `
-User "$user"`
-Password $password
#Start-Sleep -Seconds 10
Unregister-ScheduledTask -TaskName RemoteQueueManager -Confirm:$false
Remove-Item -Path "C:\temp\ManageQueue.ps1" -Force
} -ArgumentList $user,$password,$scriptblock
}
}

From your analysis I have feeling that it is issue of rights.
Did you check the rights for your user?
If you are a normal user you have to do the following (not an Administrator) on the
destination computer/server/VM:
1) first create a group and add there users
net localgroup "Remote PowerShell Session Users" /add
net localgroup "Remote PowerShell Session Users" the-user /add
2) Invoke GUI
Set-PSSessionConfiguration microsoft.powershell -ShowSecurityDescriptorUI
3) Add Remote PowerShell Session Users group and grant it execute (invoke) rights
4) Restart the service:
Set-PSSessionConfiguration microsoft.powershell -ShowSecurityDescriptorUI
5) the user now should be able to run remote session
The original source is here.

Related

Running a script on a virtual machine using Invoke-Command

I wrote this code:
$vmName = $args[0]
$sign_check_tool = $args[1]
$arguments = $args[2]
$remote_session = New-PSSession -VMName $vmName -Credential $cred
try {
Invoke-Command -Session $remote_session -Block {
$signcheck_output = ./$using:sign_check_tool /accepteula -c $using:arguments
Write-Output "${signcheck_output }"
}
} catch [Exception] {
Remove-PSSession $remote_session
exit 1
}
Exit-PSSession
I want to run this script for several sign check tools that I receive as a parameter, and for different installers. But I get this error:
The term './$using:sign_check_tool' is not recognized as the name of a cmdlet, function, file, or operable
I want to pass as a parameter several types of tools to run for the same installer but I get the previous error. If you could help me, I would be grateful.
I think you need to pass $using:sign_check_tool to -ArgumentList to be picked up, for example:
Invoke-Command -Session $remote_session -Block -ArgumentList $using:sign_check_tool, $using:arguments {
param($tool, $args)
$signcheck_output = ./$tool /accepteula -c $args
Write-Output "${signcheck_output }"
}

Create a script which disables a Windows Account on a target host. Only Admin can execute this action

I want to create a PowerShell script which will disable the windows account, the target host name will be provided as an argument. Only admin should be able to execute this task.
This is what I have tried. Could someone please tell me if this approach is right or is there any better way to do this.
param( [Parameter(Mandatory=$true)] [String] $TargetHost ,
[Parameter(Mandatory=$true)] [String] $TargetUserName ,
[String] $User ,
[String] $Password)
# Set up a trap to properly exit on terminating exceptions
trap [Exception] {
write-error $("TRAPPED: " + $_)
exit 1
}
function DeactivateAccount($TargetHost , $TargetUserName ,$User , $Password){
$TargetHost = $TargetHost #Target Host on which windows account deactivation will be done.
$TargetUserName = $TargetUserName #User Name of Target.
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() #Domain name of the localhost.
$localHost = [System.Net.Dns]::GetHostName()
$localIP = [System.Net.Dns]::GetHostAddresses("$localHost")
#if TargetHost and LocalHost are same.
if($localHost -like $TargetHost -OR $localIP -like $TargetHost) {
if($Domain -eq [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()){
$process = net user $TargetUsername /domain /active:no #Performs the operation on the domain controller in the computer's primary domain.
} else {
$process = net user $TargetUsername /active:no
}
Write-host " $TargetUsername account deactivated "
}
#If TargetHost is remote Host.
else {
$User = $User #Creds to perform admin function.
$Password = $Password
$SecurePassword = new-Object System.Security.SecureString #Convert password into secure string.
$Password.ToCharArray() | % { $SecurePassword.AppendChar($_) }
$Cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist "$User",$securePassword
$newSession = New-PSSession -ComputerName "$TargetHost" -credential $Cred #Used PSSession for persistent connection and credentials to Specify a user account that has permission to perform this action.
$export_username = Invoke-Command -Session $newSession -ScriptBlock {$username=args[1]} # Invoke-Command command uses the Session parameter(here newSession) to run the commands in same session.
if($Domain -eq [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()){
$process = Invoke-Command -Session $newSession -ScriptBlock {net user $username /domain /active:no}
} else {
$process = Invoke-Command -Session $newSession -ScriptBlock {net user $username /active:no}
}
Write-host " $TargetUsername account deactivated "
Remove-PSSession $newSession # Closes Windows PowerShell sessions.
}
if(-not $?) { # Returns true if last command was successful.
Write-Error "Windows Deactivation Failed!!"
exit 1
}
}
DeactivateAccount($TargetHost , $TargetUserName ,$User , $Password)
Couple of things:
Your meant to show some code to show you tried but since you're new to Powershell I'll let that slide :)
Is it a local windows account you are trying to disable or an AD one? For the purpose of this I'll assume local.
Grab this module: https://gallery.technet.microsoft.com/PowerShell-Module-to-255637a3
The dude basically made a module for exactly what you want to do :)
Note: If you have Powershell 5.1+ you won't need the module they added new cmdlets to do this natively.
Credential-wise I wouldn't worry, Powershell can't bypass windows security, it will execute with the permissions of the user that ran the script unless your script specifically gives credentials for another user in the commands.
Let me know how you get on.

Powershell - File path, is not a recognized as the name of a cmdlet. function script file

I am getting the following error,
Errors caught - TRAPPED: System.Management.Automation.RemoteException with message TRAPPED: The term 'D:\ServiceNow\RDC-
Dev-All\agent\scripts\PowerShell\ImMigration_script.ps1' is not recognized as the name of a cmdlet, function, script fil
e, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and t
ry again.
The issue appears to be with the invoke-command
Invoke-Command -Session $Session -ScriptBlock $theCommand2
i have tired using -FilePath with no luck.
Also tired passing the command and param separately :
Invoke-Command -Session $Session -ScriptBlock $theCommand2 -argumentlist $leName
I am triggering the script using:
D:\ServiceNow\RDC-Dev-All\agent\scripts\PowerShell\invokLyncUAdd.ps1 -param1 'CN=lync2013testuser1,CN=Users,DC=test,DC=COMPANY,DC=com' -param2 AD\sys-LyncProATSC -param3 Z0185-XAP0007-S.test.COMPANY.com
###############################################################################
param( $param1, $param2, $param3 )
$ErrorActionPreference = "Stop"
# trap {
# write-output $("TRAPPED: " + $_.Exception.GetType().FullName);
# write-output $("TRAPPED: " + $_.Exception.Message);
# break
#}
$leName = $param1
$leName = ("'" + "$leName" + "'")
$thePath = 'D:\ServiceNow\RDC-Dev-All\agent\scripts\PowerShell'
$theCommand = $thePath+"\ImMigration_script.ps1 -param1 $leName"
$theCommand2 = [Scriptblock]::Create($theCommand)
# Write-Host "We use string $theCommand below"
$Account = $param2
$useP = Get-Content $thePath\'Information.txt'
$Prompt = convertto-securestring $useP -AsPlainText -Force
$leHost = $param3
try{
$Credential = new-object -typename System.Management.Automation.PSCredential
-argumentlist $Account, $Prompt
$Timeout = New-PSSessionOption -IdleTimeout 60000
$Session = New-PSSession -ComputerName $leHost -Credential $Credential -
Authentication Credssp -SessionOption $Timeout -ErrorAction Stop
Invoke-Command -Session $Session -ScriptBlock $theCommand2
}
catch
{
$exceptType = $("TRAPPED: " + $_.Exception.GetType().FullName);
$exceptMess = $("TRAPPED: " + $_.Exception.Message);
}
finally
{
if($exceptType) { "Errors caught - $exceptType with message $exceptMess " } }
Any help would be great, Thanks
The session is being executed on the remote computer, and I believe that's where PowerShell will expect the file to exist.
I would approach it by attempting to load the local script as a scriptblock so that it is in memory:
$thePath = 'D:\ServiceNow\RDC-Dev-All\agent\scripts\PowerShell'
$theCommand = $thePath+"\ImMigration_script.ps1"
$theCommand2 = [Scriptblock]::Create(Get-Content $theCommand)
Then, from your question:
Invoke-Command -Session $Session -ScriptBlock $theCommand2 -argumentlist $leName
Please let me know if this works.
If the file is in local, then
powershell.exe -noexit -file 'D:\ServiceNow\RDC-Dev-All\agent\scripts\PowerShell\invokLyncUAdd.ps1' -param1 'CN=lync2013testuser1,CN=Users,DC=test,DC=COMPANY,DC=com' -param2 'AD\sys-LyncProATSC' -param3 'Z0185-XAP0007-S.test.COMPANY.com'
If It is in the remote system, then make sure you are mentioning the remote path properly in the invoke-command.

Upgraded to PS3, System.Net.WebClient not working on some machines

I am running in a lab environment and need to automate about 50 machines. I am trying to recover an .xml wireless network profile from a server then install it. This command is being sent from 1 server to the 50 clients.
I recently reimaged my some of my clients and upgraded from PS2 to PS3 and now my Download script is not working anymore.
It does work fine on my PS2 workstations. I am assuming that it might be a permission thing, but I'm not sure. ThrustedHosts is set to * and Script execution policy is set to Unrestricted.
Here's a snippet and the error:
function InstallProfile(){
clear
$fonction =
#'
param($profileName)
$File = "c:\profiles\profile.xml"
$webclient = New-Object System.Net.WebClient
$webclient.Proxy = $NULL
$ftp = "ftp://anonymous:anonymous#192.168.2.200/profiles/$profileName"
$uri = New-Object System.Uri($ftp)
Write-Host (hostname)
$webclient.DownloadFile($uri, $File)
write-host (hostname) (netsh wlan add profile filename="c:\profiles\profile.xml")
'#
$profileName = Read-Host "Enter the profile name(XML file must be present in c:\share\profiles\)"
ExecCmd -fonction $fonction -argument $profileName
func_done
}
#
function ExecCmd
{
param(
$fonction,
$argument
)
$PingTest = RetrieveStatus
$results = #{}
$results = $PingTest.up
$results | sort -uniq | out-Null
$fonctionSB = ConvertTo-ScriptBlock($fonction)
foreach($result in $results)
{
$os = "Windows"
try{
$session = New-PSSession -ComputerName $result.address -Credential $credentials -EA stop
}
catch{
$os = "Not Windows"
}
if($os -eq "Windows"){
Invoke-Command $result.address -ScriptBlock $fonctionSB -Arg $argument -Credential $credentials
Get-PSSession | Remove-PSSession
}
else{
Write-Host $result.address "does not support Powershell commands"
}
}
}
And the error:
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
+ PSComputerName : 192.168.2.110
I found a workaround,
I added a try/catch for the webclient.Download, which works for PS2. In the catch portion, I replaced the command with Invoke-WebRequest $uri -OutFile $File
Works fine for PS2 and PS3 this way!

Powershell - Some commands won't run with Invoke-Command

I am trying to send some commands from a server to about 50 clients running Powershell. Most commands work using Invoke-Command. I used the exact same format as my other commands, yet this one won't work. Basically I want to have each client fetch an .xml file from my server to import it later on. I am missing $credentials and other variables from my code sample here but they are setup correctly somewhere else in my script.
Permission wise, TrustedHosts in winrm is set to * and script execution is set to Unrestricted.
clear
$temp = RetrieveStatus
$results = $temp.up #Contains pinged hosts that successfully replied.
$profileName = Read-Host "Enter the profile name(XML file must be present in c:\share\profiles\)"
$File = "c:\profiles\profile.xml"
$webclient = New-Object System.Net.WebClient
$webclient.Proxy = $NULL
$ftp = "ftp://anonymous:anonymous#192.168.2.200/profiles/$profileName"
$uri = New-Object System.Uri($ftp)
$command = {write-host (hostname) $webclient.DownloadFile($uri, $File)}
foreach($result in $results)
{
# download profile from C:\share\profiles
Invoke-Command $result.address -ScriptBlock $command -Credential $credentials
# add profile to wireless networks
# Invoke-Command $result.address -ScriptBlock {write-host (hostname) (netsh wlan add profile filename="c:\profiles\$args[0].xml")} -argumentlist $profileName -Credential $credentials
}
I get the following error:
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (DownloadFile:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Any idea? The same command works flawlessly on the clients when run locally.
You use $webclient within a scriptblock where $webclient will not be defined on the other end. Why don't you create the web client in the scriptblock e.g.:
$command = {
param($profileName)
$File = "c:\profiles\profile.xml"
$webclient = New-Object System.Net.WebClient
$webclient.Proxy = $NULL
$ftp = "ftp://anonymous:anonymous#192.168.2.200/profiles/$profileName"
$uri = New-Object System.Uri($ftp)
Write-Host (hostname)
$webclient.DownloadFile($uri, $File)}
}
$profileName = Read-Host "Enter the profile name(XML file must be present in c:\share\profiles\)"
Invoke-Command $result.address -ScriptBlock $command -Credential $credentials -Arg $profileName
This will require you to provide some of the variables from the client to the remote machine via the -ArgumentList parameter on Invoke-Command. Those supplied arguments then map to the param() statement in the scriptblock.