Enable Remote Desktop Connections with PowerShell
Enter-PSSession does not work when a IPV6 address is entered as the -Computer value.
I cannot get Enter-PSSession to work with a specific IPV6 address and when TrustedHosts is also set to this address.
NOTE: If TrustedHosts is set to "*", then the command succeeds, so I'm pretty sure the target is configured correctly to allow remote access.
Example:
set-item wsman:\localhost\Client\TrustedHosts "fc00:10:114:247:2d0b:6bf8:c982:ce10"
ENTER-PSSession -Computer fc00:10:114:247:2d0b:6bf8:c982:ce10 -Credential <somecred>
----
ENTER-PSSession : Connecting to remote server [fc00:10:114:247:2d0b:6bf8:c982:ce10] failed with the following error message : The WinRM client cannot process the request. Default authentication maybe used with an IP address under the following conditions: the transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure
TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more information on how to set TrustedHosts run the following command: winrm help config. For more
information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ ENTER-PSSession -Computer fc00:10:114:247:2d0b:6bf8:c982:ce10 -Credential Admini ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (fc00:10:114:247:2d0b:6bf8:c982:ce10:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
Move folder
Hello,
need help with little script, now i work with this (manualy)
$text = Get-Content D:\move.txt
$dir = Get-ChildItem D:\Old
foreach ($item in $text) {
foreach ($folder in $dir) {
if ($folder.name -like $item) {
Move-Item "D:\Old\$item" 'D:\Test'
Write-Host "Folder $item moved successfully"
[array]$totalitems += $item
break
}
}
}
I need a script to seek users in the OU ($user = get-aduser -Filter * -SearchBase "OU=TEST,OU=Lab,DC=corp,DC=firma,DC=cz") then used their sAMAccountName, to move folder with name same as user samaccountname.
example:
samaccountname: test8
folder: D:\Old\test8
Thank you for your response,
Jiri
Server 2008 R2 Powershell version 4 cannot use Get-Net* (anything) commands
Brand new to PS here.
I have a new install of 2008R2 and have updated to Powershell 4 by installing Windows Management Framework 4.0. The system has DotNET 4.5.1 on it as well.
I am trying to run a script for setting IP which is part of the example shown in the following blog:
So far I have run into a brick wall as I am unable to break the code for using the Get-NetAdapter command.
In the example, the following is shown: $ipif = (Get-NetAdapter).ifIndex New-NetIPAddress -IPAddress $ipaddress -PrefixLength $ipprefix -InterfaceIndex $ipif -DefaultGateway $ipgw
When running the script, PS errors with"Get-NetAdapter : The term 'Get-NetAdapter' is not recognized as the name of a cmdlet, function, script file, or operable program"
I found that by using "$ipif = Get-Command -Module NetAdapter -InterfaceIndex" , I get nothing. When I use the PowerShell ISE, no error is given either and the Intellisense feature is no help.
I have executedGet-Module on my system and this is the output:
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.0.0.0 ISE {Get-IseSnippet, Import-IseSnippet, New-IseSnippet}
Manifest 3.1.0.0 Microsoft.PowerShell.Management {Add-Computer, Add-Content, Checkpoint-Computer, Clear...
Manifest 3.0.0.0 Microsoft.PowerShell.Security {ConvertFrom-SecureString, ConvertTo-SecureString, Get...
Manifest 3.1.0.0 Microsoft.PowerShell.Utility {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Manifest 3.0.0.0 Microsoft.WSMan.Management {Connect-WSMan, Disable-WSManCredSSP, Disconnect-WSMan...
Executing the command$psversiontable returns the following:
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.18408
BuildVersion 6.3.9600.16406
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
I would welcome suggestions, comments and/or pointers for the correct direction in which to travel.
Thanks in advance
Outlook Account Settings
Hi
I need to add a second account to all users outlook profile.
Is this possible via a powershell script?
Thanks
Using powershell to write to an access database from a .csv file
Writing to an access database seems similar in powershell to how I've always did it in vbscript but there are a few minor differences I don't fully understand.
The script below is how I have been doing it
Option Explicit
'on error resume next
Dim adoCSVConnection, adoCSVRecordSet, strPathToTextfile
Dim strCSVFile, adoJetConnection, adoJetCommand, strDBPath
Dim objScript, strPathToMDB, strTempDB
Const adCmdText1 = &H0001
' Specify path to CSV file.
strPathToTextFile = "C:\New_Hire_Scripts\NewHireDB"
' Specify CSV file name.
strCSVFile = "Newhiredbimport.csv"
' Specify Access database file.
strDBPath = "C:\New_Hire_Scripts\NewHireDB\All_Users.mdb"
' Open connection to the CSV file.
Set adoCSVConnection = CreateObject("ADODB.Connection")
Set adoCSVRecordSet = CreateObject("ADODB.Recordset")
' Open CSV file with header line.
adoCSVConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strPathtoTextFile & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited(,)"""
adoCSVRecordset.Open "SELECT * FROM " & strCSVFile, adoCSVConnection
' Open connection to MS Access database.
Set adoJetConnection = CreateObject("ADODB.Connection")
adoJetConnection.ConnectionString = "DRIVER=Microsoft Access Driver (*.mdb);" _
& "FIL=MS Access;DriverId=25;DBQ=" & strDBPath & ";"
adoJetConnection.Open
' ADO command object to insert rows into Access database.
'Set adoJetCommand = New ADODB.Command
Set adoJetCommand = CreateObject("ADODB.Command")
Set adoJetCommand.ActiveConnection = adoJetConnection
adoJetCommand.CommandType = adCmdText1
' Read the CSV file.
Do Until adoCSVRecordset.EOF
' Insert a row into the Access database.
adoJetCommand.CommandText = "INSERT INTO Domain_Users" _
& "([Username], First_Name, Last_Name, Facility, Work_Phone, Position, Display_Name, PIN, Hire_Date, State, Employee_ID, Employment_Status, Termination_Date) " _
& "VALUES (" _
& "'" & adoCSVRecordset.Fields("Username").Value & "', " _
& "'" & adoCSVRecordset.Fields("First_Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Last_Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Facility").Value & "', " _
& "'" & adoCSVRecordset.Fields("Work_Phone").Value & "', " _
& "'" & adoCSVRecordset.Fields("Position").Value & "', " _
& "'" & adoCSVRecordset.Fields("Display_Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("PIN").Value & "', " _
& "'" & adoCSVRecordset.Fields("Hire_Date").Value & "', " _
& "'" & adoCSVRecordset.Fields("State").Value & "', " _
& "'" & adoCSVRecordset.Fields("Employee_ID").Value & "', " _
& "'" & adoCSVRecordset.Fields("Employment_Status").Value & "', " _
& "'" & adoCSVRecordset.Fields("Termination_Date").Value & "')"
adoJetCommand.Execute
On Error Resume Next
adoCSVRecordset.MoveNext
Loop
adoJetConnection.Close
adoCSVRecordset.Close
adoCSVConnection.Close
Set objScript = Nothing
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
So as shown above vbscript has always worked for me. That being said I feel I should change to powershell because from my perspective it is a more powerful scripting tool. So I searched the forums and found a script shown below I have began to modify. What I want to do is import a text file similar to this one into a database using powershell similar to what I have done in vbscript.
Username,First_Name,Last_Name,Facility,OU,Telephone,Position,DisplayName,EmployeeNUM,HireDate,State,EmployeeID,Employmentstatus,Termination_Date
Test12,Test,User1,TESTFACILITY,8675309,Administrator,Test User1,1111,03 06 2012,NY,2222,NewHire
Test23,Test,User2,TESTFACILITY,8675309,Route Driver,Test User2,2222,03 06 2012,NY,3333,NewHire
Test34,Test,User3,TESTFACILITY,8675309,Billing,Test User3,3333,03 06 2012,NY,4444,NewHire
Test56,Test,User4,TESTFACILITY,8675309,Billing,Test User4,4444,03 06 2012,NY,5555,Termination,1 09 2014
Test78,Test,User5,TESTFACILITY,8675309,Billing,Test User5,5555,03 06 2012,NY,7777,NewHire
Test90,Test,User6,TESTFACILITY,8675309,Sales,Test User6,7777,03 06 2012,NY,1111,NewHire
Test91,Test,User7,TESTFACILITY,8675309,Route Driver,Test User7,7777,03 06 2012,NY,1111,NewHire
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
$filename
="c:\scripts\test.mdb"
$connString
="Provider=Microsoft.Jet.OLEDB.4.0;"
$connString
+="Data Source=${filename}"
$conn
=New-Objectdata.OleDb.OleDbConnection$connString;
$conn
.Open();
$sql
="INSERT INTO Users ( Username, First_Name, Last_Name, Facility, Work_Phone, Position, Display_Name, PIN, Hire_Date, State, Employee_ID, Employment_Status, Termination_Date)"
$sql
+="SELECT 'JDoe', 'John', 'Doe', 'TestFacility','212-867-5309','admin','John Doe','1923','1-1-1919','NY','4444','NewHire'"
$command
=New-Objectdata.OleDb.OleDbCommand$sql
$command
.connection=$conn
$a
=$command.ExecuteNonQuery()
As you can see I'm on track but I want to read the file contents from a .csv file in powershell instead of hard code them. The new hires and terms we get in a comma delimited text file I auto create or term in AD. The access database merely will hold employee info so if we need to look up an employee id we can for a name change etc... In the powershell example I named the db test.mdb and created a table named users with the headers specified above. You can guess that our long term plan is upgrading to powershell to gain functionality such as deleting , modifying , etc.. records rather than just add them. Vbscript is capable of doing those types of things as well but powershell so far has just made everything easier and more reliable. Slowly but surely I am getting all of my old scripts upgraded so this is not a hurry because for now I have a working solution. I will continue to work on this though always appreciate advice as a fresh opinion is always helpful.
Generate Excel which Shows ADUsers and his Groups in a Matrix with AllGroups
Hi There.
I Need an Excel table for managemet, which Shows the following:
The Colums should be named as Username ActiveDirectory and some Properties and ALL Groups which are availible in Active Directory
Each row should then contain Username and in the Column of Group an "X" or somthing else, if the user is in the Group - like a Matrix.
Username,Firstname,Lastname,Group1,Groups2,Group3,Group4...
Username1,Firstname1,Lastname1,,x,,x.. -- User1 is in Group2 and Group4
Username2,Firstname2,Lastname2,x,x,x,x... -- User2 is in Group 1-4
I thought about generating an Hashtable with all AD-Groups and a Hashtable with User and his AD-Groups, but I don't know how to match them.
Have anyone an idea?
Thanks.
Change NIC Adapter binding order
Hi All,
I've looked through many articles and built a script that changes the registry keys for:
"HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Linkage\" Bind"HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Linkage\" Route
But the problem is that it doesn't show that it changed in the UI. Is there somewhere else in the registries that I would need to change it?
Can I determine if my Lenovo Thinkpad is docked?
I want to be able to determine if my Lenovo Thinkpad is in it's docking station or not. I found that this may be available info on some PCs via the ChassisTypes setting in WMI (e.g. (gwmi Win32_SystemEnclosure).ChassisTypes ) but this returns a value of '10' aka 'Notebook' for me. It never returns '12' aka Docking Station, whether docked or not.
When my PC is docked the Windows XP Start menu has an item labelled "Undock Computer" right above the Shutdown option, so it seems like there must be something I can check either in the registry or in WMI, but I can't figure out what. Anyone have any thoughts?
MAC address range
Hi,
I am looking for a way to write out all MAC addresses between a start and end MAC address. Is there any method in doing this easily in Powershell? Is yes, how?
Thank you
Add variables together (Beginner)
Hi - I'm trying to write a script that will back up a folder from my DropBox, but adding a date element so that when the script is run again (say the next day....) the file name isn't a duplicate.
I'm not sure how to create a directory based on the location and the date though.... Perhaps easier to see :
##Script to copy folder from DropBox to Desktop folder ##Make directory variables $DropBox_location = "C:\Users\USER NAME\Dropbox\OTHER NAME\synced dropbox" $Back_Up_Location = "C:\Users\USER NAME\Desktop\DropBackUp" ##Create a unique key number based on date & time for each folder name to use. $ID_Number = Get-Date -Format s ##create a folder which uses the ID variable. $Back_Up_Location_New = $Back_Up_Location && $ID_Number
Its the $Back_Up_Location_New that I'm not really sure about (although I may well be wrong about other elements...)
Hope that's clear.
Thank you.
Can't get ValueFromPipelineByPropertyName to work with Get-ADComputer
Hi!
I am trying to create a CMDlet that will get input from Get-ADuser or Get-ADComputer but i can't get it to work with the ValueFromPipelineByPropertyName property.
The script below only outputs the name of the user or computer but it does not work with Get-ADuser or Get-ADcomputer, it does work if i create my own object as you can see below
function Just-a-Test { [CmdletBinding()] [OutputType([int])] Param ( # Param1 help description [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("Name")] $TheName ) Begin { } Process { Write-Host $thename } End { } } $obj = New-Object psobject -Property @{name = "test"} # Output: Test $obj | Just-a-Test #Output: Just empty rows, Why oh why? Get-ADComputer -Filter * | Just-a-Test
Any idea why?
Thanks!
Incorrect colours displayed by Write-Host
Much of my PowerShell is reporting and I like to use coloured output to make the results easier to interpret. I have on numerous occasions run into a problem with the wrong colours being displayed by Write-Host (no lectures please about not using Write-Host).
I am working in PowerShell ISE.
For instance:
$fgcolor = 'Green' Write-Host "Some text in green?" -ForegroundColor $fgcolor
However it will actually display the text in some other colour.
When I check the value of the variables they are correct.
I have searched online on many occasions but I don't find any reports of anyone else being troubled. My normal work around is to output in HTML and view using a web browser, but that's really not a solution.
Can anyone give me any ideas how I might troubleshoot this further?
Below is my actual code and a picture of some example output:
Function ReportStatusOfAccounts { Write-Host "Pre-Report of all user accounts in the OU $OU" Foreach ($record in $global:allusers) { $Rname = $Rlastlogondate = $Rpasswordlastset = $Rhomedirectory = $Rprofilepath = '' # Set them all to blank so we don't get variable value 'bleed' $Rname = $record.name $Rlastlogondate = $record.lastlogondate ; $Rpasswordlastset = $record.passwordlastset $Rhomedirectory = $record.homedirectory $Rprofilepath = $record.profilepath $global:lldColor = $global:plsColor = 'Black' if ($($record.lastlogondate) -lt $90Days ) { $global:lldColor = 'Green' } if ($($record.lastlogondate) -gt $90Days ) { $global:lldColor = 'Red' } if (-not $Rlastlogondate) { $Rlastlogondate = "No Value " ; $global:lldColor = 'DarkYellow' } if ($($record.passwordlastset) -lt $90Days ) { $global:plsColor = 'Green' } if ($($record.passwordlastset) -gt $90Days ) { $global:plsColor = 'Red' } Write-Host "User " -nonewline -ForegroundColor $global:normalTextColor Write-Host "$($record.name)`t" -nonewline -ForegroundColor $global:variableTextColor Write-Host "`tLast Logon Date: " -nonewline -ForegroundColor $global:normalTextColor Write-Host "$Rlastlogondate $global:lldColor" -nonewline -ForegroundColor $global:lldColor Write-Host "`tPassword Last Set: " -nonewline -ForegroundColor $global:variableTextColor Write-Host "$Rpasswordlastset $global:plsColor" -ForegroundColor $global:plsColor } }
You can see values on the last line should be showing in DarkYellow and Red, but are both in Green
Other note: Use of some colours seems to 'trigger' this behaviour. Up until I tried using 'DarkYellow' this was reporting in Red and Green without problem. However removing the DarkYellow reference (and restarting my 'ISE session) do not cause
the behaviour to revert to correct.
GetHashCode to find Doubles; Can you do it better?
Hi guys!
Last month i post a code of mine(The Full Code is here: http://social.technet.microsoft.com/Forums/it-IT/7acea85b-1d48-4b14-bd97-45c0603c8d64/powershell-basta-usare-un-po-di-logica-xd?forum=benvenutiofftopicit#365d668d-9ea6-4f72-8360-11ec7602f5b0)
The goal of this code is find Doubles but it use MD5 Hash:
$md5Hash = [System.Security.Cryptography.MD5]::Create() $hashBytes = $md5Hash.ComputeHash($bytes)
but it takes a lot of time...
How can i search double faster?
Thanks
A
checking user privilages of account running script
I have a powershell script that occasionally fails on systems that aren't running it with the correct account.
What I want to do is put a check at the beginning of the script to check that the user running the script has admin rights.
In Linux bash scripts I'd use something like this:
if [ "$(id -u)" != "0" ]; then
I've run a few internet searches but I've not been able to find anything...
What is the powershell equivelant to this?
any help would be much appreciated
PowerShell Script to list a server's users, groups, permissions, etc.
Defining a object array in a C# custom type
I'm pulling information from a web service using New-WebServiceProxy with GetRecords, and manipulating how it displays in PS using a custom type. For the sake of the question, the PS code looks like:
function Get-ServerInfo {
param (
[Parameter(ValueFromPipeline=$true)]$ServerName
)
begin {
Add-Type @"
namespace MyTypes {
public class ServerItem {
public string server_name ;
public string ip_address ;
public bool ip_active ;
}
}
"@
$server = New-Object MyTypes.ServerItem
$uri = 'https://mysite.com/servers_list.do?WSDL'
$conn = New-WebServiceProxy -Uri $uri
$getRecords = new-object ( $conn.GetType().Namespace + '.getRecords')
}
process {
$getRecords.server_name = $ServerName
$SNConn.getRecords($getRecords) | %{
New-Object MyTypes.ServerItem -Property @{
name = $_.name
ip_address = $_.ip_address
ip_active = $_.ip_active
}
}
}
}
Get-ServerInfo Server1 | ft-autosize
name ip_address ip_active
---- ---------- ---------
Server1 148.89.245.124 True
Server1 127.0.0.1 False
The WSDL that I'm using is doing an outer join between the server object table, and the IP table, so if the server has two assigned IPs, it returns two records. I would like to add a property to the object like IPInfo, that would retain the ip_address and ip_active structure, but allow be to store it as a single instance on the object I'm returning. So that the return for the server would look like:
Get-ServerInfo Server1 name ip_info ---- ---------- Server1 {148.89.245.124,127.0.0.1} ( Get-ServerInfo Server1 ).ip_info ip_address ip_active ---------- --------- 148.89.245.124 True 127.0.0.1 False
Do I need to define a public Object[] ip_info, or something else. Examples would be appreciated, as this is my first foray into the C# side.
Detect if key is held
I am at a loss on how to handle this. I want a little snippet of code that could detect if a key is held down during the code execution.
So for example if you are holding shift while the code runs it would return true or false based on this.
Thought?
Defining a object array in a C# custom type
I'm pulling information from a web service using PowerShell's New-WebServiceProxy with GetRecords, and manipulating how it displays in PS using a custom type. For the sake of the question, the PS code looks like:
functionGet-ServerInfo{
param (
[Parameter(ValueFromPipeline=$true)]$ServerName
)
begin{
Add-Type@"
namespace MyTypes {
public class ServerItem {
public string server_name ;
public string ip_address ;
public bool ip_active ;
}
}
"@
$server =New-ObjectMyTypes.ServerItem
$uri ='https://mysite.com/servers_list.do?WSDL'
$conn =New-WebServiceProxy-Uri $uri
$getRecords =new-object( $conn.GetType().Namespace+'.getRecords')
}
process {
$getRecords.server_name = $ServerName
$SNConn.getRecords($getRecords)|%{
New-ObjectMyTypes.ServerItem-Property@{
name = $_.name
ip_address = $_.ip_address
ip_active = $_.ip_active
}
}
}
}
Get-ServerInfoServer1| ft-autosize
name ip_address ip_active
---- ---------- ---------
Server1148.89.245.124 True
Server1127.0.0.1 False
The WSDL that I'm using is doing an outer join between the server object table, and the IP table, so if the server has two assigned IPs, it returns two records. I would like to add a property to the object like IPInfo, that would retain the ip_address and ip_active structure, but allow be to store it as a single instance on the object I'm returning. So that the return for the server would look like:
Get-ServerInfoServer1 name ip_info --------------Server1{148.89.245.124,127.0.0.1}(Get-ServerInfoServer1).ip_info ip_address ip_active -------------------148.89.245.124True127.0.0.1False
Do I need to define a public Object[] ip_info, or something else. Examples would be appreciated, as this is my first foray into the C# side.
How to export all AD objects into .xlsx file?
Hi Folks,
I am novice to PowerShell Scripting and managed to build a query which can fetch user object in .csv file.
Here is Query I used for fetching the AD data
Import-Module Activedirectory
Get-ADuser -LdapFilter "(&(objectCategory=person)(!sAMAccountName=*$)(!sAMAccountName=IUSR*)(!sAMAccountName=IWAM*))" -Properties SamAccountName,GivenName,Surname,Title,mail,Enabled, Manager,Department,Office,telephoneNumber | select @{N="LogonName";E={$_.SamAccountName}},@{N="FirstName";E={$_.GivenName}},@{N="LastName";E={$_.Surname}},Title,@{N="Email";E={$_.mail}},@{N="AccountIsDisabled";E={Switch
($_.Enabled){$True {$False};$False {$True}}}}, Manager,Department,Office,telephoneNumber | export-csv C:\ADexport.csv –NoTypeInformation
The problem I am facing here is, I am not able to export data into .xlsx format. I know we can do it later by just changing the extension into .xlsx but I want this to be automated.
Please suggest something which can help me out getting the Powershell output directly into .xlsx format
Regards,
Mahendra
msc