Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

Problems retrieving the correct 'Message' using Get-Eventlog

$
0
0

When running this query on my DC:

Get-EventLog -LogName system -Newest 50, in the Message column, I get many events with the following sort of message:

"The description for Event ID '-2108030929' in Source 'W32Time' cannot be found. The local computer may not have the necessary registry information or message DLL files to display the message, or you may not have permission to access them. The following information is part of the event:'time.windows.com,0x1', 'The peer is unreachable. ' "

When I view the corresponding event in Event Viewer, it gives me the correct error Message, in this case:

"Time Provider NtpClient: No valid response has been received from manually configured peer time.windows.com,0x1 after 8 attempts to contact it. This peer will be discarded as a time source and NtpClient will attempt to discover a new peer with this DNS name. The error was: The peer is unreachable."

This is not specific to any particular event source, I am just giving an example. This happens with most but not all the System events returned by the cmdlet when querying the System log, but not when querying the Application log.  Then all the messages are the same as appear in Event Viewer.

Can anyone explain why I am not getting the full and proper description of the events when using PS to get them?

 


PS: The server is running WS2008 SP2.

 









Powershell: Post build event in Visual Studio 2010 with feedback

$
0
0

Hello everybody

I would like to execute a powershell script in "postbuild" event in Visual studio. It is rather difficult to get it working. 

My script should run on any develper machine. From visual Studio (which  is 32Bit ) i have to start 32Bit powershell. No problem with that. But often on the developers machines it is not allowed to execute scripts and everyone must execute "Set-ExecutionPolicy Unrestricted" . This seems to be the default "out of the box" setting. 

Problem 1: to execute scripts I have to execute a script.....hmmm

So at least one would expect that the build in Visual Studio would break if the powershell script failed. But no, Visual Studio happily executes whatever happens in powershell script. I can start a good old dos batch file an return something with "exit 1". Then Visual Studio breaks.  

Problem 2: How can I get a return value so Visual Studio does not think everything is ok?

I can enter "%windir%\SysWOW64\WindowsPowerShell\v1.0\PowerShell.exe -Command "& PostBuild.ps1""
But then an error may happen if the user has the policy not set. How can I set the policy to unrestricted and have an error value in dos?
Event if the execution policy is set correctly,  the ps script may fail anyway. How can I get the error code then?

I hope somebody has a tip.
Thanks
Ben

Logging Verbose and Debug output with private proxy functions

$
0
0

The following code added to a script that utilizes Write-Verbose and Write-Debug should be able to implement logging of that output when the script is run as a scheduled task:

To log the events immediatly when they are encountered in the script:

$logfile = './logfile.log' 
 function private:Write-Debug {  
  if ([int]$DebugPreference){  
       Add-Content $args[0] $logfile 
       write-debug $args[0]  
      }  
 }  
    
 function private:Write-Verbose {
   
    if ([int]$VerbosePreference){  
         Add-Content $args[0] $logfile 
         write-verbose $args[0]  
     }  
 } 

This will write them to a variable. 

$logvar = {}.invoke()  
    
 function private:write-Verbose {  
  if ([int]$verbosepreference){  
         $logvar.add($args[0])  
         write-verbose $args[0]  
       }  
  }   
      
 function private:write-Debug {  
   if([int]$debugpreference){  
        $logvar.add($args[0])  
        write-Debug $args[0]  
     }  
 } 
Anybody see any potential unintended consqeunces, or an easier way?

[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

CSV file logging need help

$
0
0

Hi,

I am working on a logging script for some servers, the data im looking to pull is all users logged on, date, count. i want to run this for about 3 days and pull data about 5 mins apart.

I am outputting to a csv file, but when it outputs its overwriting my previous data. I tried noclobber but that just errors out and says file already exists

$date = Get-Date -format g
$server = "ctx45dcepc62"
$file = ".\users.csv"
Import-Module psterminalservices
$users = get-tssession -computername $server -Filter {$_.username -AND $_.ConnectionState -eq 'Active'} | select username
$count = $users.Count
$users | add-member -name Date -type noteproperty $date
$users | add-member -name Count -type noteproperty $count
$users | export-csv $file -NoTypeInformation

Could some one help me out, or should i not use export-csv? Also how would i get a 5 min timer to run this script say for 3 days?

Thanks in advance


List the state of multipul services on all servers in the domain

$
0
0

I'm trying to list the state of specific services that are running on all servers in the domain ie. DHCP Server or DNS Server

At the moment i have the following script working for one service only and its querying a list of servers in a txt file which is not ideal -


$Computers = Get-Content "C:\Servers.txt"
$WmiObject = @{
Class = "Win32_Service"
}
foreach ($Computer in $Computers)
{
$Select = @{
Property = "SystemName","Name","StartMode","State"
}
Get-WmiObject @WmiObject -ComputerName $Computer | where{$_.Name -eq "DNS Server"} | Select-Object @Select
}

Powershell has stopped working - File Server Migration

$
0
0

I am trying to migrate a 2003 x86 File and Printer server to 2008 R2 x64. I am using the Windows Server Migration Tools included with R2 and I am using the one step copy procedure described here http://technet.microsoft.com/en-us/library/dd379474.aspx#BKMK_MigrateData I have done the prelim steps of exporting the install files for 2003 etc..

As soon as the destination server reaches the Finalizing Migration step I get a powershell has stopped working error on the destination server. The details are posted below.

Problem signature:
  Problem Event Name:    PowerShell
  NameOfExe:    powershell.exe
  FileVersionOfSystemManagementAutomation:    6.1.7601.17514
  InnermostExceptionType:    System.ArgumentException
  OutermostExceptionType:    System.ArgumentException
  DeepestPowerShellFrame:    unknown
  DeepestFrame:    System.ThrowHelper.ThrowArgumentException
  ThreadName:    unknown
  OS Version:    6.1.7601.2.1.0.18.10
  Locale ID:    1033

This line was also at the bottom of setuperr.log on the destination R2 server

2012-08-11 12:01:37, FatalError [0x090001] PANTHR Exception (code 0xE0434F4D: <unknown>) occurred at 0x000007FEFDE3CACD in C:\Windows\system32\KERNELBASE.dll (+000000000000CACD).  Minidump attached (327086 bytes).




list hotfix on remote servers

$
0
0

Hi,

I am using this command to get a list of Hotfix installed in a remote server.  Get-Hotfix -Computername test01

Please let me know if i can provide a list of remote servers as a txt file ? and get an output in excel/csv.

what else should i add to the above command.

Thanks in Advance

Alex


Alex

Run Powershell script as Scheduled task, that uses Excel COM object

$
0
0

What am I missing here..

 

I have  Powershell script that uses the Quest AD cmdlets to get computer information from AD and populate an Excel spreadsheet with the data.

The script works fine, so I created a batch file and started the script from there (which works fine as well). It populates the excel spreadsheet, saves and closes the file.

If I run the script as a scheduled task, I can see from the logging that it supposedly gets the computers from AD, and runs through them. But a file is never saved, I have tried to run the scheduled task with admin credentials.

What am I forgetting?


the "#" and tab characters and command history

$
0
0

Interesting info from a few replies by Lincoln Atkinson in another thread: http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/a7836860-9136-4109-b00a-507b750fc2a1

In addition to the various "history" commands, one can use "#<string><tab>" to display commands from the history by their "ID" or by doing a regex match on the string given. After playing with it a bit I deduced that the tab key cycles from most recent to oldest commands, and that the backtab cycles in the opposite order

This does not appear to be mentioned anywhere in HELP, and Lincoln couldn't remember where he had seen it mentioned. It seems like a useful feature, however my first impression was that it would cause code containing #comments to behave differently whether typed at the console or contained in a script or function. I suspect that it is not common for people to type comments in the console, and, even if they do, the only problem is using the tab or backtab key.

Where it is a potential problem is when one copy/pastes code from a script file to the console, if the comments contain tab or backtab characters, the results are likely to be different from what one expects when one notices that random commands from the history are executed instead of the comments just being displayed.

Again, this doesn't seem likely to be a problem likely to happen often. But it is a bit surprising.

So my questions are:

  1. does anyone know where this behaviour is documented?
  2. are there any other similar undocumented features?


Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

Cannot redirect Powershell output using Task Scheduler

$
0
0

I'm running Windows Server 2008 Enterprise x64 R2.

Sample script x.ps1:

(Get-Date).DateTime
Write-Output "output"
Write-Warning "warning"
Write-Error "error"

Run this in the cmd console:

powershell -command ".\x.ps1" *> x.log.  Works like a charm, I've got a log.

Now delete x.log.  Create a scheduled task with the exact same command:  powershell -command ".\x.ps1" *> x.log.  Run the scheduled task.  No log.

WTF?  How hard should this be?  I've spent hours Googling, I know this problem comes up a lot.  Why is a scheduled task so different than running from a cmd console?

I also tried powershell -file, as well as Start-Transcript, which looked promising, but I don't like the line wrapping in the scheduled task output.

need to supply multiline input from a copy/paste

$
0
0

Hello,

I would like to write a script that prompts for input (like using read-host), but I need to be able to copy/paste that input from the clipboard, and that clipboard data will have line breaks in it, like copy/pasting the contents of a text file.

The script is a simple script that will process the lines of input, but for ease of use for this particular scenario, I don't want to have to save the text to a text file and then read in that file, I really need to just copy/paste it directly into the input prompt of the script.

can I do this? something with HERE strings and read-host? or do I need to hit up something in the [console] class like readline or readlines etc..???

I'm about to start experimenting but as always I appreciate the experienced input from the community here.

Thanks.


Trying to comapre one text line to several and see if it is contained in a hash Table

$
0
0

Hello All!

I have a list of files named Extracted AID Block-001, Extracted AID Block-002,...etc all the way to Extracted AID Block-00n. In every file is one line of txt that looks similar like this: A000000018100203. This is the name of an applet ID and they vary from file to file.

Keeping this in mind, I have n number of files and inside of them, I have multiple lines of applet ID's instead of just one like the Extracted AID Block-00n. I want to compare a "one-lined" applet ID file (from Extracted AID Block-00n) and see if it is contained in the multiple lined files. If it is, I want to list the one lined files content and then show that it is contained in the multiple line file by listing the name of the file. So for example it should report this:

A000000018100203   ->  Available in "AIDList1.txt"

Where "A000000018100203" is from the file Extracted AID Block-00n.txt file and "AIDList1.txt" is the file that has multiple applet ID's in it.

So far I has been able to create a hash table for all of the values from the files that have multiple applet ID's.

The tricky part for me comes when I want to compare just one line from the "Extracted AID Block-00n" file to a list of hash table values.

So far I have this:

Function COMP{
$getAIDFolder = "C:\Users\user\Desktop\Project1-Phase 2\AID"
$pathOfG = "C:\Users\user\Desktop\Project1-Phase 2"
	
$ht = @{}
foreach ($aid in gci "$getAIDFolder\Extracted AID" -include *.txt -recurse ){
     $ht[$aid.name] = [io.file]::ReadAllText($aid.fullname)
	      }
$w = foreach ($load in gci "$pathOfG\Extracted AID Blocks"){
     $loadtext = [io.file]::ReadAllText($load.fullname)
     $unknown = $true
     foreach ($key in $ht.keys){
         if ($loadtext -eq $ht[$key]){
			$justName = "$key"
			$justName = $justName.Replace(".txt","")
			$Global:IdentifiedCount++
			
            write-output "$load -> Available in '$keyName'"
           $unknown = $false
           }
      }
     If ($unknown){
	 $Global:unknownCount++
     Write-output "$load -> UNKNOWN"
     }
	 
}
$w|out-file "$pathOfG\test.txt"
}	
comp

So far I am able to generate the report that looks like this:

Extracted AID Block-001.txt -> UNKNOWN
Extracted AID Block-002.txt -> UNKNOWN
Extracted AID Block-003.txt -> UNKNOWN
Extracted AID Block-004.txt -> UNKNOWN
Extracted AID Block-005.txt -> UNKNOWN

However I am having trouble grabbing the info from "Extracted AID Block-001.txt " and just displaying it so that it looks like what I want:

A000000018100203   ->  Available in "AIDList1.txt"

I am also having an issue with my matching logic. So, so far I am just receiving UNKNOWN for all of my values.

Any help will be greatly appreciated as I have hit the coding wall!

Thank you and please if this comes across as a little convoluted or difficult to understand, please let me know as I applogize in advanced.

Thanks!

List File properties with PC Name

$
0
0

Does anybody know how I would go about reading a list of PC names, then getting a list of files with properties, and then exporting to a csv file?  I have this.  I have been on this for hours...

Get-Content C:\Scripts\PCLists\test.txt | Get-ChildItem -Path { "C:\csd" } -force -recurse | export-csv -path C:\test.csv

The thing that is missing is how would I know what PC the file came from?  I'm writing this because I need to search a specific directory for all files with sizes from a list of computers.

Any and all would would be appreciated,

Tim

Help with a simple script

$
0
0

Hey guys,

I grabbed a script off the repository and trying to use it, but we have 23bit subnet masks.  I can figure out how to modify the octets, domain OUs, but how do I change these subnets?  Here is where the variables are entered into the script.

##############################
# Set the Location IP ranges #
##############################

$Site1IPRange = "\b(?:(?:192)\.)" + "\b(?:(?:168)\.)" + "\b(?:(?:1)\.)" + "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))" # 192.168.1.0/24
$Site2IPRange = "\b(?:(?:192)\.)" + "\b(?:(?:168)\.)" + "\b(?:(?:2)\.)" + "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))" # 192.168.2.0/24
$Site3IPRange = "\b(?:(?:192)\.)" + "\b(?:(?:168)\.)" + "\b(?:(?:3)\.)" + "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))" # 192.168.3.0/24

Thanks,

Dan

Here is the entire script if needed

#####################
# Environment Setup #
#####################

#Add the Quest PowerShell snapin
Add-PsSnapIn Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue

#Set the threshold for an "old" computer which will be moved to the Disabled OU
$old = (Get-Date).AddDays(-365) # Modify the -60 to match your threshold

#Set the threshold for an "very old" computer which will be deleted
$veryold = (Get-Date).AddDays(-900) # Modify the -90 to match your threshold


##############################
# Set the Location IP ranges #
##############################

$Site1IPRange = "\b(?:(?:128)\.)" + "\b(?:(?:1)\.)" + "\b(?:(?:8)\.)" + "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))" # 128.1.8.0/24
$Site2IPRange = "\b(?:(?:192)\.)" + "\b(?:(?:168)\.)" + "\b(?:(?:2)\.)" + "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))" # 192.168.2.0/24
$Site3IPRange = "\b(?:(?:192)\.)" + "\b(?:(?:168)\.)" + "\b(?:(?:3)\.)" + "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))" # 192.168.3.0/24

########################
# Set the Location OUs #
########################

# Disabled OU
$DisabledDN = "OU=Disabled,DC=yourdomain,DC=com"

# OU Locations
$Site1DN = "OU=Site1,DC=vailres,DC=com"
$Site2DN = "OU=Site2,DC=yourdomain,DC=com"
$Site3DN = "OU=Site3,DC=yourdomain,DC=com"

###############
# The process #
###############

# Query Active Directory for Computers running Windows 7 (Any version) and move the objects to the correct OU based on IP
Get-QADComputer -ComputerRole member -IncludedProperties pwdLastSet -SizeLimit 0 -OSName 'Windows 7*' | ForEach-Object {

 # Ignore Error Messages and continue on
 trap [System.Net.Sockets.SocketException] { continue; }

 # Set variables for Name and current OU
 $ComputerName = $_.Name
 $ComputerDN = $_.DN
 $ComputerPasswordLastSet = $_.pwdLastSet
 $ComputerContainer = $ComputerDN.Replace( "CN=$ComputerName," , "")

 # If the computer is more than 90 days off the network, remove the computer object
 if ($ComputerPasswordLastSet -le $veryold) {
  Remove-QADObject -Identity $ComputerDN
 }

 # Check to see if it is an "old" computer account and move it to the Disabled\Computers OU
 if ($ComputerPasswordLastSet -le $old) {
  $DestinationDN = $DisabledDN
  Move-QADObject -Identity $ComputerDN -NewParentContainer $DestinationDN
 }

 # Query DNS for IP
 # First we clear the previous IP. If the lookup fails it will retain the previous IP and incorrectly identify the subnet
 $IP = $NULL
 $IP = [System.Net.Dns]::GetHostAddresses("$ComputerName")

 # Use the $IPLocation to determine the computer's destination network location
 #
 #
 if ($IP -match $Site1IPRange) {
  $DestinationDN = $Site1DN
 }
 ElseIf ($IP -match $Site2IPRange) {
  $DestinationDN = $Site2DN
 }
 ElseIf ($IP -match $Site3IPRange) {
  $DestinationDN = $Site3DN
 }
 Else {
  # If the subnet does not match we should not move the computer so we do Nothing
  $DestinationDN = $ComputerContainer 
 }

 # Move the Computer object to the appropriate OU
 # If the IP is NULL we will trust it is an "old" or "very old" computer so we won't move it again
 if ($IP -ne $NULL) {
  Move-QADObject -Identity $ComputerDN -NewParentContainer $DestinationDN
 }
}


Dan Heim

Mapping home drive using a ps script not working

$
0
0

Hello,

I'm trying to map my home drive using a ps script but I'm have trouble and can't work out why, it should locate my ad username and then map my drive to the z drive, any ideas?

PS C:\Users\me> (New-Object -ComObject WScript.Network).MapNetworkDrive("z:", "\\fileserver\user\%LogonUser%
")
Exception calling "MapNetworkDrive" with "2" argument(s): "The specified network resource or device is no longer availa
ble.
"
At line:1 char:56
+ (New-Object -ComObject WScript.Network).MapNetworkDrive <<<< ("z:", "\\fileserver\user\%LogonUser%")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

PS C:\Users\me>


Thanks


Powershell : Deploying msp, msi, or exe to remote computers

$
0
0

Hello Everyone!

I was wondering if anyone could give me some pointers on how i could go about deploying msi, msp, and exe to remote machines using both from WinRM and WMI approaches. 

I'd like to be able to be dynamic so that i can add any UNC path to a read-host and then the name of the file with any switches i may want to add from an additional read-host.

I have seen some variation of different ways to deploy from powershell, but i havent seen one that actually works for remote machines.

Thank you, look forward to speaking with you all.

Powershell script for Ad users

$
0
0

I have a requirement to run powershell script for below scenario.I have 3 field in AD which is Employee Id,userAccountControl
& sa-grp2(has multiple values like (2,4,6,7).I have to get the users when employee id is not blank ,userAccountControl is true  and sa-grp2-2,4,6,7.How to work on this query?

Thanks

Add domain user and group to local administrator

$
0
0

Hi all,

Need your help to modify my script to work much efficiantly, i have script for add the domain groups to local admin it's works fine for only one host,

                                            1. i need it for mutiple hosts (csv or txt)

                                            2. if already that group or user account added to that hostname i shoud return message " gpgroup already added to this host"

Please help me how to modify this script. please find the attached script below.

        $c = Read-Host " Enter computer name"
        
            
        [string[]]$computerName = $c

        
        ([ADSI]"WinNT://$computerName/Administrators,group").Add("WinNT://code1/ggINGBTCPIC1-dtadmin")
        ([ADSI]"WinNT://$computerName/Administrators,group").Add("WinNT://code1/ggINGBTCPIC1-itadmin")
        ([ADSI]"WinNT://$computerName/Administrators,group").Add("WinNT://code1/ggINGBTCPIC1-mancomp")
        ([ADSI]"WinNT://$computerName/Administrators,group").Add("WinNT://code1/ggINGBTCPIC5-mancomp")
        
       
        


k sivakumar

powershell glitch when putting Active Directory data into Excel

$
0
0

I'm compiling a script to collect AD info and put into Excel...

I'm selecting DisplayName, SamAccountName, sid, Email, CreationDate, ModificationDate

When the step comes to put the collected data into Excel, all fields are filled in with the exception of the SID field.

Heres the code:

### Get all user accounts
$ADUserAccounts = Get-QADUser|Select DisplayName, SamAccountName, sid, Email, CreationDate, ModificationDate

### Create a Excel Workspace
$excel = New-Object -ComObject Excel.Application

### Disable Excel visibilty
$excel.visible = $true

### Create blank workbook
$workbook = $excel.Workbooks.add()

### Create Sheet 1
### This sheet is the summary presentation part of report
$s1 = $workbook.sheets|where {$_.name -eq 'Sheet1'}
$s1.Delete()

### Create Sheet 2
### This sheet will have all Domain user info
$s2 = $workbook.sheets|where {$_.name -eq 'Sheet2'}
$s2.name = "User Accounts"
### Add information to sheet 2
$cells= $s2.Cells
    $s2.range("A1:A1").cells="DisplayName"
    $s2.range("A1:A1").font.bold = "true"
    $s2.range("B1:B1").cells="UserName"
    $s2.range("B1:B1").font.bold = "true"
    $s2.range("C1:C1").cells="SID"
    $s2.range("C1:C1").font.bold = "true"
    $s2.range("D1:D1").cells="Email"
    $s2.range("D1:D1").font.bold = "true"
    $s2.range("E1:E1").cells="Created"
    $s2.range("E1:E1").font.bold = "true"
    $s2.range("F1:F1").cells="Modified"
    $s2.range("F1:F1").font.bold = "true"

$Row2=2
$col1=1
$col2=2
$col3=3
$col4=4
$col5=5
$col6=6
    Foreach ($user in $ADUserAccounts) {
        $Row2++
	    $col1=1
	    $col2=2
        $col3=3
        $col4=4
        $col5=5
        $col6=6
        $cells.item($Row2,$col1)=$user.DisplayName
	$col1++
        $cells.item($Row2,$col2)=$user.SamAccountName
        $col2++
        $cells.item($Row2,$col3)=$user.Sid
        $col3++
        $cells.item($Row2,$col4)=$user.Email
        $col4++
        $cells.item($Row2,$col5)=$user.CreationDate
        $col5++
        $cells.item($Row2,$col6)=$user.ModificationDate
        $col6++
		}
$s2.range("A1:F1").EntireColumn.autofit() | out-Null


# get sheet and update sheet name
		$s6 = $workbook.Sheets.add()
		$s6.name = "Report Summary"
		
# Put user information on Sheet - 1 
		$s6.range("D7:D7").cells="Title:"
		$s6.range("D7:D7").font.bold = "true"
		$s6.range("E7:E7").cells="Active Directory GUM Report"
		$s6.range("D8:D8").font.bold = "true"
		$s6.range("D8:D8").cells="Generated By:"
		$s6.range("E8:E8").cells="$env:username"
		$s6.range("D9:D9").font.bold = "true"
		$s6.range("D9:D9").cells="Generation Date:"
		$s6.range("E9:E9").cells=$date
		$s6.range("D7:D9").EntireColumn.autofit() | out-Null		
#Saving File
"`n"
write-Host "Saving file in $env:userprofile\desktop"
$workbook.SaveAs("$env:userprofile\desktop\ActiveDirectoryReport.xlsx")

#############################################

...need help...please...anyone!!!???!!!

Tks!!!


Team is a group in which members work together to achieve a common goal.

Add multiple groups as group Owners

$
0
0

Hi,

I am creating Sharepoint using power shell script with one group as group owner

$web.SiteGroups.Add($GroupName, $grpSecMgr, $Null, $Null)

where my $grpSecMgr variable contains the group name of the owner group

now i want to add multiple groups owners i.e i will be storing multiple group values in array and use that array . Any suggestions/pointers would be higly appreceated

Viewing all 2562 articles
Browse latest View live


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