New-PSsession not working in Script - powershell

I have a strange problem with one of my servers :
I am trying to open a PSsession with it.
If I copy my script directly in powershell everything works fine, but if i run it via a .ps1 file I get a access denied error.
The same sript works on multiple machines except this one.
Additonal information:
Executing Server : Server 2012
Target Server2003SP2
Another Server2003SP2 is working fine without a Problem
the Client Server was configured using :
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts MY2012Server -concatenate -force
Restart-Service WinRM
And the Error Message:
New-PSSession : [Server2003SP2] Connecting to remote server Server2003SP2 failed with the following error message : Access is denied. For more information,
Help topic.
At C:\Users\Administrator\Desktop\Script.ps1:23 char:13
+ $Session = New-PSSession -ComputerName $Servername -credential $Cred #-sessionO ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Edit : My full SCript as requested :
$Password = "Hereismypasswordwith#and€init"
$Username = "Servername\Administrator"
$Servername = "Servername"
$Language = {
$oscode = Get-WmiObject Win32_OperatingSystem -ErrorAction continue
$oscode = $oscode.oslanguage
$switch = switch ($oscode){
1031 {"Deutsch"};
1033 {"English"};
default {"English"};
}
write-host $switch
return $switch
}
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
$pssessionoption = new-pssessionoption -operationtimeout 7200000 -IdleTimeout 7200000
$Session = New-PSSession -ComputerName $Servername -credential $Cred -sessionOption $pssessionoption
Invoke-Command -Session $Session -Scriptblock $Language
Remove-PSSession -Session $Session
UPDATE :
it seems to be something within the Char encoding.
the password in the ps1 file produces a difrent output for the € in it :
in the ps1. ¬
in the ps window : ?
if i pass the Password as a Paramter it also works.
$password.gethash() also prouces difrent outputs. codepage is the same though (chcp)
the script was created in notepad++

Changing / Converting to ansi from UTC without BOM fixed the issue.. jesus crist who thinks about stuff like that / why the hell was it set to this value..

Related

Configuring Remote Desktop Services remotely via powershell

Trying to manage our Remote Desktop Services installation using PowerShell and we're running into an issue where the commands in the RemoteDeskop module and the RemoteDesktopServices module do not appear to work when being run via Invoke-Command. Basically it appears that these functions do not work when run in a remote session.
The script below gets the following error:
The RD Connection Broker server is not available. Verify that you can
connect to the RD Connection Broker server.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-RDServer
+ PSComputerName : AWSELABSDevX13.LABSDEV.com
$server = "OUR_SERVER"
$connection_broker = "OUR_SERVER"
$collectionName ="COLLECTION"
$admin_user = "FULLY_QUALIFIED_DOMAIN_USER"
$password = "PASSWORD"
$password_sec = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($admin_user, $password_sec)
$sb =
{
function Test-IsAdmin {
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
if (Test-IsAdmin) {
""
"You are running with Administrator access."
""
} else {
""
"You do not have admin access."
""
}
whoami /priv
Import-Module RemoteDesktop
Import-Module RemoteDesktopServices
Get-RDServer
}
Invoke-Command -Credential $cred -ComputerName $connection_broker -ScriptBlock $sb

O365 Mobile Device Export

The following code works on our internal exchange server minus the connection bits as thats not needed on-prem. I have added connection code to 365, which works fine. When I run this, I get the following error and it forces me to login a second time and exports only a fraction of the results:
Starting a command on the remote server failed with the following error message : The I/O operation has been aborted
because of either a thread exit or an application request. For more information, see the about_Remote_Troubleshooting
Help topic.
+ CategoryInfo : OperationStopped: (ps.outlook.com:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : JobFailure
+ PSComputerName : ps.outlook.com
Processing data from remote server ps.outlook.com failed with the following error message: WS-Management cannot
process the request. The operation failed because of an HTTP error. The HTTP error (12152) is: The server returned an
invalid or unrecognized response . For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OperationStopped: (ps.outlook.com:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : JobFailure
+ PSComputerName : ps.outlook.com
Below is the code I am attempting to use. Do I have it formatted wrong?
#Script Created by Daniel Taylor 8/8/18
#Set Location for export:
$fLocation = "C:\temp\"
#Get username and password for 0365 connection
$cred = get-credential
#Import microsoft online
Import-module msonline
#Connect to MSonline
connect-msolservice -Credential $cred
#Connect to exchange online
$EolSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri “https://ps.outlook.com/powershell/” -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $EolSession -DisableNameChecking
Write-host "You are now connected to Exchange. Begning ActiveSync Export:" -ForegroundColor DarkGreen
#create File to write report to:
$fName = $fLocation+"ActiveSyncDevices.txt"
$test = test-path $fName
if ($test -eq $True)
{
write-host "Removing Old File..." -ForeGroundColor Red
Remove-Item $fName
}
#Else
#{
#New-Item $fName -type file
#}
Write-host "Creating New File..." -ForeGroundColor Green
New-Item $fName -type file
#Get ActiveSync and Mailbox data
$EASDevices = ""
$AllEASDevices = #()
$EASDevices = ""| select 'User','PrimarySMTPAddress','DeviceType','DeviceModel','DeviceOS', 'LastSyncAttemptTime','LastSuccessSync'
$EasMailboxes = Get-Mailbox -ResultSize unlimited
foreach ($EASUser in $EasMailboxes) {
$EASDevices.user = $EASUser.displayname
$EASDevices.PrimarySMTPAddress = $EASUser.PrimarySMTPAddress.tostring()
foreach ($EASUserDevices in Get-MobileDevice -Mailbox $EasUser.alias) {
$EASDeviceStatistics = $EASUserDevices | Get-MobileDeviceStatistics
$EASDevices.devicetype = $EASUserDevices.devicetype
$EASDevices.devicemodel = $EASUserDevices.devicemodel
$EASDevices.deviceos = $EASUserDevices.deviceos
$EASDevices.lastsyncattempttime = $EASDeviceStatistics.lastsyncattempttime
$EASDevices.lastsuccesssync = $EASDeviceStatistics.lastsuccesssync
$AllEASDevices += $EASDevices | select user,primarysmtpaddress,devicetype,devicemodel,deviceos,lastsyncattempttime,lastsuccesssync
}
}
$AllEASDevices = $AllEASDevices | sort user
$AllEASDevices | Export-Csv $fname
write-host "The script completed successfully! The output file can be found at $fName" -ForeGroundColor Yellow
You cannot be logged in to Exchange on-prem and Exchange online at the same time. They use the same cmdlet and on-prem will take precedence.
If you are using PSRemoting, you must use two different sessions, and it's best to prefix those, so they are unique.
Or, be on the Exchange server directly and do your thing there, and open a new PSRemoting session to O365, prefixed so that the proxied commands have the prefix name.
Then make your O365 calls with the proxied cmdlets, not the on-prem ones.
Example Session setup:
# Exchange PowerShell Remote Management
#
$creds = Import-Clixml -Path $CredPath
$ExchangeSession = New-PSSession -ConfigurationName 'Microsoft.Exchange' `
-ConnectionUri ('http://' + $ExchangeServerFQDN + '/PowerShell') `
-Authentication Kerberos -Credential $Creds.ExpAdmin
Import-PSSession $ExchangeSession -Prefix 'EXP'
$creds = Import-Clixml -Path $CredPath
$ExchangeOnlineSession = New-PSSession -ConfigurationName 'Microsoft.Exchange' `
-ConnectionUri 'https://outlook.office365.com/PowerShell-liveid/' `
-Authentication Basic -Credential $Creds.ExoAdmin -AllowRedirection
Import-PSSession $ExchangeOnlineSession -Prefix 'EXO'
Get-PSSession
Each of the command will have EXP or EXO as part of the name of the proxied cmdlets.
Again, if you are doing this directly on Exchange, you only need the EXO session, and use the on-prem Exchange cmdlets normally.

Could not find or load main class com.smartbear.ready.cmd.runner.pro.SoapUIProTestCaseRunner

I have a Power Shell script that sits on a VM and creates a PSSession to a physical machine and runs a batch file. Running the batch file directly in the physical machine works as expected, however when I try running it remotely from the VM is it throwing up error.
Power Shell:
$Username = "Domain\User"
$Password = ConvertTo-SecureString "Password*" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($Username, $password)
$session = New-PSSession -ComputerName "K2" -Credential $cred
Enter-PSSession -Session $session
Invoke-Command -ComputerName "K2" -ScriptBlock {
Set-Location 'C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner'
& '.\PSTR.bat'
}
Exit-PSSession
Get-PSSession | Remove-PSSession
Batch File:
"C:\Program Files\SmartBear\ReadyAPI-2.4.0\bin\testrunner.bat" -A -j "-fC:\Users\administrator.HYPERSPHERIC\Desktop\Go4Schools Tests\Test Results" "-RJUnit-Style HTML Report" -FXML -EDevTest "C:\Users\administrator.HYPERSPHERIC\Desktop\Go4Schools Tests\Project Saves\SoapUI_Mobile_API_Project.xml"
Error:
PS C:\> C:\Users\administrator.HYPERSPHERIC\Desktop\PS_TR.ps1
C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner>"C:\Program Files\SmartBear\ReadyAPI-2.4.0\bin\testrunner.bat" -A -j "-fC:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Sch
ools Tests\Test Results" "-RJUnit-Style HTML Report" -FXML -EDevTest "C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Project Saves\SoapUI_Mobile_API_Project.xml"
Error: Could not find or load main class com.smartbear.ready.cmd.runner.pro.SoapUIProTestCaseRunner
+ CategoryInfo : NotSpecified: (Error: Could no...oTestCaseRunner:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : K2
Ready API and soapUI use some environment variables in testrunner.bat to set up dependencies and the like. So, whenever I've executed testrunner.bat with a script from outside of the application, I've always CD'ed to the bin directory first:
cd <Ready API installation directory>\bin
./testrunner.bat ...

Invoke-Command with -credentials

I want to invoke a command on a remote server, I do not want to have to put in the password to run the script. I've tried encrypting the password and storing it in a txt file.
$username = "Mydomain\service.account"
$password = cat C:\username-password-encrypted.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential - argumentlist $username, $password
Invoke-command $cred -Computer myserver -scriptblock {param([string]$LocalUser); Add-PSSnapin Citrix* ; Get-BrokerSession -max 10000 | Where-Object brokeringusername -eq "mydomain\$($LocalUser)" | Stop-BrokerSession} -ArgumentList $user
Here is the error I get
Invoke-Command : A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'.
At \\uncpath\citrix\Installation Media\Citrix\Ticketing_script\Ticketing_Script - Copy (3).ps1:70 char:1
+ Invoke-command $cred -Computer MyServer -scriptblock {param([s ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
There has to be an easier way to run this command on myserver without having to put in the password every time.
You just have to specify the -Credential parameter:
Invoke-command -Credential $cred -Computer myserver -scriptblock {param([string]$LocalUser); Add-PSSnapin Citrix* ; Get-BrokerSession -max 10000 | Where-Object brokeringusername -eq "mydomain\$($LocalUser)" | Stop-BrokerSession} -ArgumentList $user
4 years later but here goes:
Frode F. had the right idea in the comments. Your third line has - argumentlist but it must be -ArgumentList, otherwise it will throw New-Object : A positional parameter cannot be found that accepts argument 'ArgumentList'.
Also, when I copy and run your exact code it does not throw the same error which leads me to believe that the code you're running is not the same as the one you've written here. Here are the different errors you've received and the reasons for them:
Incorrect syntax
A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'.
This means that you've not specified the flag correctly, Powershell thinks you're using a flag or parameter called System.Management.Automation.PSCredential. You can simulate this by adding a hyphen like New-Object -TypeName - System.Management.Automation.PSCredential and see for yourself, so your syntax is wrong somewhere.
Incorrect password format
Cannot find an overload for "PSCredential" and the argument count: "2".
This means that the $Password is not in the correct format. You're importing a file called password-encrypted.txt but after this you pass it to ConvertTo-SecureString. Are you sure that the information in the password-encrypted.txt file is passed to both ConvertTo-SecureString and then to ConvertFrom-SecureString before you saved it, like so?
"MyPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\username-password-encrypted.txt"
For more information on how to deal with passwords in Powershell, see this post that goes into detail on how to do credentials in Powershell:
https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-1/
In conclusion
If you run the code you've provided here using both -ArgumentList (instead of - argumentlist) and -Credentials $creds like others have suggested it should run fine. You're most likely not running the code that you've provided here because with these two adjustments the code runs.

Call VBS on a server with parameters

I want to call a VBScript located on a server with a PowerShell script, I want to pass parameters in the VBS by using invoke-command.
Code:
$username = [Environment]::UserName # Get the current user name
# Get with a Credential the logins to connect to an AS400 Server
$credential = $host.ui.PromptForCredential("Login", "Please enter your ID.", "", "")
$ASUser = $credential.Username.Substring(1)
$ASPwrd = $credential.GetNetworkCredential().password
# Call of the VBS on the server with these parameters
Invoke-Command -ComputerName MyServerName -ScriptBlock {
CSCRIPT "C:\MyScript.vbs"
} -ArgumentList $username, $ASUser, $ASpwrd
But I've got an issue caused by the parameters in the VBS, at these lines:
User = WScript.Arguments(0)
UID = WScript.Arguments(1)
PWD = WScript.Arguments(2)
The PowerShell script returns me this error:
C:\MyScript.vbs(64, 1) Microsoft VBScript runtime error: Subscript out of range
+ CategoryInfo : NotSpecified: (C:\Excel Script...pt out of range:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
The line 64 is User = WScript.Arguments(0).
It seems that my VBS does not recognize that I pass parameters, so I think the problem comes from the PS script, I also tried to pass the parameters like this:
Invoke-Command -ComputerName MyServerName -ScriptBlock {
CSCRIPT "C:\MyScript.vbs" $username $ASUser $ASpwrd
}
It does not work.
You're passing arguments into the scriptblock, but you never use them.
Change this:
Invoke-Command -ComputerName MyServerName -ScriptBlock {
CSCRIPT "C:\MyScript.vbs"
} -ArgumentList $username, $ASUser, $ASpwrd
into something like this:
Invoke-Command -ComputerName MyServerName -ScriptBlock {
CSCRIPT "C:\MyScript.vbs" $args[0] $args[1] $args[2]
} -ArgumentList $username, $ASUser, $ASpwrd
or this:
Invoke-Command -ComputerName MyServerName -ScriptBlock {
Param($user, $user2, $pass2)
CSCRIPT "C:\MyScript.vbs" $user $user2 $pass2
} -ArgumentList $username, $ASUser, $ASpwrd