Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Exchange online- The WinRM client cannot process the request because the server name cannot be resolved

$
0
0

When i tried to connect to Exchange online by using powershellthe following error arises for me.

$LiveCred = Get-Credential

Username

password

$Session = New-PSSession -ConfigurationName Microsoft.Exchange

 -ConnectionUri https://ps.outlook.com/powershell/ -Credential 

$LiveCred -Authentication Basic -AllowRedirection //While creating session the error

occurs."[ps.outlook.com] The WinRM client cannot process the request because the server name

 cannot be resolved"..


i have configured the winrm correctly..



C:\Windows\system32>winrm quickconfig
WinRM is already set up to receive requests on this machine.
WinRM is already set up for remote management  on this machine.

But still the error exists for me.







Creating one custom object out one .net static method and one parameter

$
0
0

Hey Guys got this code:

$Comps = Get-Content C:\comps.txt

Foreach ($i in $comps) {
Try
{
Write-Host $i
[System.Net.Dns]::GetHostAddresses("$i") | fl IPAddressToString -ErrorAction stop
}
Catch 
{
Write-Host "Computer $i is not accessible `n"
continue 
}
    }

C:\comps is just a list of computers - I'm getting there last seen IP's from our DNS records - what I would like to do however is instead of printing 

Computer Name

<Output of static method>  as two seperate lines 

I'd much rather create an object with two parameters - Name of computer, and IP address. How can I take the output of the write-host and the output of the static method and place them into one object? This would make formatting much easier and I would be able to export to csv.

Thanks guys. 

Powershell v3 Installation

$
0
0

Hi All

To Install Powershell version 3 does the whole WMF need to be installed (is it dependant on the other bits) or can v3 of powershell be installed without the rest of the bits being installed also?

Thanks in advance for any assistance.

DbNull Treatment in PoSh 2 vs. 3

$
0
0

PoSh v3 apparently interprets System.DbNull values differently than PoSh v2.

In v2, this expression returns True: [System.DbNull]::Value -eq $null. In v3, it returns False.

More specifically, in v3 ([System.DbNull]::Value).Length returns 1, whereas in v2 it returns $null.

Has anybody else seen this?

Delete files/folders on remote servers using powershell

$
0
0

Hello,

 i am new to powershell.

i am trying to delete some files & folders from remote computers (server-1, server-2. server-3, server-4) 

Some are windows 2003 server are some are 2008

folders to be deleted from server are been imported to script from files.txt (c:\temp\*.*, c:\Windows\temp\*.*, c:\recycler\*.*, c:\documents and settings\*.* -except Default, All users,Administrator. 60 (profiles older than 60 days)

c:\windows\$NTUnunstaller , 30(older than 30 days), c:\users\*.* - except Default, All users, Administrator

c:\$abcd$\*.* 30

i am having this script in VB that works with only windows 2003 i am looking for script in powershell.

Deleted file log should be saved to log.txt with date

thanks in advance


Thanks, jeevan

Date comparison failing at the same times each day

$
0
0

I have a script that checks the last run time of a scheduled task on a windows 2012 server. If the last run time was before 35 minutes ago..... it sends me an email. Works great until 1:17AM and 1:17pm. Then I get an email. The logs show the task ran at the right time.....the check that powershell does is failing (I guess) even though the last run time is within the success parameters??? I'm at a loss. Any help would be appreciated.

Here is the almost awesome script:

$tasklists = Get-Content 'C:\Scripts\Monitoring\ScheduledTasksList.txt'
ForEach($tasklists in $tasklists)
{
$servername = "Server1"
$schedule = new-object -com("Schedule.Service")
$schedule.connect($servername)
$tasks = $schedule.getfolder("\").gettasks(0) | Where-Object {$_.Enabled -like 'True' -and $_.Name -like $tasklists}
$tasks | select name, state, lastruntime, lasttaskresult, NextRunTime, Enabled, NumberOfMissedRuns
$LRT = $tasks.LastRunTime.ToString("MM-dd-yyyy hh:mm tt")
$DateTime = (get-date).AddMinutes(-35).ToString("MM-dd-yyyy hh:mm tt")
If($LRT -le $DateTime)
{
$TaskInfo = $tasks | select name, state, lastruntime, lasttaskresult, NextRunTime, Enabled, NumberOfMissedRuns| Out-String
Send-MailMessage -From "myemail@email.org" -To "myemail@email.org" -Subject "Bla bla" -Body "A scheduled task on Server1 called $tasklists last ran at $LRT `n $TaskInfo" -smtpServer mysmtp@email.org
}
}


Please mark my post as helpful or the answer or better yet.... both! :) Thanks!

using powershell for tpm enabling and encryption

$
0
0

Hello All,

  In an old version of a software install I am creating, I used manage-bde in the win 7 standard environment to do bitlocker driver encryption. I had a script that did the following steps

1.  Turn the tpm chip on  ( manage-bde -tpm -t   )

2. Give the chip a new owner ("manage-bde -tpm -o "NewOwnerName")

3. Begin encryption ( manage-bde -on C: )

There was a reboot between each step because of the tpm chip and chipset but thats no big deal. So now I am trying to do these same steps in WinPe (Windows 8). It turns out that i can't use the manage-bde command line in WinPe, it tells me I have to use powershell. So I have installed powershell and all the needed packages to my Winpe boot image, but haven't found any clear instructions of how to do the steps above (or the equivalent) using powershell commands. Any ideas?

How to update TerminalServicesProfilePath domain-wide?

$
0
0

OS = Server 2003 x86 SP1

PS = v 2.0

I need to find all users in our domain that have a TS User Profile and update the path to a new destination.  The problem is Get-ADUser cannot access the terminal services profile path.

I've been experimenting with the script below but I need to search the entire domain (not a specific user), test if the TerminalServicesProfilePath exists, then update it.

How do I loop the entire domain and test if a path value exists?

thx

function SetTSProperties()
{
 $ou = [adsi]"LDAP://ou=mytestou,dc=nwtraders,dc=com"
 $user = $ou.psbase.get_children().find($userDN)
 $user.psbase.invokeSet("allowLogon",1)
 $user.psbase.invokeSet("TerminalServicesHomeDirectory",$hDirValue)
 $user.psbase.invokeSet("TerminalServicesProfilePath",$ppValue)
 $user.psbase.invokeSet("TerminalServicesHomeDrive",$hdValue)
 $user.setinfo() 
} #end SetTSProperties

function QueryTSProperties()
{
 $ou = [adsi]"LDAP://ou=mytestou,dc=nwtraders,dc=com"
 $user = $ou.psbase.get_children().find($userDN)
 foreach($property in $aryTSProperties)
 {"$($Property) value: $($user.psbase.invokeget($Property))"
 } #end foreach
} #end QueryTSProperties

$userDN = "CN=My User"
$hDirValue = "\\Hamburg\TSUsers\Home\TestUser"
$hdValue = "t:"
$ppValue = "\\Hamburg\TSUsers\Profiles\TestUser"
$aryTSProperties="allowLogon","TerminalServicesHomeDirectory","TerminalServicesHomeDrive","TerminalServicesProfilePath"
SetTSProperties
queryTSProperties
from: http://blogs.technet.com/b/heyscriptingguy/archive/2008/10/23/how-can-i-edit-terminal-server-profiles-for-users-in-active-directory.aspx




Create folder in Outlook and move contents to it

$
0
0

Hi all

We have Outlook 2003, 2007 and 2010 and Exchange 2003 and the following

We need to create a folder in Outlook called "whatever" and move all the contents of the Sent Items folder into the folder called "whatever". If the Sent Items folder has a substructure like 2013, 2012 and 2011 this structure must be retained under the folder called "whatever"

Is this possible with powershell?

How to deal with Exceptions and -ErrorAction SilentlyContinue

$
0
0

Hi all.

I have stumbled upon a problem with Exception handling and I am a bit lost.

I am in the process of fixing several Powershell modules to make Cmdlets throw exceptions instead of erroring to the console. Previously, all these Cmdlets reported errors by means of return codes (horror!).

So far so good. The real problem is that most existing modules are full of this kind of code:

# Check if user exists
$user = Get-AdUser $user -ErrorAction SilentlyContinue

if($user) {
	#do something with $user
}

Now, if I wrap this kind of code into a try...catch block I still get an exception!

[PS] C:\> try {>> get-aduser dfjgdfjgj -erroraction silentlycontinue>> } catch {>> write-host "exception caught">> }>>
exception caught
[PS] C:\>

Since this kind of check is all over the code, wrapping all of these in try...catch blocks would be a MASSIVE job. I am wondering if there is a way to make -ErrorAction SilentlyContinue not raise the exception at all.

Has anyone had this kind of issue before? Has anyone got any idea?

Thanks!

PowerShell Get-ChildItem

$
0
0

I want to get the directorys and file names of a path in a nice object. My problem is creating the one object out of the two different objects that are returned from get-childitem. I would like a dir name associated with each file object so later I can spin thru this object as needed.

Thank you,

Bob

Problems removing a user from a Group where the group dn contains a "/" character

$
0
0

Hellos.

We have a requirement that when a User's contract (leaves company) his AD account is Disabled and All Group memberships are removed.

The Powershell script running to do this contains theses lines:-

$id is samaccountname of user to have his group memberships nullified

$PPSServer is FQN of AD domain controller

$ErrorActionPreference  = "stop"
$Error.Clear()

$strFilter = "(&(objectCategory=person)(objectClass=user)(samAccountName=$id))"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://"+$PSServer) 

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
$objSearcher.PropertiesToLoad.Add('memberOf')

$dn = $objSearcher.findOne()
if ($dn -eq $null -or $dn.count -eq 0) {
$x= "No user found with username=" + $id
$x
exit
}

# set his description attribute on AD
$datestr = Get-Date -format "dd.MM.yyyy"
$desc = "Disabled " + $datestr

$MyuserDN = $dn.path
$MyuserObj = [ADSI]$MyuserDN 
$x = $MyuserObj.Put("description",$desc)
$x = $MyuserObj.SetInfo()

$output = ""
$userObj = $dn.GetDirectoryEntry()
$userDN = $userObj.distinguishedName.Value
$groups = $userObj.memberOf

if ($groups -eq $null -or $groups.count -eq 0)
{
   $x = $userDN + " has no AD group memberships" + "`r`n"
   $x
}
else
{
   foreach ($groupDN in $groups)
   {
$grpEnt = New-Object System.DirectoryServices.DirectoryEntry("LDAP://"+$groupDN)
$output = $output + " Removing user: " + $userDN + " from group: " + $groupDN + "`r`n"
$grpEnt.Properties["member"].Remove($userDN);
    $grpEnt.CommitChanges();
    $grpEnt.Close();
   }
}
$output
#debug/logging
# get the Groups he is currently a member of now
#$x=Get-ADPrincipalGroupMembership -Identity $id
#$x

If the $groupDN contains a / then I get error "Cannot index into a null array." when the command $grpEnt.Properties["member"].Remove($userDN); is executed.

WHY???????

To keep me going I have simply added $ErrorActionPreference  = "SilentlyContinue" before the foreach loop. But I really want to know what is causing this error. 

date join and emp id bulk add

$
0
0

Dear Team

The following objects have been added to the active directory 2008 R2. there are about thousand of users in my existing environment. My question is possible way of adding join date automatically rather than adding manually?

Is it possible for me to create a CSV file and input the date join and emplyee id to add the employee id or what is the easiest way to add. 

  1. Employee ID
  2. Date join(Employee)

Please help me.

Thank you

Mahesh Leema

Dear Team

The following objects have been added to the active directory 2008 R2.  there are about thousand of users in my existing environment. My question is possible way of adding join date automatically rather than adding manually?

Is it possible for me to create a CSV file and input the date join and emplyee id to add the employee id or what is the easiest way to add. 

1.       Employee ID

2.       Date join(Employee)


Please help me.

Thank you

Mahesh Leema

Error when creating virtual machine through C# powershell codings

$
0
0

Hi,

I have difficulty creating new virtual machine. I always get this error when invoking the powershell codes:

An exception of type 'System.Management.Automation.ParameterBindingException' occurred in System.Management.Automation.dll but was not handled in user code

                PowerShell ps = PowerShell.Create();
                ps.AddCommand("New-VM");
                ps.AddParameter("Name", "TestVM");
                ps.AddParameter("VHDPath", "C:\Users\Public\Documents\Hyper-V\Virtual hard disks\Win8.vhdx");
                ps.AddParameter("SwitchName", "TestSwitch");
                ps.AddParameter("MemoryStartupBytes", "512MB");
                var result = ps.Invoke();

The error occurs when I specify the memory size. When I comment out the following line, a virtual machine is created successfully without any error:

ps.AddParameter("MemoryStartupBytes", "512MB");

However, when I want to specify the memory size, I will get an error. 

How should I proceed from here? I want to be able to specify the memory size without any error.

Can someone help me out on this as I'm in deep need of assistance to overcome this problem?

Any help is greatly appreciated. 

Thanks.

Just a bit of startup help creating IIS Sites in IIS 7 - Powershell

$
0
0

Hi Guys, Girls,

I have had a read everywhere, and I am getting mixed cmd coding for powershell.

I would like to run a powershell script to create IIS Sites, the software will be held on a local drive.

I will be creating: Bindings, Application Pools, Virtual Directory.

If someone can point me in the right direction to on how to start this up, it would be much appricated.


PowerShell Script won't load Module/Snap-In when kicked off by scheduling software.

$
0
0

I have a PowerShell script that setups up new AD users based on information from our payroll system.  I want to run it using CRD, which is a scheduling software we use mostly for sending out Crystal Reports.

When I run the script from a PS session, command prompt, or Task Scheduler it works flawlessly.

When I run it from CRD it won't register my SQLTools Module or my Exchange tools snap-in.  I get these errors:

Import-Module : The specified module 'SQLTools' was not loaded because no valid
 module file was found in any module directory.
At C:\PJ_Processes\PowerShell\CreateNewADUsers.ps1:12 char:14+ Import-Module <<<<  SQLTools+ CategoryInfo          : ResourceUnavailable: (SQLTools:String) [Import-M 
   odule], FileNotFoundException+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Comm 
   ands.ImportModuleCommand

Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 
2.
At C:\PJ_Processes\PowerShell\CreateNewADUsers.ps1:13 char:13
+ Add-PSSnapin <<<<  Microsoft.Exchange.Management.PowerShell.Admin+ CategoryInfo          : InvalidArgument: (Microsoft.Excha...owerShell.Ad 
   min:String) [Add-PSSnapin], PSArgumentException+ FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.Ad 
   dPSSnapinCommand

I can get the module to register by copying the directory to a temporary location and specifying the full path, which suggests a permission issue to me, but when I add Echo "$env:userdomain\$env:username"to the script I can see that it's running under my domain account.

Here is the command I use to call the script:

Path:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Working Folder:
C:\PJ_Processes\PowerShell

Optional Parameters:
.\CreateNewADUsers.ps1 2>&1 | tee -filePath C:\PJ_Processes\PowerShell\NewUsersLog.txt

I have tried adding "-version 1", "runas /user:", and "-executionpolicy bypass" but I still get the same results.

Is there a permission issue I'm missing here?  Is there a way I can find out why it's failing to register the modules and snap-in?

PowerShell - Setting targetAddress Active Directory attribute for all computers listed in CSV file

$
0
0

Hi,

I would like to add all the individual MAC addresses for each corresponding computer account in Active Directory through PowerShell. The list has already been created in a CSV file.

The column headers in the CSV file are as followed:

sAMAccountName,targetAddress

I checked the info in the CSV file list and the computer names and their corresponding mac addresses are on the same line seperated by a comma, so the CSV file is correct. There are over 100 computers in the list.

I want to write all the MAC addresses to the targetAddress attribute of each of their corresponding computer in AD, but my command is not working.

Here is my command:

Import-Csv c:\updateAD.csv | Set-ADcomputer -Identity { $_.sAMAccountName } -add @{targetAddress = $_.targetAddress}

Can someone help with the syntax, or perhaps I must use a different algorithm ?

Kind Regards,

unexpected line breaks while using out-file

$
0
0

Hi all,

here is my code to export bunch of inventory to a text file.

$ADInfo = Get-ADDomain
$allDCs = $ADInfo.ReplicaDirectoryServers
foreach ($item in $allDCs)
{
$processor1 = (gwmi win32_processor -ComputerName $item).Name
$RAM = (gwmi win32_ComputerSystem -ComputerName $item).TotalPhysicalMemory
$memory = [math]::Round($RAM/1024/1024/1024, 0)
$TimeZone0 = (gwmi Win32_TimeZone -ComputerName $item).caption
$TimeZone1 = $TimeZone0 -replace ":", ""
$TimeZone = $TimeZone1 -replace " ", ""
$IPGateway0 = (gwmi win32_NetworkAdapterConfiguration -ComputerName $item | where {$_.IPEnabled -eq "True"}).DefaultIPGateway
foreach ($ipgw in $IPGateway0)
{
$IPGateway = $ipgw | Out-String				
}
$NICs = Get-ADComputer -Filter * -Properties ipv4Address | where {$_.DNSHostName -like "$item"} | foreach {$_.ipv4address}
foreach ($NICItem in $NICs)
{
$IPAddress2 = $NICItem | Out-String"$item : {0} : {1} GB : {2} : {3} : {4}" -f $processor1,$memory,$TimeZone,$IPAddress2,$IPGateway >> c:\scripts\hardware.log 
}

}

It exports data to hardware.log file. But for the last variable (IPGateway or anything i put) it breaks line and add something like that:

Intel(R) Core(TM) i5-2520M CPU @ 2.50GHz + 1 + (UTC+0200)Minsk + 10.0.0.2
 + 100.0.8.7

Any idea?

Get-ADGroupMember - Trusted Domain User Accounts

$
0
0

I have several two way domain trusts at the moment and I think I'm hitting some type of resource problem or timeout when using Get-ADGroupMember on domain local groups that contain user accounts from the trusted domains. 

I can only get the cmdlet to work while I'm using Powershell (v2 or v3) on a domain controller (2008R2 and 2012 systems) in my root/primary domain.  If I use another member server of my root domain I get an error message that "FullyQualifiedErrorId : A local error has occurred,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember".  If I use ADUC on that same member server it resolves the names without a problem.  Using get-adgroupmember on member servers for AD groups without user accounts from trusted domains works as expected.  I've tried bumping up the Kerberos size limit to the maximum on my member server and validated the trusts but no change.

Any ideas are appreciated, thanks.

PowerShell script to change AD password remotely

$
0
0

Hi,

I'm trying to make a script in PowerShell for people in my organization to change their AD password.

Some users of our organization aren't at the same domain (different organizations) but, their network can access mine.

So, today... those guys need to use the remote desktop to connect to one of our machines and logon to be able to change their passwords.

I wanted a way to create a script to put in a shared folder to allow them to change their passwords from that network or from VPN.

What I've had in my mind is something like this:

$ADcred = ??? (need to specify the account admin in here: user + password)

$user = Read-Host "Type username:"

$password = Read-Host "Type password:" -AsSecureString

Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $password -Force) -Credential $ADcred


Then I'm thinking about creating an EXE to protect that password in the code...

Any help please?

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>