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

Need a tad of help with a regex

$
0
0

I've been working on this for three days now. Thought it would be easy (is in cmd... lol)

I have a said number of files that I need to script some moves to certain folders. I've done it many times; however, this time I just can't get the right regex

Anyway, I need to match  two static characters at the beginning of a string and a few characters at the end of the string.  Not caring about what is in the middle of the two points.  Seems easy; but, ...   Something like   ab*-05.pdf   works perfectly in cmd

I know it is going to come fast to someone


Remotely enable PSRemoting

$
0
0

Hi guys,

So, the scripting world is new to me but I’m trying to get a handle on it, and hope that you can help me.

I’m working in a mixed environment; our domain contains XP clients and 2008R2 servers. All client computers have PS 2.0 installed.

I want to be able to work with PSRemoting on other client computers. Of course I have Admin privileges and I ran the commands as admin.

My problem is that I can't enable remoting through Group Policy. Our organization is really big and changing GPO will take forever because of IT policies and different approvals.

Right now we have a few jobs we really need to execute and can’t wait till GPO changes are done.

So actually, I’m looking for a way to enable remoting on remote machines in our domain. When I logon interactively to a machine and enable PSReomting, I’m able to work remotly on this machine after that. But I can't find a way to remotely enable PSReomting.

I’ve tried to enable thewinrm service through cmd, and then with PS, like this:

SC\\server start winrm

Then, from PS:

foreach ($i in 'Computer') { Enable-PSRemoting -Force }

Then I ranwinrm quickconfig, and the result was:

WinRM already is set up to receive requests on this machine

WinRM already is set up for remote management on this machine

After performing these steps, I tried remoting and got this error:

"Connecting to remote server failed with the following error message: access is denied. for more info...."

I went through every step in About_Remote_Troubleshooting but found nothing.

After googling for hours I found nothing.

Also, does anyone know if PS Active Directory module is available for XP? After some searching it looks like XP doesn’t support this module, but just to make sure.

Thank youJ

FileSystemWatcher script - call function on change

$
0
0
$fsw = New-Object IO.FileSystemWatcher
$fsw.Path = $path
$fsw.IncludeSubdirectories = $false
$fsw.EnableRaisingEvents = $true

$change = Register-ObjectEvent $fsw Changed -Action {
    $filename = $($event.SourceEventArgs.Name)
    $changetype = $($event.SourceEventArgs.ChangeType)
    $timestamp = $($event.TimeGenerated)
    $eventid = $($event.SourceEventArgs.Id)
    MyFunction ($filename, $changetype, $timestamp, $eventid)
}

How do I call MyFunction from this block of code?

The change event is firing okay but I want to send email, call an executable, etc, when change event fires.  Code within the Register-ObjectEvent block does not seem to execute... am I doing something wrong?

Why does my WPF UI Freezes when trying to update ListBox?

$
0
0

I am having problems when trying to use Register-EngineEvent to update a listBox in a different runspace. (Line 32)http://pastebin.com/JuY5KfP4[1]

When the Search button is pressed it triggers an event to write 'Event Happened' to console and it should return 'Test' to the UI ListBox. However, the part of the event that should be updating the ListBox is causing the UI to freeze.

I got a single thread version of this to work, however, my UI would freeze while doing a complex search (in my case a Get-ChildItem on a big directory). This is how I came across using different Runspace's. http://learn-powershell.net/2012/10/14/powershell-and-wpf-writing-data-to-a-ui-from-a-different-runspace/[2]

I have found someone with a very similar problem: http://stackoverflow.com/questions/23699507/why-does-this-code-freeze-my-wpf-ui[3] but I could not find a solution or an explanation.

PS version: 4.0

This is new territory to me so please forgive me if I use the wrong terminology. 

Thank you for your time.


Compare multidimensional arrays

$
0
0

I've got a problem with multidimensional arrays. I need to compare two multidimensional arrays as follows:

$array1
number      word

$array2
number      word

If "number" from $array1 matches any "number" in $array2, check if corresponding "word" from $array1 also matches "word" in $array2.
Also accept wildcards "*" for "word" in @array1, which should match any "word" in $array2.

Write out all non-matches to a third array, $array3.
The arrays are very different in size. $array1 will hold at most 50 entries. $array2 will probably contain hundreds or thousands.
I'm not very experienced with multidimensional arrays and can't figure out how to loop and match.

Bonus points to the one who figures out what I'm trying to achieve with this. :-)

Thanks in advance! 

  

Powershell in dynamic Table

$
0
0
How to get Dynamic Table in powershell please help me

Deleting registry keys.

$
0
0

Hi, Newbie here. I was laid off for a while and have really gotten rusty on my skills with Powershell which were in the fetus stage at that time. Anyway, I need to delete the contens of this registry key from 150 or so Win 7 boxes.

HKLM\SW\MS\Windows Defender\Signature Updates

I would like for the script to write to a CSV file for success or failure for each machine it touches.

I know this is a simple script, but can someone get me back in the game here?

Thanks!


Capperdog

Little help with a script

$
0
0

Hello guys,

I'm hoping that you guys can give me a little bit of help with a script that i'm trying to write, i'm a beginner when it comes to scripting so you're help it's greatly appreciated. The purpose of the script below is to through to a list of different DNS domain names and search for certain criteria and then display on the screen or file for me, the problem that I'm running into is that I don't know how to display or write to file the variable $dnszone to the screen so that when I get the output for hostnames I can tell from which DNS zone it came from.

Here is the script thus far

$dnszones = Get-Content "C:\all_dnz_zones.txt"
$IPv4Address = "10.10.*"
foreach ($dnszone in $dnszones) {Get-DnsServerResourceRecord -ZoneName $dnszone -ComputerName htxdc01 | Where-Object {$_.RecordData.IPv4Address -like $IPv4Address}}

This is the output that I see write now, i'm missing the $dnszone names :(



Multiple params in cmdlet

$
0
0

Hi,

Im in powershell for couple years now, but still I have doubts how to manage multiple params in custom c# cmdlet's. I don't like having multiple if's. 

Do you have some solution on this, maybe some pattern?

regards.

pw.

Use Powershell to Add AD Computer Object to an AD Group

$
0
0

Hello, I am trying to write a script that adds a Computer Object in Active Directory to a group.  The script works fine if I run it against a computer object that has been in AD a long time.  However, if I run the script on an object that has been recently added to the domain, it always fails.  The purpose of this process is to run it on newly domain joined machines, which isn't working.

I get the following error:

The following exception occurred while retrieving member "Add": "Unknown error (0x80005000)"

Anyone have any ideas why this is happening and any ideas on how to fix it?  My script is below (note: I can't use AD cmdlets to accomplish this as I have to be able to run it from servers that do not have those components installed):

# Get parameters, if not specified ask for them or set default value.
param ([string] $ADGroup, [string] $ComputerName)
If (!$ADGroup)
{
 $ADGroup = read-host "Enter the Active Directory group to add object to: "
}

If (!$ComputerName)
{
    $ComputerName = $env:computername
}

# Set LDAP Search Parameters to find computer account.
$ComputerFilter = "(&(objectCategory=Computer)(CN=$ComputerName))"
$GroupFilter = "(&(objectCategory=Group)(CN=$ADGroup))"

$Domain = New-Object System.DirectoryServices.DirectoryEntry

$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.SearchRoot = $Domain
$Searcher.PageSize = 1000
$Searcher.SearchScope = "Subtree"

# Set LDAP property list, comma seperated for powershell array (ie. "adspath", "cn")
$PropertyList = "adspath"

foreach ($Property in $PropertyList)
{
    $Searcher.PropertiesToLoad.Add($Property) | Out-Null
}

#Find Computer Path
$Searcher.Filter = $ComputerFilter
$FindCP = $Searcher.FindOne()
$ComputerPath = $FindCP.Properties.adspath

#Find Group Path
$Searcher.Filter = $GroupFilter
$FindGP = $Searcher.FindOne()
$GroupPath = $FindGP.Properties.adspath

# Get Group Object
$Group = [ADSI]"$GroupPath"

# Add Computer to Group
$Group.Add("$ComputerPath")
$Group.SetInfo()

Forms and input boxes

$
0
0

Hi,

I have a script which works. What I would like is a user friendly form, which requires input from a user, which will then edit the content of the script before running it.

Ideally I need about 3 input boxes, each one will edit a variable in the script.

Input box 1 will edit $x in the script

Input box 2 will edit $y in the script

Input box 3 will edit $z in the script

Then an 'enter' button to run script.

Thanks in advance for any assistance.

Nested function not recognized as the name of a cmdlet

$
0
0
Below is the file (highly simplified versions) of interest:

main-func.psm1:
function main-func
{    [CmdletBinding()]    param    ()    Write-Verbose "In main-func"    main-workflow
}

workflow main-workflow
{
    [CmdletBinding()]    param     ()    Write-Verbose "In main-workflow"    func-outer
}

function func-outer
{
    [CmdletBinding()]    param   ()   Write-Verbose "In func-outer"    func-inner
}

function func-inner
{
    [CmdletBinding()]    param    ()    Write-Verbose "In func-inner"
}

Export-ModuleMember -function main-func
Now I open Windows Powershell and execute the following commands:
> Import-Module .\main-func.psm1> main-func -Verbose

The output that I get is as below:
VERBOSE: In main-func
VERBOSE: [localhost]:In main-workflow
VERBOSE: [localhost]:In func-outer
The term 'func-inner' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.    + CategoryInfo          : ObjectNotFound: (func-inner:String) [func-outer], CommandNotFoundException    + FullyQualifiedErrorId : CommandNotFoundException,func-outer    + PSComputerName        : [localhost]
But if I replace main-workflow in function main-func with func-outer, then it works.

I'm pretty new to Powershell and Workflows and using workflows is a requirement. Can somebody please explain what's wrong here?


Synchronize files and folders

$
0
0

Is there already some kind of script in place created in Powershell and uses robocopy to synchronize files ?

I need to be able to do the following:

Make use of separate input files for robocopy command

    • Copy directories to remote location
    • Input files for script
    • Included file: For included folders, sub-folders (not whole root folders should be copied) and included files
    • Excluded file: For excluded sub-directories and excluded files.

If it’s not created yet, anyone got an idea on how it should look like ?

LDAP Paged Search Problem

$
0
0

Hi,

I posted this question in the "Directory Services" forum but was told it was a wrong forum (http://social.technet.microsoft.com/Forums/en-CA/winserverDS/thread/478f03b8-9a15-44d9-81c3-c72ab786faf1), so if this is a wrong forum again, kindly direct me to the right one, thanks.

I was trying to create a general LDAP Search function not using the DirectorySearcher class, after running into issues with it (http://dunnry.com/blog/PagingInSystemDirectoryServicesProtocols.aspx).  As suggested by several posts on the net, I'm using DirectoryServices.Protocols namespace to bypass the issues with the COM objects.  However, I don't seem to get the paging part to work.  The code only returns the first page of results.  More precisely, the PageResultResponseControl does not return a cookie, although many more pages are expected.

Here is my code:

function LDAPPagedSearch ([string]$searchRoot= ([adsi]'LDAP://rootDSE').defaultNamingContext.value, [string]$filter= {throw'filter is required'}, [String[]]$attributes= @('name'), [switch]$typesOnly, $dc=$script:domainController)
{$resultSet= @()$connection= New-Object System.DirectoryServices.Protocols.LdapConnection($dc)$connection.Timeout = New-Object system.TimeSpan(3.8e10)$searchRequest= New-Object System.DirectoryServices.Protocols.SearchRequest($searchRoot,$filter,[System.DirectoryServices.Protocols.SearchScope]::Subtree,$attributes)$searchRequest.TimeLimit = New-Object system.TimeSpan(3e9)$searchRequest.SizeLimit =[int]::MaxValue$searchRequest.TypesOnly =$typesOnly$pageResultControl= New-Object System.DirectoryServices.Protocols.PageResultRequestControl(10)[Void]$searchRequest.Controls.Add($pageResultControl)do
	{$searchResponse=[System.DirectoryServices.Protocols.SearchResponse]$connection.SendRequest($searchRequest)$searchResponse.Controls | ? { $_-is[System.DirectoryServices.Protocols.PageResultResponseControl] } | % {$pageResultControl.Cookie = ([System.DirectoryServices.Protocols.PageResultResponseControl]$_).Cookie
		}$resultSet+=$searchResponse.Entries
	}while ($pageResultControl.Cookie.length -gt 0)return$resultSet
}

cls
$script:domainController= ([ADSI]"LDAP://RootDSE").dnsHostName.value$searchRoot= ([adsi]'LDAP://rootDSE').defaultNamingContext.value$searchFilter='(&(objectcategory=person)(objectclass=user))'$searchAttrib= @('name')$usersResult= @(LDAPPagedSearch -searchRoot $searchRoot-filter$searchFilter-attributes $searchAttrib-typesOnly)


So when the above code is run, I only get back 10 results (the first page), although there are 400,000 user objects in the domain.  Is there anything I did wrong?

Thanks in advance.

Invoke PS session

$
0
0

Hi,

I'm trying to get a poweshell script to run as my privileged account in an enterprise domain below is the power shell script that I'm running. This is just a test script where I'm trying to get-process at the mometn.

Start-Transcript C:\Users\useraccount\Desktop\PSLog.txt
$computer = Read-host "please enter a fully qualified computer name"
Test-WsMan $computer
Invoke-Command -ComputerName $computer -ScriptBlock { Get-Process Powershell > C:\Users\useraccount\Desktop\Process.tx  } -credential [-username]
exit
Read-Host -Prompt "Press Enter to exit"
Stop-Transcript

I'm using the below batch command to run the script.

@ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
PAUSE

And below is the Transcript:

**********************
Windows PowerShell Transcript Start
Start time: 20150525160839
Username  : domain\PriviledgedAccount 
Machine : HostName (Microsoft Windows NT 6.1.7601 Service Pack 1) 
**********************
Transcript started, output file is C:\Users\Useraccount\Desktop\PSLog.txt
please enter a fully qualified computer name: HostName


wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.x
                  sd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 0.0.0 SP: 0.0 Stack: 2.0

[HostName] Connecting to remote server failed with the following error messa
ge : Logon failure: unknown user name or bad password. For more information, se
e the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (:) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionStateBroken
**********************
Windows PowerShell Transcript End
End time: 20150525160902
**********************

Not sure why this is not authenticating, I'm running the batch file as my PriviledgedAccount by holding Shift, Run as a different user.

I will need this to jump across domains eventually but just want to get this to work in one domain at the moment.
Any advice or hints in regards to why I'm getting the authentication error would be greatly appreciated. 



How do I get video file duration in powershell script

$
0
0

Here's a partial code snip. I'd like to test the duration of the original .avi to the newly created .mp4 and

display a warning if they are not within a second of each other:

The duration shows as "length" in Windows explorer

----------------------------------------------------

$movies = ls -recurse $inputpath\*.avi

$starttime = get-date

foreach($movie in $movies){

 $name = $movie.fullname
 $basename=$movie.basename

 $outname=$name.Replace(".avi",".mp4")

 #  skip if mp4 already exists   (Literalpath needed as square brackets in the filename causes problems
 if(!(test-path -literalpath "$outname")){
  write-output "$outname  Started at $now"
  handbrakecli -i "$name" -o "$outname"  --preset="Normal"   2>&1>> D:\'$Data'\convmp4.log
  $now = get-date
  write-output "$outname Done at $now">>d:\'$Data'\convmp4Done.log

  $now=get-date
  $elapsedrun=$now-$starttime
  if ($elapsedrun.Totalminutes -ge $runlimit){
    write-host "Time limit reached of $runlimit minutes at $now"
    write-output "Time limit reached of $runlimit minutes at $now">>d:\'$Data'\convmp4Done.log
      exit
      }

  }
 else{
 write-output "Skipping (already exists):  $outname $length"
 }

}

    

Parse robocopy Log File - new value

$
0
0

Hello,

I have found a script, that parse the robocopy log file, which looks like this:


-------------------------------------------------------------------------------
   ROBOCOPY     ::     Robust File Copy for Windows                             
-------------------------------------------------------------------------------

  Started : Thu Aug 07 09:30:18 2014

   Source : e:\testfolder\
     Dest : w:\testfolder\

    Files : *.*
    
  Options : *.* /V /NDL /S /E /COPYALL /NP /IS /R:1 /W:5

------------------------------------------------------------------------------

     Same          14.6 g e:\testfolder\bigfile - Copy (5).out
     Same          14.6 g e:\testfolder\bigfile - Copy.out
     Same          14.6 g e:\testfolder\bigfile.out

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         1         0         0         0
   Files :         3         3         0         0         0         0
   Bytes :  43.969 g  43.969 g         0         0         0         0
   Times :   0:05:44   0:05:43                       0:00:00   0:00:00


   Speed :           137258891 Bytes/sec.
   Speed :            7854.016 MegaBytes/min.

   Ended : Thu Aug 07 09:36:02 2014

Most values at output file are included, but the two speed paramter not.

How can I get this two speed paramters at output file?

Here is the script:

param(
	[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false,HelpMessage='Source Path with no trailing slash')][string]$SourcePath,
	[switch]$fp
	)

write-host "Robocopy log parser. $(if($fp){"Parsing file entries"} else {"Parsing summaries only, use -fp to parse file entries"})"

#Arguments
# -fp	File parse. Counts status flags and oldest file Slower on big files.

$ElapsedTime = [System.Diagnostics.Stopwatch]::StartNew()
$refreshrate=1 # progress counter refreshes this often when parsing files (in seconds)

# These summary fields always appear in this order in a robocopy log
$HeaderParams = @{
	"04|Started" = "date";"01|Source" = "string";"02|Dest" = "string";"03|Options" = "string";"07|Dirs" = "counts";"08|Files" = "counts";"09|Bytes" = "counts";"10|Times" = "counts";"05|Ended" = "date";
	#"06|Duration" = "string"
}

$ProcessCounts = @{
	"Processed" = 0;"Error" = 0;"Incomplete" = 0
}

$tab=[char]9

$files=get-childitem $SourcePath

$writer=new-object System.IO.StreamWriter("$(get-location)\robocopy-$(get-date -format "dd-MM-yyyy_HH-mm-ss").csv")
function Get-Tail([object]$reader, [int]$count = 10) {

	$lineCount = 0
	[long]$pos = $reader.BaseStream.Length - 1

	while($pos -gt 0)
	{
		$reader.BaseStream.position=$pos

		# 0x0D (#13) = CR
		# 0x0A (#10) = LF
		if ($reader.BaseStream.ReadByte() -eq 10)
		{
			$lineCount++
			if ($lineCount -ge $count) { break }
		}
		$pos--
	}

	# tests for file shorter than requested tail
	if ($lineCount -lt $count -or $pos -ge $reader.BaseStream.Length - 1) {
		$reader.BaseStream.Position=0
	} else {
		# $reader.BaseStream.Position = $pos+1
	}

	$lines=@()
	while(!$reader.EndOfStream) {
		$lines += $reader.ReadLine()
	}
	return $lines
}

function Get-Top([object]$reader, [int]$count = 10)
{
	$lines=@()
	$lineCount = 0
	$reader.BaseStream.Position=0
	while(($linecount -lt $count) -and !$reader.EndOfStream) {
		$lineCount++
		$lines += $reader.ReadLine()
	}
	return $lines
}
function RemoveKey ( $name ) {
	if ( $name -match "|") {
		return $name.split("|")[1]
	} else {
		return ( $name )
	}
}

function GetValue ( $line, $variable ) {

	if ($line -like "*$variable*" -and $line -like "* : *" ) {
		$result = $line.substring( $line.IndexOf(":")+1 )
		return $result
	} else {
		return $null
	}
}

function UnBodgeDate ( $dt ) {
	# Fixes RoboCopy botched date-times in format Sat Feb 16 00:16:49 2013
	if ( $dt -match ".{3} .{3} \d{2} \d{2}:\d{2}:\d{2} \d{4}" ) {
		$dt=$dt.split(" ")
		$dt=$dt[2],$dt[1],$dt[4],$dt[3]
		$dt -join " "
	}
	if ( $dt -as [DateTime] ) {
		return $dt.ToStr("dd/MM/yyyy hh:mm:ss")
	} else {
		return $null
	}
}
function UnpackParams ($params ) {
	# Unpacks file count bloc in the format
	#    Dirs :      1827         0      1827         0         0         0
	#	Files :      9791         0      9791         0         0         0
	#	Bytes :  165.24 m         0  165.24 m         0         0         0
	#	Times :   1:11:23   0:00:00                       0:00:00   1:11:23
	# Parameter name already removed

	if ( $params.length -ge 58 ) {
		$params = $params.ToCharArray()
		$result=(0..5)
		for ( $i = 0; $i -le 5; $i++ ) {
			$result[$i]=$($params[$($i*10 + 1) .. $($i*10 + 9)] -join "").trim()
		}
		$result=$result -join ","
	} else {
		$result = ",,,,,"
	}
	return $result
}

$sourcecount = 0
$targetcount = 1

# Write the header line
$writer.Write("File")
foreach ( $HeaderParam in $HeaderParams.GetEnumerator() | Sort-Object Name ) {
	if ( $HeaderParam.value -eq "counts" ) {
		$tmp="~ Total,~ Copied,~ Skipped,~ Mismatch,~ Failed,~ Extras"
		$tmp=$tmp.replace("~","$(removekey $headerparam.name)")
		$writer.write(",$($tmp)")
	} else {
		$writer.write(",$(removekey $HeaderParam.name)")
	}
}

if($fp){
	$writer.write(",Scanned,Newest,Summary")
}

$writer.WriteLine()

$filecount=0

# Enumerate the files
foreach ($file in $files) {
	$filecount++
    write-host "$filecount/$($files.count) $($file.name) ($($file.length) bytes)"
	$results=@{}
$Stream = $file.Open([System.IO.FileMode]::Open,
                   [System.IO.FileAccess]::Read,
                    [System.IO.FileShare]::ReadWrite)
	$reader = New-Object System.IO.StreamReader($Stream)
	#$filestream=new-object -typename System.IO.StreamReader -argumentlist $file, $true, [System.IO.FileAccess]::Read

	$HeaderFooter = Get-Top $reader 16

	if ( $HeaderFooter -match "ROBOCOPY     ::     Robust File Copy for Windows" ) {
		if ( $HeaderFooter -match "Files : " ) {
			$HeaderFooter = $HeaderFooter -notmatch "Files : "
		}

		[long]$ReaderEndHeader=$reader.BaseStream.position

		$Footer = Get-Tail $reader 16

		$ErrorFooter = $Footer -match "ERROR \d \(0x000000\d\d\) Accessing Source Directory"
		if ($ErrorFooter) {
			$ProcessCounts["Error"]++
			write-host -foregroundcolor red "`t $ErrorFooter"
		} elseif ( $footer -match "---------------" ) {
			$ProcessCounts["Processed"]++
			$i=$Footer.count
			while ( !($Footer[$i] -like "*----------------------*") -or $i -lt 1 ) { $i-- }
			$Footer=$Footer[$i..$Footer.Count]
			$HeaderFooter+=$Footer
		} else {
			$ProcessCounts["Incomplete"]++
			write-host -foregroundcolor yellow "`t Log file $file is missing the footer and may be incomplete"
		}

		foreach ( $HeaderParam in $headerparams.GetEnumerator() | Sort-Object Name ) {
			$name = "$(removekey $HeaderParam.Name)"
			$tmp = GetValue $($HeaderFooter -match "$name : ") $name
			if ( $tmp -ne "" -and $tmp -ne $null ) {
				switch ( $HeaderParam.value ) {"date" { $results[$name]=UnBodgeDate $tmp.trim() }"counts" { $results[$name]=UnpackParams $tmp }"string" { $results[$name] = """$($tmp.trim())""" }
					default { $results[$name] = $tmp.trim() }
				}
			}
		}

		if ( $fp ) {
			write-host "Parsing $($reader.BaseStream.Length) bytes"
			# Now go through the file line by line
			$reader.BaseStream.Position=0
			$filesdone = $false
			$linenumber=0
			$FileResults=@{}
			$newest=[datetime]"1/1/1900"
			$linecount++
			$firsttick=$elapsedtime.elapsed.TotalSeconds
			$tick=$firsttick+$refreshrate
			$LastLineLength=1

			try {
				do {
					$line = $reader.ReadLine()
					$linenumber++
					if (($line -eq "-------------------------------------------------------------------------------" -and $linenumber -gt 16)  ) {
						# line is end of job
						$filesdone=$true
					} elseif ($linenumber -gt 16 -and $line -gt "" ) {
						$buckets=$line.split($tab)

						# this test will pass if the line is a file, fail if a directory
						if ( $buckets.count -gt 3 ) {
							$status=$buckets[1].trim()
							$FileResults["$status"]++

							$SizeDateTime=$buckets[3].trim()
							if ($sizedatetime.length -gt 19 ) {
								$DateTime = $sizedatetime.substring($sizedatetime.length -19)
								if ( $DateTime -as [DateTime] ){
									$DateTimeValue=[datetime]$DateTime
									if ( $DateTimeValue -gt $newest ) { $newest = $DateTimeValue }
								}
							}
						}
					}

					if ( $elapsedtime.elapsed.TotalSeconds -gt $tick ) {
						$line=$line.Trim()
						if ( $line.Length -gt 48 ) {
							$line="[...]"+$line.substring($line.Length-48)
						}
						$line="$([char]13)Parsing > $($linenumber) ($(($reader.BaseStream.Position/$reader.BaseStream.length).tostring("P1"))) - $line"
						write-host $line.PadRight($LastLineLength) -NoNewLine
						$LastLineLength = $line.length
						$tick=$tick+$refreshrate
					}
				} until ($filesdone -or $reader.endofstream)
			}
			finally {
				$reader.Close()
			}

			$line=$($([string][char]13)).padright($lastlinelength)+$([char]13)
			write-host $line -NoNewLine
		}

		$writer.Write("`"$file`"")
		foreach ( $HeaderParam in $HeaderParams.GetEnumerator() | Sort-Object Name ) {
			$name = "$(removekey $HeaderParam.Name)"
			if ( $results[$name] ) {
				$writer.Write(",$($results[$name])")
			} else {
				if ( $ErrorFooter ) {
					#placeholder
				} elseif ( $HeaderParam.Value -eq "counts" ) {
					$writer.Write(",,,,,,")
				} else {
					$writer.Write(",")
				}
			}
		}

		if ( $ErrorFooter ) {
			$tmp = $($ErrorFooter -join "").substring(20)
			$tmp=$tmp.substring(0,$tmp.indexof(")")+1)+","+$tmp
			$writer.write(",,$tmp")
		} elseif ( $fp ) {
			$writer.write(",$LineCount,$($newest.ToString('dd/MM/yyyy hh:mm:ss'))")
			foreach ( $FileResult in $FileResults.GetEnumerator() ) {
				$writer.write(",$($FileResult.Name): $($FileResult.Value);")
			}
		}

		$writer.WriteLine()

	} else {
		write-host -foregroundcolor darkgray "$($file.name) is not recognised as a RoboCopy log file"
	}
}

write-host "$filecount files scanned in $($elapsedtime.elapsed.tostring()), $($ProcessCounts["Processed"]) complete, $($ProcessCounts["Error"]) have errors, $($ProcessCounts["Incomplete"]) incomplete"
write-host  "Results written to $($writer.basestream.name)"
$writer.close()

I hope somebody can help me,

Horst


Thanks Horst MOSS 2007 Farm; MOSS 2010 Farm; TFS 2010; TFS 2013; IIS 7.5

How to save and pass variable to xWebSite DSC resource BindingInfo parameter.

$
0
0

Let's say I'd like to divide data and configuration and I'd love to sites binding info in DSCConfigurationdata file, separately from DSC configuration like that:

        xWebsite xWebsite1
        {
            Name = "site.name.com"
            ApplicationPool = "site.name.com"
            Ensure = "Present"
            PhysicalPath = "C:\Inetpub\wwwroot\site.name.com"
            State = "Started"
            BindingInfo = $Node.BindingInfo
        }

and  DSCConfigurationdata file will contain something following:

            BindingInfo = @(
                            @{
                                   Protocol = "HTTP"
                                   Port = 80
                                   IPAddress = "1.1.1.1"
                                   HostName = "site.name.com"
                              },
                            @{
                                   Protocol = "HTTPS"
                                   Port = 443
                                   IPAddress = "1.1.1.1"
                                   HostName = "site.name.com"
                                   CertificateThumbprint = "54634563456345"
                                   CertificateStoreName = "WebHosting"
                              }
                           )

But since BindingInfo should be of type [CimInstance[]]] and this is specific CIM instance defined resource I can instantiate it and create an array of elements of CimInstance (actually MSFT_xWebBindingInformation class).

So can anybody please can help me on how to achieve that.

Thanks in advance.

how get a group of computer's average memory ultilization and average cpu ultilization, average page out per second and peak disk ultilization and operating system name

$
0
0

not all computers in active directory, can i use DNS host instead of active directory to do the request

when using active directory, i got error, where can find the group name of computers?

PS C:\Users\Administrator\Downloads> .\RunCommand.ps1 FileServicesGroup "systemi
nfo | findstr /C:""Total Physical Memory"""
The term 'Get-ADGroupMember' is not recognized as the name of a cmdlet, functio
n, script file, or operable program. Check the spelling of the name, or if a pa
th was included, verify that the path is correct and try again.
At C:\Users\Administrator\Downloads\RunCommand.ps1:11 char:36
+ $ADGroupMembers = Get-ADGroupMember <<<<  -Identity $ADGroupName
    + CategoryInfo          : ObjectNotFound: (Get-ADGroupMember:String) [], C
   ommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Invoke-Command : Cannot validate argument on parameter 'ComputerName'. The argu
ment is null or empty. Supply an argument that is not null or empty and then tr
y the command again.
At C:\Users\Administrator\Downloads\RunCommand.ps1:15 char:33
+     Invoke-Command -ComputerName <<<<  $computer.name -ScriptBlock $ScriptBlo
ckContent -ArgumentList $CommandToRun
    + CategoryInfo          : InvalidData: (:) [Invoke-Command], ParameterBind
   ingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power
   Shell.Commands.InvokeCommandCommand

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$true, Position=1)][string]$ADGroupName,
    [Parameter(Mandatory=$true, Position=2)][string]$CommandToRun
)

$ScriptBlockContent = {
    param ($CommandToRun)
    Invoke-Expression $CommandToRun }

$ADGroupMembers = Get-ADGroupMember -Identity $ADGroupName
foreach ($computer in $ADGroupMembers)
{
    #Run the required command on each computer in the group
    Invoke-Command -ComputerName $computer.name -ScriptBlock $ScriptBlockContent -ArgumentList $CommandToRun
}


can not choose absolute uri, why there are still choices?

RESPONSE REQUEST: PowerShell Gurus Please Connect with Internet of Thinkers (aka TNWiki)

$
0
0

May the Thoughts be with you!

Well, a small nod there to Star Wars day, and we turn our thoughts to more the serious matter of ingesting the more valuable brain telemetry from and to our very own Internet of Thinkers!

Connect to the real network, the world wide workers!

Cut through the chatter and produce some pertinent protocols!

All over the world, highly intellegent autominous entities are uploading neural nuggets of gold, words of wisdom and inspirational instructionals!

So step forward... beacons of brain power, and download your technical torrent of tips to the Head Hub - TechNet Wiki!

 

All you have to do is add an article to TechNet Wiki from your own specialist field. Something that fits into one of the categories listed on the submissions page. Copy in your own blog posts, a forum solution, a white paper, or just something you had to solve for your own day's work today.

Drop us some nifty knowledge, or superb snippets, and become MICROSOFT TECHNOLOGY GURU OF THE MONTH!

This is an official Microsoft TechNet recognition, where people such as yourselves can truly get noticed!

HOW TO WIN

1) Please copy over your Microsoft technical solutions and revelations toTechNet Wiki.

2) Add a link to it on THIS WIKI COMPETITION PAGE (so we know you've contributed)

3) Every month, we will highlight your contributions, and select a "Guru of the Month" in each technology.

If you win, we will sing your praises in blogs and forums, similar to the weekly contributor awards. Once "on our radar" and making your mark, you will probably be interviewed for your greatness, and maybe eventually even invited into other inner TechNet/MSDN circles!

Winning this award in your favoured technology will help us learn the active members in each community.

Feel free to ask any questions below.

More about TechNet Guru Awards

Thanks in advance!
Pete Laker


#PEJL
Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over toTechNet Wiki, for future generations to benefit from! You'll never get archived again, and you could win weekly awards!

Have you got what it takes o become this month's TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!

Viewing all 21975 articles
Browse latest View live


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