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

Set IP Phone?

$
0
0

I'm hoping someone here can help me; I've searched and searched and haven't
been able to find an answer.

I've created a program to add new users in AD.  The program generates
Powershell and Quest ActiveRoles cmdlets which contain the details for the user
to be created.  The operator then runs the cmdlets (or scripts) manually and
viola, the user is created. 

The one field that I cannot figure out how to set is the IP Phone on the
Telephones tab.  I can get it with "get-aduser ttester -properties ipphone", but
I can't set it.  I don't want to do anything fancy - I just want a straight
cmdlet like set-aduser -identity ttester -iphone '1234'.

I just don't know if I should be using "vanilla" Powershell for this or if I should be doing it with Quest.  Since I'm able to get it with a regular Powershell cmdlet it seems logical I should be able to set it that way too, though I am clueless about the syntax to be used.


In excel RemoveDuplicates() rows

$
0
0

Hi,

I want to delete some duplicate rows in excel. I recorded a macro in excel that does the work, Now I would like to convert that macro into Powershell.

Here is the Macro:

cells.Select

ActiveSheet.Range("A$1:$E$25").RemovesDuplicates Columns:4, Header:=xlYes

Here is what I tried so far:

$Range = $ws.range("D2:D25")

$Range.select()

$Range.RemoveDuplicates()

It runs with no errors but nothing happens.

Any ideas?



Script Just doesn't want to run correctly.

$
0
0

trying to run this script

It applies registry values based on ($apps)

Error = Missing Expression after unary operator '_'  On several lines

Please assist

$app = get-childitem c:\dome\$computername

$computername = (get-wmiobject -class win32_computersystem)._server

New-Item -path hklm:\Software\Management\Server -name Packages

Switch (&app)

{

"01" { set-itemproperty -path hklm:\Software\Management\DC\Server\Packages -name 01 -value 0173 }

"03" { set-itemproperty -path hklm:\Software\Management\DNS\Server\Packages -name 03 -value 1797 }

"04" { set-itemproperty -path hklm:Software\Management\WINS\Server\Packages -name 03 -value 1979 }

}

PowerShell Script to list a server's users, groups, permissions, etc.

$
0
0
I'm looking for a PowerShell script that will query and output all the local and AD users, service accounts, and groups on a given Windows servers. I need the script to recursively list the members of each group that has privileges on that server. I'm looking for a script that will give me a good starting point from which I can tailor it to my specific needs. Thanks.

Retry command until it is successful

$
0
0

I am writing a PowerShell script that stops an IIS Application Pool, does several other operations and then starts the AppPool again.

The problem is that the AppPool can take a long time to stop and if you try to start it before it is done stopping, you get the error

Start-WebAppPool : The service cannot accept control messages at this time. (Exception from HRESULT: 0x80070425)

 

Stop-WebAppPool -name $AppPool;
# do other stuff
Start-WebAppPool -name $AppPool;

What is the best way to get PowerShell to either

  1. keep trying to start the AppPool or
  2. force the AppPool to stop by killing the process.

Active Directory user properties blank in CSV export

$
0
0

Hi,

I'm working on a script to export some properties of user accounts and export them to CSV, but, strangely, some of these properties are blank in the output, while they are set when I display them from the PS console. Here's the relevant snippet of my code:

$user = Get-ADUser -Filter 'samaccountname -like $username'

    $obj = New-Object -TypeName PSObject
    $obj | Add-Member -MemberType NoteProperty -Name UserName -Value $username
    $obj | Add-Member -MemberType NoteProperty -Name UserSurname -Value $user.surname
    $obj | Add-Member -MemberType NoteProperty -Name UserGivenName -Value $user.givenname
    $obj | Add-Member -MemberType NoteProperty -Name UserStatus -Value $user.Enabled
    $obj | Add-Member -MemberType NoteProperty -Name PwdExp -Value $user.PasswordExpired
    $obj | Add-Member -MemberType NoteProperty -Name Locked -Value $user.LockedOut
    $obj | Add-Member -MemberType NoteProperty -Name WhenUserChanged -Value $user.whenChanged

    $out += $obj
[...]

$out | Export-Csv .\UserStatus.csv -NoTypeInformation

Now, the last three columns (PasswordExpired, LockedOut, whenChanged) are blank, so a line would look like this:

"UserName","UserSurname","UserGivenName","UserStatus","PwdExp","Locked","WhenUserChanged"
"accountname","lastname","firstname","True",,,

Any idea?

Thanks!

Powershell- Exchange Online session not lasting more then 2 minutes with Proxy Option

$
0
0

Hi,

    My exchangeonline session is not longing more then 2 minutes.. I created a session as follows

PS C:\>$sessionOpts=New-PSSessionOption -ProxyAccessType AutoDetect -IdleTimeout 3600000 -OpenTimeout 0

and then created a session as 

PS C:\>$session =New-PSSession -Credential <credentials> -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Authentication Basic -AllowRedirection -SessionOption $sessionOpts

After establishing the exchange online session, i was able to import-pssession module. After that if i run any cmdlet like get-mailbox, get-mailuser, i will be getting a window to enter credentials.. when i check the $session it results the following

 Id  Name            ComputerName    State         ConfigurationName     Availability
 --   ----                     ------------           -----         -----------------                     ------------
  1  Session1        pod51053psh.... Broken        Microsoft.Exchange            None

Though i kept idle timeout for 1 hour.

please find the screenshots of the issue. 

A pop window came up after 2 mins of idle. 

Is it a known scenario or not? What is the way of making the session last for more then 10 mins. Please let me know if any furthur information required.

Thanks,

satya

Help with string functions

$
0
0

I'm trying to figure out how to change how the table insert works.  Right now, it's just populating 2 columns.  I would like to break up the first column into several columns using substring or something like take the next 3 characters after the"(".  Any help would be appreciated.

#$destserver = "SESQLDEV01"
#$destDB = "Monitor"
param ($destserver, $destDB)
$destserver = "BEAST"
$destDB = "SSIMS_Prod"
###########################################################################################
function Get-SqlData 
{
    param([string]$serverName=$(throw 'serverName is required.'), 
          [string]$databaseName=$(throw 'databaseName is required.'),
          [string]$query=$(throw 'query is required.'))
    Write-Verbose "Get-SqlData serverName:$serverName databaseName:$databaseName query:$query"
    $connString = "Server=$serverName;Database=$databaseName;Integrated Security=SSPI;"
    $da = New-Object "System.Data.SqlClient.SqlDataAdapter" ($query,$connString)
    $dt = New-Object "System.Data.DataTable"
    [void]$da.fill($dt)
    $dt
}
###########################################################################################
function out-DataTable
{
  $dt = new-object Data.datatable  
  $First = $true  

  foreach ($item in $input){  
    $DR = $DT.NewRow()  
    $Item.PsObject.get_properties() | foreach {  
      if ($first) {  
        $Col =  new-object Data.DataColumn  
        $Col.ColumnName = $_.Name.ToString()  
        $DT.Columns.Add($Col)       }  
      if ($_.value -eq $null) {  
        $DR.Item($_.Name) = "[empty]"  
      }  
      elseif ($_.IsArray) {  
        $DR.Item($_.Name) =[string]::Join($_.value ,";")  
      }  
      else {  
        $DR.Item($_.Name) = $_.value  
      }  
    }  
    $DT.Rows.Add($DR)  
    $First = $false  
  } 

  return @(,($dt))

}
###########################################################################################
function Get-WMIInfo 
{ 
param($serverName)
@("\\$serverName\PhysicalDisk(*)\Avg. Disk Read Queue Length", "\\$serverName\PhysicalDisk(*)\Avg. Disk Write Queue Length", "\\$serverName\PhysicalDisk(*)\Avg. Disk sec/Read", "\\$serverName\PhysicalDisk(*)\Avg. Disk sec/Write","\\$serverName\PhysicalDisk(*)\Disk Read Bytes/sec","\\$serverName\PhysicalDisk(*)\Disk Reads/sec","\\$serverName\PhysicalDisk(*)\Disk Write Bytes/sec","\\$serverName\PhysicalDisk(*)\Disk Writes/sec") |% { 
    (Get-Counter $_.replace("*","1 c:")).CounterSamples } | 
    Select-Object Path, CookedValue | `
    add-Member -memberType noteProperty -name Server -value $servername -passThru

} 
###########################################################################################
function Write-DataTableToDatabase 
{ 
    param ($dataTable,$destTbl) 
    $connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;" 
    $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString 
    $bulkCopy.DestinationTableName = "$destTbl" 
    $bulkCopy.WriteToServer($dataTable) 
} 
###########################################################################################
Get-SqlData $destserver $destDb "Select ServerName From ServerNames" |
foreach {
    $dataTable = Get-WMIInfo $_.servername | out-datatable 
    if ($dataTable) 
    { Write-DataTableToDatabase $dataTable 'PhysicalDisk' } 
}


Add Users to AD and assign them office 365

$
0
0

Hello,

Can anyone tell me please how to add 100 users to active directory and Automatically Assign Licenses to Office 365 Users ?

Thank you.

Get-Counter path is not correct

$
0
0

I'm to get this to run but keep getting this error: Get-Counter : The specified counter path could not be interpreted.

Any insight into this issue would be appreciated.

param($destserver, $destDB)
$destserver = "CCIIT23"
$destDB = "SSIMS_Prod"

$Servers = Get-SqlData $destserver $destDb "Select ServerName From ServerNames"
write-output $Servers


$CounterList = Get-SqlData $destserver $destDb "Select Counter From MemoryCounterList"
write-output $CounterList

$Servers | Foreach-Object {
    $Serv = $_; $CounterList | Foreach-Object {
        Get-Counter -Computer $Serv -Counter $_ -SampleInterval 1
        }
    }

Backup-GPO cmdlet errors in Task Scheduler

$
0
0

I have scheduled a simple script on my Windows Server 2012 domain controller to backup my group policies (separate from the System State backup). I ran the script manually, and it works as expected. I scheduled the script in Task Scheduler using a service acct with domain admin privileges. Due to our domain policy settings, I had to select the "Do not store password" option on the job, otherwise the usual error regarding "no session" is presented. This means I have access to local resources only (on the DC).

I also right-clicked the job and selected "run" and the job executes properly. However, when the job kicked off at the scheduled time on its own, it only ran partially. The date stamped backup folder was created, and it contained a partial "manifest.xml" file which is created at every backup. The manifest only has the header in it, no other content such as GPO names and GUIDs.

In the Powershell transcript output, it generates an error when the Backup-GPO cmdlet runs:

Backup-Gpo : The system cannot open the device or file specified. (Exception from HRESULT: 0x8007006E)

The command is:

Backup-Gpo -All -Path $backup_dir\$date_stamp

And yes, I have selected to run the job without the user being logged in. Is it possible to backup domain GPOs without the credentials cached in the job? Are the GPOs considered a "local resource" on the domain controller?

Performance of powershell on 64bit on 2008 R2 v. powershell on 32bit on 2003 SP2

$
0
0

Converted a script written in vbscript to powershell v2.0.  When running the script in 32bit mode on Windows Server 2003 SP2 script runs in about 10 minutes and processes 6500 files.  Running the same script on Windows Server 2008 R2 SP1 script is killed after 3 hours and processed less than 1000 files.

Both OS's are running in a VMWare vSphere 5.5 VM.

Script is to produce a CSV file for import into our Software Inventory System.

Script uses WMI calls to Win32_directory and CIM_DataFile to create an object that is use in generating CSV files. 

On Windows Server 2003 SP2, used Export-CSV to generate the file and had no problems or performance issues.  On Windows Server 2008 R2, have switched from using Export-CSV to Convert-CSV piped to Out-File to generate an appendable CSV file. Still Testing Convert-CSV, and it doesn't look good.

Tried to use pipelining with the WMI Objects, but it took looker than creating the WMI object and looping through them.

Any ideas on how to improve the performance would be appreciated. 

DJ

mapping a drive with NET USE in PowerShell using WEBDAV not working right

$
0
0

I am using NET USE to map a drive to a SharePoint library (using WEBDAV). When I do this in a DOS command prompt, everything works perfectly. I map the drive, the drive letter is instantly accessible, I can list contents with DIR and everything works great. But when I use the same command in PowerShell, the drive does map, but when I try to run a DIR against the new drive letter, it's not accessible.

CODE

cls
net use q: "http://MyPath/Server Build Requests"
Get-ChildItem q:\
net use q: /delete

ERROR

Get-ChildItem : Cannot find drive. A drive with the name 'q' does not exist.
At C:\Users\MyUser\AppData\Local\Temp\2\c64dbe78-c74e-401e-b39f-405165a31e13.ps1:5 char:14+ Get-ChildItem <<<<  q:\+ CategoryInfo          : ObjectNotFound: (q:String) [Get-ChildItem], DriveNotFoundException+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Any help would be appreciated!

search for group with earliest creation date

$
0
0

Hello all. I have a fun little idea where I'd like to search through the domain and return the group with the earliest creation date. I'm guessing a DirectorySearcher would be in order here, except I haven't worked with Date/Time objects in LDAP queries before, and my Google searches haven't turned up much. To my mind there's 2 ways to go about this. First, I could grab all group objects in the domain and then sort by created date (which I don't know how to do and seems like would take forever). Second, I could use an LDAP filter to only grab groups that are older than a certain date (which I also don't know how to do but sounds better than option 1).

The only problem is, I'm at a loss on working with Date/Time objects in LDAP queries. The short script I have so far (which doesn't work) is:

cls

$earlydate = [string]1/1/2000
$GroupSearchFilter = "(&(objectcategory=group)(whencreated>=$earlydate)"
$GroupSearchDomain = New-Object system.DirectoryServices.DirectoryEntry("LDAP://dc=mydomain,dc=net")
$GroupSearcher = New-Object System.DirectoryServices.DirectorySearcher
$GroupSearcher.SearchRoot = $GroupSearchDomain
$GroupSearcher.PageSize = 1000
$GroupSearcher.Filter = $GroupSearchFilter
$GroupSearcher.SearchScope = "Subtree"

#SETTING THE PROPERTIES WE WANT RETURNED FOR EACH GROUP
$GroupPropertyList = "sAmAccountName","whencreated" > $null
foreach ($i in $GroupPropertyList){$GroupSearcher.PropertiesToLoad.Add($i)} 

#FINDING ALL THE GROUPS THAT MEET THE $GroupSearchFilter CRITERIA
$GroupResults = $GroupSearcher.FindAll()
"Getting Domain Local Security Group search results... Please wait..."
$DisplayResults = Foreach($Result in $GroupResults){
                    $GroupName = $GroupResults.Properties.sanaccountname
                    $GroupCreateDate = $GroupResults.Properties.whencreated
                  }
$ResultsTable = @{n="Group Name";e={$GroupName}},`
                @{n="Date Created";e={$GroupCreateDate}}

$DisplayResults | ft $ResultsTable

And please critique away. I'm new to powershell so I take all the help I can get!




Exchange 2010 - Get-Mailboxpermission and security groups

$
0
0

Hi all,

Apologies in advance if this question has been asked before however i'm failing to find any resources online about it.

I am doing a migration from Exchange 2010 > Office365 and need to run a report about who has access to what mailboxes.

The issue i have is that using "Get-Mailboxpermission mymailbox@mydomain.com" returns values which may contain security groups. The report then returns that the group has full access permission, But does not enumerate the users contained in the group.

As 90% + of our permissions are granted this way, I need an easy way to enumerate this.

Unfortunately, The "Get-Adgroupmembers" cmdlet does not accept identities in the format of "Domain\Group" only "Group" or "SID" or "LDAP string"

Has anyone run into a situation like this before and or have a script available that performs the above action?

Thanks in advance

Chris


Add-PrinterDriver -InfPath

$
0
0

Hello,

I am working on managing new windows 8.1 machines with some powershell scripts. I have figured out how to add a printer, assuming that the driver already exists on the machine. However, I cannot seem to add a printer driver.

The line I believe should work looks like this:

Add-PrinterDriver -Name "Canon iR-ADV C5045/5051 PS3" -InfPath "C:\Scratch\CanonPrintDriver\"

However, I receive the following:

Add-PrinterDriver : One or more specified parameters for this operation has an invalid value.
At line:1 char:1
+ Add-PrinterDriver -Name "Canon iR-ADV C5045/5051 PS3" -InfPath "C:\Scratch\Canon ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (MSFT_PrinterDriver:ROOT/StandardCimv2/MSFT_PrinterDriver) [Add-Printer
   Driver], CimException
    + FullyQualifiedErrorId : HRESULT 0x80070057,Add-PrinterDriver

If I remove the -infpath option, it fails, saying the driver does not exist in the driver store, so I know that the issue must be with the syntax of -infpath. However, I am unable to find any resources online that show me an example of the -infpath parameter correctly used. Any ideas?

Thanks

Error message for Users

$
0
0

Hello all,

My plan is to perform four hardware checks prior to the installation of some softare - the checks are:

OS is at least Windows 7

HDD Freespace is not less than 6.0 GB

CPU is greater 4.00Ghz

RAM is not less than 2.0 GB

Scripting the above is pretty easy...but what I now want to do is capture any of the failed checks and report them to the user.

E.g. one computer might fail HDD and RAM checks but another system may only fail on RAM - how can I dynamically build up a message to inform the user of the specific issue with their machine?

It would be pretty easy to just pop-up some info to the user stating that their machine doesnt meet the minimum specs but I'd rather tell them more specifically what the issue is so the service desk don't have to connect and figure out which check or checks have failed....hope this makes sense?

Thanks,

C


Carl Barrett | Twitter: @Mosquat

Powershell set-executionpolicy configuration?

$
0
0

Why is it that when i run s script, it still ask question(highlighted part)?

even though I already set the set-executionpolicy to UNRESTRICTED.

How to disable it? How can i set my powershell to whenever I run a script, no confirmation/question ask and run it.

Thank you in advance


Edit DNS Zone files with PowerShell

$
0
0

I recently spent a couple of days trying to transfer DNS server zone files from an older public DNS server (Windows 2008) to a new replacement (Windows 2012 R2) at a different IP address. This involved editing them to change the IP address of one of the NS entries in each zone file. These were not AD integrated zones.

Following some good articles, I used this process:

  • Export the Registry entries for the Zones from HKLM\Software\Microsoft\Windows NT\Current Version\DNS Server\Zones (Capture the entire Zones key structure)
  • Copy all the .dns zone files from C:\Windows\System32\DNS\ to another folder (using C:\DNSTransfer in this example)
  • Edit the copied zone files to change the IP address as needed. Script was:
  1. $OldIP = "11.22.33.44"   #Example only
  2. $NewIP = "55.66.77.88"   #Example only
  3. Get-ChildItem C:\DNSTransfer -Recurse | Select-String -Pattern '$OldIP' -SimpleMatch | Foreach-Object{
         $content = Get-Content $_.Path
         $content -replace '$OldIP','$NewIP' | Out-File $_.Path  }
  • Install DNS on the new server
  • Configure the server as required (use DNSCMD /Info to capture existing server settings)
  • Create a dummy zone (to initialise the new DNS) - delete this later
  • Import/Merge the .REG file to load the Zone information into the new registry
  • Copy the edited .dns zone files into to new server's C:\Windows\System32\DNS folder.
  • Restart DNS server service.

Every time I did this I only ended up with the internal name of the DNS server as the only record in each Zone as seen from DNS Manager. The Zone files were still correct, the registry keys were correct, but DNS only served up garbage. All the NS, MX A, CNAME etc records appeared to vanish.

Even rebuilt new servers in various editions of Windows (2008 R2, 2012, 2012 R2) and got the same results.

When I created new zones on the servers they worked fine. When I copied content rom old zones into the new zones that also worked. Eventually twigged that the problem was the ENCODING of the .dns zone files. The ones that had been edited were in Unicode format. Original and new files were in ANSI format. No amount of changing the Name Checking method in the DNS servers could get them to properly read these Unicode files.

The answer was deceptively simple: PowerShell had modified the encoding when the script was run. Added the encoding switch and it all worked. The new script is:

  1. $OldIP = "11.22.33.44"   #Example only
  2. $NewIP = "55.66.77.88"   #Example only
  3. Get-ChildItem C:\DNSTransfer -Recurse | Select-String -Pattern '$OldIP' -SimpleMatch | Foreach-Object{
         $content = Get-Content $_.Path
         $content -replace '$OldIP','$NewIP' | Out-File $_.Path -Encoding ASCII  }

 So the simple message is: Make sure your Microsoft DNS Zone files are in ANSI encoding, otherwise the DNS server will treat them as faulty and write default entries only.

winrm - enable-psremoting error

$
0
0

Hello,

Why am i receiving this error and how do I fix it?

PS C:\WINDOWS\system32> enable-psremoting -force

WinRM is already set up to receive requests on this computer.
Set-WSManQuickConfig : <f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault" Code="5"
Machine="HOSTNAME1"><f:Message>The WinRM client cannot process the request. The WinRM client tried
to use Negotiate authentication mechanism, but the destination computer (localhost:47001) returned an 'access denied'
error. Change the configuration to allow Negotiate authentication mechanism to be used or specify one of the
authentication mechanisms supported by the server. To use Kerberos, specify the local computer name as the remote
destination. Also verify that the client computer and the destination computer are joined to a domain. To use Basic,
specify the local computer name as the remote destination, specify Basic authentication and provide user name and
password. Possible authentication mechanisms reported by server:       Kerberos   </f:Message></f:WSManFault>
At line:69 char:17
+                 Set-WSManQuickConfig -force
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Set-WSManQuickConfig], InvalidOperationException
    + FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.SetWSManQuickConfigCommand

thank you.


Viewing all 21975 articles
Browse latest View live