How to set schedule.service "Run whether user is logged on or not" in Powershell? - powershell

I need to create a schedule task using Powershell with "Run whether user is logged on or not".
I use the following codes to create a task, and I've checked the members of settings, principal, triggers, and action, but failed to find the setting I need.
$service = new-object -com("Schedule.Service")
$service.connect($servername)
$rootFolder = $service.Getfolder("\")
$taskDefinition = $service.NewTask(0)
$settings = $taskDefinition.Settings
$principal = $taskDefinition.Principal
$triggers = $taskDefinition.Triggers
$Action = $taskDefinition.Actions.Create( 0)
$rootFolder.RegisterTaskDefinition( $taksName, $taskDefinition, 6, $taskRunAsuser , $taskRunasUserPwd , 0)
Does anyone know how to do that?
Thanks

It was the last parameter in the RegisterTaskDefinition() method... change it from 0 to 1.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa382577(v=vs.85).aspx

Related

How to remove a permission, a member, or a role?

I have this script below to add roles and members and permissions
Import-Module sqlserver
$Server = new-Object Microsoft.AnalysisServices.Tabular.Server
$Server.Connect("SERVER\INSTANCE")
$TabDB = $SERVER.Databases["DATABASENAME"]
$AddRole = new-Object Microsoft.AnalysisServices.Tabular.ModelRole
$AddRole.Name = 'NewRole1'
$AddRole.ModelPermission="Read"
$RoleMember = New-Object Microsoft.AnalysisServices.Tabular.WindowsModelRoleMember
$RoleMember.MemberName = 'DOMAIN\ACCOUNT'
$TabDB.Model.Roles.Add($AddRole)
$AddRole.Members.Add($RoleMember)
$TabDB.Update([Microsoft.AnalysisServices.UpdateOptions]::ExpandFull)
$server.Disconnect()
How can I remove a permission, a member, and a role?
I tried this at least for the role, but the console returns back "False"
$TabDB.Model.Roles.Remove($AddRole)
When working with ssas from powershell (or C# for that matter) you can use the analysisservices namespace of microsoft:
Microsoft analysisservices.
This is an object oriented way of working with ssas databases.
This is an old script I wrote for maintainers:
function addRoleToDb {
$roleName = Read-Host "How should this role be called?"
if ($global:dataBase.Roles.findByName($roleName)) {
echo "This role already exists"
return
} elseif ($roleName -eq "") {
echo "You can't give an empty name for a role."
return
}
echo "Warning: this role will start out empty and will have to be modified in order to be used. (it wil have read permission)"
[Microsoft.AnalysisServices.Role] $newRole = New-Object([Microsoft.AnalysisServices.Role])($roleName)
$global:dataBase.Roles.add($newRole)
$dbperm = $global:dataBase.DatabasePermissions.add($newRole.ID)
$dbperm.Read = [Microsoft.AnalysisServices.ReadAccess]::Allowed
$global:dataBase.Roles.Update()
$dbperm.Update()
return
}
At this point I already had a global variable database.
This is a method that would add a role to the database. Deleting the database would work practically the same, you would get the instance of the role with:
role = database.roles.findbyname()
or
role = database.roles.findbyid()
and then
role.Drop(DropOptions.AlterOrDeleteDependents);
You should check that last line before using it because the alterordeletedependants is something I now use in my c# program, I don't remember if it worked in powershell.
Good luck!

Auto creation of Service without DefaultServices on developer machines

At the recent Service Fabric Community Q&A 24th Edition there was a lot of discussion around using the DefaultService construct in the ApplicationManifest.xml and it's drawbacks. Microsoft suggested omitting this from an ApplicationManifest entirely and instead modifying the Deploy-FabricApplication.ps1 to construct a default implementation of an application so developers still have a decent F5 experience.
So I have modified the Deploy-FabricApplication.ps1 to the following (this excerpt is the bottom of the script):
if ($IsUpgrade)
{
$Action = "RegisterAndUpgrade"
if ($DeployOnly)
{
$Action = "Register"
}
$UpgradeParameters = $publishProfile.UpgradeDeployment.Parameters
if ($OverrideUpgradeBehavior -eq 'ForceUpgrade')
{
# Warning: Do not alter these upgrade parameters. It will create an inconsistency with Visual Studio's behavior.
$UpgradeParameters = #{ UnmonitoredAuto = $true; Force = $true }
}
$PublishParameters['Action'] = $Action
$PublishParameters['UpgradeParameters'] = $UpgradeParameters
$PublishParameters['UnregisterUnusedVersions'] = $UnregisterUnusedApplicationVersionsAfterUpgrade
Publish-UpgradedServiceFabricApplication #PublishParameters
}
else
{
$Action = "RegisterAndCreate"
if ($DeployOnly)
{
$Action = "Register"
}
$PublishParameters['Action'] = $Action
$PublishParameters['OverwriteBehavior'] = $OverwriteBehavior
$PublishParameters['SkipPackageValidation'] = $SkipPackageValidation
Publish-NewServiceFabricApplication #PublishParameters
#Get-ServiceFabricApplication
New-ServiceFabricService -Stateless -ApplicationName "fabric:/Acme.Hierarchy" -ServiceTypeName "Acme.Hierarchy.HierarchyServiceType" -ServiceName "fabric:/Acme.Hierarchy/Acme.Hierarchy.HierarchyService"-InstanceCount 1 -PartitionSchemeSingleton
}
The above fails with the error
FabricElementNotFoundException
However, if you uncomment the line #Get-ServiceFabricApplication you will see that it does in fact return an application of
ApplicationName : fabric:/Acme.Hierarchy
ApplicationTypeName : Acme.HierarchyType
ApplicationTypeVersion : 1.0.0
ApplicationParameters : { "_WFDebugParams_" = "[{"CodePackageName":"Code","Cod
ePackageLinkFolder":null,"ConfigPackageName":null,"Con
figPackageLinkFolder":null,"DataPackageName":null,"Dat
aPackageLinkFolder":null,"LockFile":null,"WorkingFolde
r":null,"ServiceManifestName":"Quantium.RetailToolkit.
Fabric.Hierarchy.HierarchyServicePkg","EntryPointType"
:"Main","DebugExePath":"C:\\Program Files
(x86)\\Microsoft Visual Studio\\2017\\Professional\\Co
mmon7\\Packages\\Debugger\\VsDebugLaunchNotify.exe","D
ebugArguments":"
{6286e1ef-907b-4371-961c-d833ab9509dd} -p [ProcessId]
-tid [ThreadId]","DebugParametersFile":null}]";
"Acme.Hierarchy.HierarchyServ
ice_InstanceCount" = "1" }
Create application succeeded.
and running the command that fails after the publish script has finished works perfectly.
Does anyone have a solution as to how I can get a good developer experience by not using DefaultServices and instead using Powershell scripts?
Thanks in advance
I have updated the answer to add more details why the default services should not be used (In production only).
On service fabric, you have two options to create your services:
The Declarative way, done via Default Services feature where you describe services that should run as part of your application using the ApplicationManifest.
and the Dynamic(Imperative) way using powershell commands to create these services once the application is deployed.
The declarative way bring you the convenience of defining the expected structure of your application, so that Service Fabric does the job of creating and starting instances of your services according to the declaration in the ApplicationManifest. The convenience it gives you is very useful for development purposes, imagine if every time you had to debug an application, it had to: Build > Package > Deployed to Service Fabric > You had to manually start the many services that define your application. This would be too inconvenient, so that is why default service become handy.
Another scenario is when your application definition immutable, that means, the same number of services and instances will stay the same without variation throughout the time it is deployed in production.
But we know this is high unlikely that these definitions will keep the same throughout the years or even hours in a day, because the idea of microservices is that they should be scalable and flexible, so that we can tweak the configuration of individual services independent of each other.
By using default services, would be too complex for the orchestration logic identify what changes has been made on your services compared to the default specified in the original deployment, and in cases of conflict, which configuration should have priority, for example:
The deployed default services define a service with 5 instances, after it is deployed you execute an powershell script to update to 10 instances, then a new application upgrade comes in with the default services having 5 instances or a new value of 8, what should happen? which one is the correct?
You add an extra named services (service of same type with other name) to an existing deployment that is not defined in the default services, what happens when the new deployment comes in and say that this service should not be expected? Delete it? And the data? How this service should be removed from production? If I removed by mistake during development?
A new version deletes an existing service, the deployment fails, how the old service should be recreated? And if there was any data there to be migrated as part of the deployment?
A service has been renamed. How do I track that it was renamed instead of removing the old and adding a new one?
These is some of the many issues that can happen. This is why you should move away from default services and create them dynamically(imperatively), with dynamic services, service fabric will receive an upgrade command and what will happen is:
"This is my new application type package with new service type
definitions, whatever version you get deployed there, replace for this
version and keep the same configuration".
If a new configuration is required, you will provide as parameters for the deployment to override the old values or change it on a separate command. This will make things much simpler, as SF won't have to worry about different configurations and will just apply package changes to deployed services.
You can also find a nice info about these issues on these links:
How not to use service fabric default services
Service Fabric Q&A 10
Service Fabric Q&A 11
Regarding your main question:
Does anyone have a solution as to how I can get a good developer
experience by not using DefaultServices and instead using Powershell
scripts?
if you want a good experience you should use the default services, it is intended for this, give the developer a good experience without worrying about services required to run at startup.
The trick is, during your CI process, you should remove the default services from the application manifest before you pack your application, so that you don't face the drawbacks later.
Removing the defaultServices during CI (Like VSTS Build), you have the benefits of defaultServices on dev environment, don't have to maintain the powershell script versions(if a new version comes along) and the removal of the default services is a very simple powershell script added as a build step. Other than that, everything keeps the same.
Ps: I don't have a real script at hand now, but will be very simple like this:
$appManifest = "C:\Temp\ApplicationManifest.xml" #you pass as parameter
[xml]$xml = Get-Content $appManifest
$xml.ApplicationManifest.DefaultServices.RemoveAll()
$xml.save($appManifest)
The solution here is to use a script named Start-Service.ps1 in the Scripts folder in Application project.
Below is an example script for the Data Aggregation sample Microsoft have provided.
$cloud = $false
$singleNode = $true
$constrainedNodeTypes = $false
$lowkey = "-9223372036854775808"
$highkey = "9223372036854775807"
$countyLowKey = 0
$countyHighKey = 57000
$appName = "fabric:/DataAggregation"
$appType = "DataAggregationType"
$appInitialVersion = "1.0.0"
if($singleNode)
{
$webServiceInstanceCount = -1
$deviceCreationInstanceCount = -1
$countyServicePartitionCount = 1
$deviceActorServicePartitionCount = 1
$doctorServicePartitionCount = 1
}
else
{
$webServiceInstanceCount = #{$true=-1;$false=1}[$cloud -eq $true]
$deviceCreationInstanceCount = #{$true=-1;$false=1}[$cloud -eq $true]
$countyServicePartitionCount = #{$true=10;$false=5}[$cloud -eq $true]
$deviceActorServicePartitionCount = #{$true=15;$false=5}[$cloud -eq $true]
$doctorServicePartitionCount = #{$true=100;$false=5}[$cloud -eq $true]
if($constrainedNodeTypes)
{
$webServiceConstraint = "NodeType == "
$countyServiceConstraint = "NodeType == "
$nationalServiceConstraint = "NodeType == "
$deviceServiceConstraint = "NodeType == "
$doctorServiceConstraint = "NodeType == "
$deviceCreationServiceConstraint = "NodeType == "
}
else
{
$webServiceConstraint = ""
$countyServiceConstraint = ""
$nationalServiceConstraint = ""
$deviceServiceConstraint = ""
$doctorServiceConstraint = ""
$deviceCreationServiceConstraint = ""
}
}
$webServiceType = "DataAggregation.WebServiceType"
$webServiceName = "DataAggregation.WebService"
$nationalServiceType = "DataAggregation.NationalServiceType"
$nationalServiceName = "DataAggregation.NationalService"
$nationalServiceReplicaCount = #{$true=1;$false=3}[$singleNode -eq $true]
$countyServiceType = "DataAggregation.CountyServiceType"
$countyServiceName = "DataAggregation.CountyService"
$countyServiceReplicaCount = #{$true=1;$false=3}[$singleNode -eq $true]
$deviceCreationServiceType = "DataAggregation.DeviceCreationServiceType"
$deviceCreationServiceName = "DataAggregation.DeviceCreationService"
$doctorServiceType = "DataAggregation.DoctorServiceType"
$doctorServiceName = "DataAggregation.DoctorService"
$doctorServiceReplicaCount = #{$true=1;$false=3}[$singleNode -eq $true]
$deviceActorServiceType = "DeviceActorServiceType"
$deviceActorServiceName= "DataAggregation.DeviceActorService"
$deviceActorReplicaCount = #{$true=1;$false=3}[$singleNode -eq $true]
New-ServiceFabricService -ServiceTypeName $webServiceType -Stateless -ApplicationName $appName -ServiceName "$appName/$webServiceName" -PartitionSchemeSingleton -InstanceCount $webServiceInstanceCount -PlacementConstraint $webServiceConstraint -ServicePackageActivationMode ExclusiveProcess
#create national
New-ServiceFabricService -ServiceTypeName $nationalServiceType -Stateful -HasPersistedState -ApplicationName $appName -ServiceName "$appName/$nationalServiceName" -PartitionSchemeSingleton -MinReplicaSetSize $nationalServiceReplicaCount -TargetReplicaSetSize $nationalServiceReplicaCount -PlacementConstraint $nationalServiceConstraint -ServicePackageActivationMode ExclusiveProcess
#create county
New-ServiceFabricService -ServiceTypeName $countyServiceType -Stateful -HasPersistedState -ApplicationName $appName -ServiceName "$appName/$countyServiceName" -PartitionSchemeUniformInt64 -LowKey $countyLowKey -HighKey $countyHighKey -PartitionCount $countyServicePartitionCount -MinReplicaSetSize $countyServiceReplicaCount -TargetReplicaSetSize $countyServiceReplicaCount -PlacementConstraint $countyServiceConstraint -ServicePackageActivationMode ExclusiveProcess
#create doctor
New-ServiceFabricService -ServiceTypeName $doctorServiceType -Stateful -HasPersistedState -ApplicationName $appName -ServiceName "$appName/$doctorServiceName" -PartitionSchemeUniformInt64 -LowKey $lowkey -HighKey $highkey -PartitionCount $doctorServicePartitionCount -MinReplicaSetSize $doctorServiceReplicaCount -TargetReplicaSetSize $doctorServiceReplicaCount -PlacementConstraint $doctorServiceConstraint -ServicePackageActivationMode ExclusiveProcess
#create device
New-ServiceFabricService -ServiceTypeName $deviceActorServiceType -Stateful -HasPersistedState -ApplicationName $appName -ServiceName "$appName/$deviceActorServiceName" -PartitionSchemeUniformInt64 -LowKey $lowkey -HighKey $highkey -PartitionCount $deviceActorServicePartitionCount -MinReplicaSetSize $deviceActorReplicaCount -TargetReplicaSetSize $deviceActorReplicaCount -PlacementConstraint $deviceServiceConstraint -ServicePackageActivationMode ExclusiveProcess -Verbose
#create device creation
New-ServiceFabricService -ServiceTypeName $deviceCreationServiceType -Stateless -ApplicationName $appName -ServiceName "$appName/$deviceCreationServiceName" -PartitionSchemeSingleton -InstanceCount $deviceCreationInstanceCount -PlacementConstraint $deviceCreationServiceConstraint -ServicePackageActivationMode ExclusiveProcess

How do I retrieve PR_RULE_ACTIONS via PowerShell and the EWS Managed API?

I have need of retrieving and inspecting the delegate forwarding rule (the built-in delegate commands in EWS being inadequate for my needs since they choke on groups being used as delegates).
I am able to successfully locate the rule created by "Schedule+ EMS Interface". However, I am unable to retrieve PR_RULE_ACTIONS. Turning on tracing.
I see that the PidTagRuleMsgProvider property is getting returned just fine, but PR_RULE_ACTIONS never does.
I suspect that I am using the wrong MAPI property type in the propertyset definition, but I've gone through everything listed at http://msdn.microsoft.com/en-us/library/exchangewebservices.mapipropertytypetype(v=exchg.140).aspx . Any clues?
Here is the relevant snippet of code:
# Setup Basic EWS Properties for Message Search - Used to locate Hidden Forwarding Rule
$searchFilterForwardRule = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Rule", [Microsoft.Exchange.WebServices.Data.ContainmentMode]::Prefixed, [Microsoft.Exchange.WebServices.Data.ComparisonMode]::Exact)
$itemViewForwardRule = New-Object Microsoft.Exchange.WebServices.Data.ItemView(30, 0, [Microsoft.Exchange.Webservices.Data.OffsetBasePoint]::Beginning)
$itemViewForwardRule.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, [Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)
$itemViewForwardRule.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
# Properties for Hidden Delegate Forwarding Rule
$PID_TAG_RULE_MSG_PROVIDER = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x65EB,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String)
$PID_TAG_RULE_ACTIONS = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6680,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)
# Property Set for Delegate Forward Rule
$propertySetForwardRule = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, $PID_TAG_RULE_MSG_PROVIDER)
$forwardRuleExists = $false
$findResults = $service.FindItems([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $searchFilterForwardRule, $itemViewForwardRule)
If ($findResults.TotalCount -lt 1) {
Write-Error "Failed to find rule" "Error"
} Else {
Foreach ($item in $findResults.Items) {
$item.Load($propertySetForwardRule)
If ($item.ExtendedProperties.Count -ge 1) {
If ($item.ExtendedProperties[0].Value -eq "Schedule+ EMS Interface") {
$forwardRuleExists = $true
write-host "Delegate forwarding rule found." -ForegroundColor Cyan
$propertySetForwardRule.Add($PID_TAG_RULE_ACTIONS)
$item.Load($propertySetForwardRule)
Write-Host "Attempting to retrieve x6680 PR_RULE_ACTIONS (PidTagRuleActions)" -ForegroundColor Cyan
$PR_RULE_ACTIONS = $null
if($Item.TryGetProperty($Pid_Tag_Rule_Actions,[ref]$PR_RULE_ACTIONS)){
return $PR_RULE_ACTIONS
} # endif
else {write-host "TryGetProperty for PR_RULE_ACTIONS failed!" -ForegroundColor Red
} # endelse
} # End If - Correct Message
} # End If - Has Extended Properties
} # End ForEach
} # End If - Message Count
Glen Scales was able to set me on the right path. It turns out that PR_RULE_ACTIONS is not exposed via EWS, but the same data exposed via an attribute called PR_EXTENDED_RULE_ACTIONS. Now I'm happily slinging code to parse the binary blob.
http://msdn.microsoft.com/en-us/library/ee218391(v=EXCHG.80).aspx
The property tag for PR_RULE_ACTIONS is 0x668000FE. You can see it (and the property data) in OutlookSpy (I am its author) - go to the Inbox folder, click IMAPIFolder button, go to the PR_RULES_TABLE tab, select the rule, double click on the PR_RULE_ACTIONS property.
Note that PT_ACTIONS MAPI type (0x000FE) is only accessing in Extended MAPI, I don't think EWS will be able to return it.

Update TFS Build Status via Powershell

I've a TFS Build Definition setup where, I execute a powershell script for security hardening, applying final patches etc.
Sometimes this powershell script can fail and I would like to change the status of build to be un-successfull or fail. Is there a way to change this TFS Build status via a powershell?
Try this:
$script:TFServerName = $ServerName
$script:TFServer = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($ServerName)
$script:TFBuildServer = $TFServer.GetService([Microsoft.TeamFoundation.Build.Client.IBuildServer])
$spec = $TFBuildServer.CreateBuildDetailSpec($TeamProject, $DefinitionName)
$spec.Status = 'Failed'
Make sure you've Add-Type the right versions of the TFS assemblies. I'm assuming here that since the properties support setters, they communicate back to the server to affect the change. But I'm not 100% sure of that.
Here's what I pieced together from MSDN:
[Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Build.Client")
[Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
$tfsServerAddress = "http://{tfs hostname}:{port}/{CollectionName}"
$build = "{build definition name}_{build date}.{build count for the day}"
#update build status
$tfsProject = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServerAddress)
$tfsBuildServer = $tfsProject.GetService([Microsoft.TeamFoundation.Build.Client.IBuildServer])
$spec = $tfsBuildServer.CreateBuildDetailSpec($teamProject)
$spec.BuildNumber = $build
$builds = $tfsBuildServer.QueryBuilds($spec).Builds
if ($builds[0].TestStatus -eq 'Succeeded'){
echo "updating test status:" $builds[0].TestStatus "to $testOutcome"
$builds[0].TestStatus = $testOutcome
}
if ($builds[0].Status -eq 'Succeeded'){
echo "updating build status:" $builds[0].Status "to $testOutcome"
$builds[0].Status = $testOutcome
}
$tfsBuildServer.SaveBuilds($builds)
Keep in mind that you need a special permission to update build status

how to establish and enter a remote session using runspace in powershell

I am trying to establish a session with a remote host B from my machine A, within a C# code. I am using runspace API for that. the code snippet is provided below
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
//constructing the vmname parameter here
vmname = useralias + DateTime.Now.ToString();
Pipeline pipeline = runspace.CreatePipeline();
string scripttext = "$secpasswd = ConvertTo-SecureString '222_bbbb' -AsPlainText –Force";
string scripttext1 = "$mycreds = New-object -typename System.Management.Automation.PSCredential('TS-TEST-09\\Administrator',$secpasswd)";
string scripttext2 = "$s = New-PSSession -ComputerName TS-TEST-09 -Credential $mycreds";
//not accepting session string here, only computername acceptable
**string scripttext3 = "Enter-PSSession -Session $s";**
//Command cmd = new Command(#"C:\mypath\helper.ps1", true);
//cmd.Parameters.Add("local_useralias", useralias);
//cmd.Parameters.Add("local_vmname", vmname);
//cmd.Parameters.Add("local_datastore", datastoredropdown.Text.ToString());
//cmd.Parameters.Add("local_architecture", architecturedropdown.Text.ToString());
pipeline.Commands.AddScript(scripttext);
pipeline.Commands.AddScript(scripttext1);
pipeline.Commands.AddScript(scripttext2);
pipeline.Commands.AddScript(scripttext3);
//pipeline.Commands.Add(cmd);
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
this code is expected to enter into a session with machine TS-TEST-09 and invoke the script helper.ps1 existing on that machine(that part is commented out in the code currently as i am not able to enter into the session with remote host).
now the problem is that i can't enter into the session $s using -Session parameter(highlighted at scripttext3) however i can enter into it using -Computername parameter.
the error that i get when using -Session parameter in scripttext3 is :
at
invokedSystem.Management.Automation.Internal.Host.InteralHost.GetIHostSupportsInteractiveSession()
at invokedSystem.Management.Automation.
Internal.Host.InteralHost.PushRunspace(Runspace runspace)
at Microsoft.Powershel.Commands.EnterPSSessionCommand.ProcessRecord()
at System.Management.Automation.Cmdlet.DoProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()
end of inner exception stack trace
does it mean i have to write a custom PSHost and add support for the Enter-PSSession cmdlet with this parameter?
Is there any alternative to make this command work?
any help will be much appreciated.
Thanks,
Manish
The easiest way to open a remote session goes something like this:
string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
var target = new Uri("http://myserver/wsman");
var secured = new SecureString();
foreach (char letter in "mypassword")
{
secured.AppendChar(letter);
}
secured.MakeReadOnly();
var credential = new PSCredential("username", secured);
var connectionInfo = new WSManConnectionInfo(target, shell, credential);
Runspace remote = RunspaceFactory.CreateRunspace(connectionInfo);
remote.Open();
using (var ps = PowerShell.Create())
{
ps.Runspace = remote;
ps.Commands.AddCommand("'This is running on {0}.' -f (hostname)");
Collection<PSObject> output = ps.Invoke();
}
You could also create remote pipelines from the remote runspace instance, but the new PowerShell object is a much more managable way to do this (since powershell v2.)
In powershell v3, you can just new up a WSManConnectionInfo and set the ComputerName property as the other properties adopt the same defaults as the above. Unfortunately these properties are read-only in v2 and you have to pass in the minimum as above. Other variants of the constructor will let you use kerberos/negotiate/credssp etc for authentication.
-Oisin
I wanted to leave a comment on the solution, as it helped me alot as well,
but one thing i was missing was the port for WSMan which is 5985
so this
var target = new Uri("http://myserver/wsman");
should be
var target = new Uri("http://myserver:5895/wsman");
in my case
Have you tried Invoke-Command? Enter-PsSession is there for interactive use. (see help Enter-PsSession -online).