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

Need help with Get-Content using regex

$
0
0

Hi,

I have created the following code which searches through a log file and displays the number of results it finds.

Im using regex to create a filter for the Get-Content command.

http://regexr.com/3dtau

The regex works fine, but doesn't seem to count the results correctly.  

Anything obvious i'm doing wrong?

$VolumeName = "1TB USB3 Backup Disk 2"
$TodaysDate = get-date -format 'dd-MM-yyyy HH'
$WeeklyDiskConnection = "C:\SBSA\EBD\WDC.log"

$combineSearch = "$TodaysDate $VolumeName"

$regexDisk = "^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d\s(17|18|19|20).+Disk [1-3]$"
$a = [regex]$regexDisk
$b = $a.Match("$($combineSearch )")
$c = $b.Captures[0].value

$Count = (get-content $WeeklyDiskConnection -Tail 55 | select-string -pattern "$($b.Captures[0].value)").Length

echo $Count

Example of log file contents:

29-07-2016 08:52 U:1TB USB3 Backup Disk 1
29-07-2016 09:20 U:1TB USB3 Backup Disk 1
29-07-2016 10:20 U:1TB USB3 Backup Disk 1
29-07-2016 11:20 U:1TB USB3 Backup Disk 2
29-07-2016 12:20 U:1TB USB3 Backup Disk 2
29-07-2016 13:20 U:1TB USB3 Backup Disk 2
29-07-2016 14:20 U:1TB USB3 Backup Disk 2

thanks,

Fulton.


Have a good day.



C# Application executing Exchange cmdlets outputs messages to the Immediate Window in Visual Studio

$
0
0

I am currently trying to figure out how I get access to the messages that are being written to the Immediate Window in Visual Studio when the pipeline.Invoke() command is executed. I have been looking for events I can latch onto, to have this information also sent to a log file.

When the pipeline.Invoke() command is called, prior to it finishing, the following messages, are put into the immediate window and are the ones I would like to have in a log file.

[00000000] 12:06:14.482 D Creating AD sessions for ''
[00000000] 12:06:14.501 D Creating AD sessions for ''
[00000000] 12:06:14.502 D MRSClient: attempting to connect to 'ACADIA.xxxxxxxx.com'
[00000000] 12:06:14.516 D MRSClient: connected to 'ACADIA.xxxxxxxx.com', version 15.0.1178.0 caps:1FFF

Here is the method being used when these messages occur, take in mind it's during the p.Invoke() command.

public static CreateMailboxExportResponse CreateMailboxExportRequest(string path, string upn, string dc, bool isArchive = false)
        {
            CreateMailboxExportResponse response = new CreateMailboxExportResponse();
            string suffix = "primary";
            if (isArchive)
                suffix = "archive";

            try
            {
                CreateRunspace();
                Pipeline p = mRunspace.CreatePipeline();
                using (p)
                {
                    Command cmd = new Command("New-MailboxExportRequest");
                    cmd.Parameters.Add(new CommandParameter("BatchName", "TerminationActivities"));
                    cmd.Parameters.Add(new CommandParameter("FilePath", path));
                    cmd.Parameters.Add(new CommandParameter("Confirm", false));
                    cmd.Parameters.Add(new CommandParameter("BadItemLimit", 10000));
                    cmd.Parameters.Add(new CommandParameter("AcceptLargeDataLoss", true));
                    cmd.Parameters.Add(new CommandParameter("WarningAction", "SilentlyContinue"));
                    if (isArchive)
                        cmd.Parameters.Add(new CommandParameter("IsArchive"));
                    cmd.Parameters.Add(new CommandParameter("Mailbox", upn));
                    cmd.Parameters.Add(new CommandParameter("DomainController", dc));
                    cmd.Parameters.Add(new CommandParameter("Name", (upn.Replace('@', '_') + "_" + suffix)));
                    cmd.Parameters.Add(new CommandParameter("Suspend", true));
                    cmd.Parameters.Add(new CommandParameter("SuspendComment", "Termination Testing"));
                    p.Commands.Add(cmd);Collection<PSObject> results = p.Invoke();

                    if (results != null)
                    {
                        if (results.Count > 0)
                            response.ExportRequest = results[0];
                    }
                }
            }
            catch (Exception ex)
            {
                response.HasError = true;
                response.Error = ex.Message.ToString();
            }
            return response;
        }

Any help getting the messages in the immediate window logged would be greatly appreciated.


How can I create registry key with slash in name?

$
0
0

I'm trying to create registry key as follows:

New-Item -Path 'HKCU:\Software\VB and VBA Program Settings\Liaison 98\SitaHost\PC/PCM'

New-Item -Path "HKCU:\Software\VB and VBA Program Settings\Liaison 98\SitaHost\PC/PCM"

New-Item -Path "HKCU:\Software\VB and VBA Program Settings\Liaison 98\SitaHost\PC`/PCM"


All 3 commands give error:

New-Item : The registry key at the specified path does not exist.
At line:1 char:1
+ New-Item -Path "HKCU:\Software\VB and VBA Program Settings\Liaison 98\SitaHost\P ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (HKEY_CURRENT_US... 98\SitaHost\PC:String) [New-Item], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.NewItemCommand

As I understand it treats slash in PC/PCM as path seperator, and as PC key is missing it throws me an error. How can I escape slash in path so it will treat it as part of the name and not path seperator?

Retrieve data from an array

$
0
0

Hi 

I'm generating a SSRS report using Powershell. If I use static variables I can create the report. However I only want to use the last two items in the list of variable values obtained from the report to populate the input report parameters. Any help or guidance would be much appreciated. Please see below for the code I'm using.

Kind regards,

Helen

#-------------------------------------------------------------- 
# add assembly 
#-------------------------------------------------------------- 
Add-Type -AssemblyName "Microsoft.ReportViewer.WinForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"

#-------------------------------------------------------------- 
# display calculated month end date 
#-------------------------------------------------------------- 
$startTime = Get-Date 
Write-Host ("=" * 80) 
Write-Host "Generating Report" 
Write-Host "Start Time: $startTime" 
Write-Host ("=" * 80)

#-------------------------------------------------------------- 
# create timestamped folder 
# where we will save our report 
#-------------------------------------------------------------- 
$dt = Get-Date -Format "yyyy-MMM-dd hhmmtt" 
$baseFolder = "\\xxx\xxx\"

# if the path exists, will error silently and continue 
New-Item -ItemType Directory -Path $baseFolder -ErrorAction SilentlyContinue | Out-Null

$rv = New-Object Microsoft.Reporting.WinForms.ReportViewer

#-------------------------------------------------------------- 
# report Server Properties 
#-------------------------------------------------------------- 
$rv.ServerReport.ReportServerUrl = "http://xxx/ReportServer" 
$rv.ServerReport.ReportPath = "/xxx/xxx" 
$rv.ProcessingMode = "Remote"

$rv.ServerReport.GetParameters() |
ForEach-Object {
    $param = $_
    $validValues = ""
    if ($param.ValidValues -ne $null)
    {
        $validValues = [string]::Join(",", ($param.ValidValues[-1..-2] |
                       ForEach-Object {$_.Value}))
    }

    $item = [PSCustomObject] @{
        ParamName = $param.Name
        ValidValues = $validValues
    }

 #$item
   $T15 = $item

   foreach ($element in $T15){$element   }

#$RegRefString =""
#if ($param = 'P_RegRef') {$RegRefString = $validValues}

#$RegRefString =""
#if ($T15.ParamName = 'P_RegRef') {$RegRefString = $T15.ValidValues}

}


# report parameters 
#-------------------------------------------------------------- 
$inputParams = @{ 
"P_RegRef" = $RegRefString;
"P_Qual" = $Qual;
}

#-------------------------------------------------------------- 
# set up report parameters 
#-------------------------------------------------------------- 
$params = $null

#create an array based on how many incoming parameters 
$params = New-Object 'Microsoft.Reporting.WinForms.ReportParameter[]' $inputParams.Count

$i = 0 
foreach ($p in $inputParams.GetEnumerator()) 

$params[$i] = New-Object Microsoft.Reporting.WinForms.ReportParameter($p.Name, $p.Value, $false) 
$i++ 

# set the parameters 
$rv.ServerReport.SetParameters($params) 
$rv.ShowParameterPrompts = $false 
$rv.RefreshReport() 
$rv.ServerReport.Refresh()

#-------------------------------------------------------------- 
# set rendering parameters 
#-------------------------------------------------------------- 
$mimeType = $null 
$encoding = $null 
$extension = $null 
$streamids = $null 
$warnings = $null

#-------------------------------------------------------------- 
# render the SSRS report in Excel 
#-------------------------------------------------------------- 
$bytes = $null 
$bytes = $rv.ServerReport.Render("Excel", 
$null, 
[ref] $mimeType, 
[ref] $encoding, 
[ref] $extension, 
[ref] $streamids, 
[ref] $warnings)

#-------------------------------------------------------------- 
# save the report to a file 
#-------------------------------------------------------------- 
$fileName = $baseFolder + "Report.xls" 
$fileStream = New-Object System.IO.FileStream($fileName, [System.IO.FileMode]::OpenOrCreate) 
$fileStream.Write($bytes, 0, $bytes.Length) 
$fileStream.Close()

#-------------------------------------------------------------- 
# calculate end time and duration 
#-------------------------------------------------------------- 
$endTime = Get-Date 
$duration = New-TimeSpan -Start $startTime -End $endTime 
Write-Host ("=" * 80) 
Write-Host "End Time: $endTime" 
Write-Host "Duration: $duration " 
Write-Host ("=" * 80)

#-------------------------------------------------------------- 
# show folder 
#-------------------------------------------------------------- 
explorer $baseFolder

 

Get- Date Format Powershell

$
0
0

Hi,

I would like to get day and month with leading 0. ( 02-06-2016)

But when I execute below , I get error Get-Date : Cannot bind parameter 'Date'. Cannot convert value "MM" to type "System.DateTime". Error: "The string was not recognized as a valid DateTime. There is a unknown word starting at index 0."

$a = Get-Date -format "MM dd YYYY" ( only this will work)
$Month = $a.Month
$date  = $a.Day
$year = $a.Year

$Month

$date

$Year

Passwordlastset is showing Blank in GetAD Report

$
0
0

Hi Guys,

can any one help me I am getting blank in passwordlastset for some users when i run the command Get-aduser.

Get-ADUser -Identity  Username -Properties * | select passwordLastset,LastLogonDate.

what could be the reason , checked user details  through dsa.msc , all looks good user not disable even he loged in system few days Back

Regards,

Triyambak


Regards, Triyambak

PowerShell memory usage for double includes.

$
0
0

I have a toplevel.ps1 script that includes .includes validation.ps1. toplevel.ps1 also includes settings.ps1. The settings.ps1 also includes validation.ps1 so that it may be .included by other scripts that do NOT .include validation.ps1.

Does the double inclusion use more memory?

pseudo code below

####toplevel.ps1 ####

toplevel.ps1

   .include settings.ps1

   .include validation.ps1

end toplevel.ps1

#### settings.ps1 ####

settings.ps1

   .include validation.ps1

end toplevel.ps1

Parse GPRESULT XML for applied settings

$
0
0

I am attempting to parse the output from a gpresult XML file, in order to retrieve the values for specific applied settings. I have generated the XML and imported it as a variable:

gpresult.exe /x C:\Temp\results.xml /f

$results = [xml] (Get-Content C:\Temp\results.xml)


I need to capture the password policy settings, which are contained in the Default Domain Policy. Here's an excerpt of the XML that shows these settings:

<ExtensionData><Extension xmlns:q2="http://www.microsoft.com/GroupPolicy/Settings/Security" xsi:type="q2:SecuritySettings" xmlns="http://www.microsoft.com/GroupPolicy/Settings"><q2:Account><GPO xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base"><Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{31B2F340-016D-11D2-945F-00C04FB984F9}</Identifier><Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">tailspintoys.com</Domain></GPO><Precedence xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base">1</Precedence><q2:Name>MaximumPasswordAge</q2:Name><q2:SettingNumber>42</q2:SettingNumber><q2:Type>Password</q2:Type></q2:Account><q2:Account><GPO xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base"><Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{31B2F340-016D-11D2-945F-00C04FB984F9}</Identifier><Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">tailspintoys.com</Domain></GPO><Precedence xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base">1</Precedence><q2:Name>MinimumPasswordAge</q2:Name><q2:SettingNumber>1</q2:SettingNumber><q2:Type>Password</q2:Type></q2:Account><q2:Account><GPO xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base"><Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{31B2F340-016D-11D2-945F-00C04FB984F9}</Identifier><Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">tailspintoys.com</Domain></GPO><Precedence xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base">1</Precedence><q2:Name>LockoutBadCount</q2:Name><q2:SettingNumber>0</q2:SettingNumber><q2:Type>Account Lockout</q2:Type></q2:Account><q2:Account><GPO xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base"><Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{31B2F340-016D-11D2-945F-00C04FB984F9}</Identifier><Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">tailspintoys.com</Domain></GPO><Precedence xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base">1</Precedence><q2:Name>PasswordHistorySize</q2:Name><q2:SettingNumber>24</q2:SettingNumber><q2:Type>Password</q2:Type></q2:Account><q2:Account><GPO xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base"><Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{31B2F340-016D-11D2-945F-00C04FB984F9}</Identifier><Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">tailspintoys.com</Domain></GPO><Precedence xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base">1</Precedence><q2:Name>MinimumPasswordLength</q2:Name><q2:SettingNumber>7</q2:SettingNumber><q2:Type>Password</q2:Type></q2:Account><q2:Account><GPO xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base"><Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{31B2F340-016D-11D2-945F-00C04FB984F9}</Identifier><Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">tailspintoys.com</Domain></GPO><Precedence xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base">1</Precedence><q2:Name>PasswordComplexity</q2:Name><q2:SettingBoolean>true</q2:SettingBoolean><q2:Type>Password</q2:Type></q2:Account><q2:Account><GPO xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base"><Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{31B2F340-016D-11D2-945F-00C04FB984F9}</Identifier><Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">tailspintoys.com</Domain></GPO><Precedence xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base">1</Precedence><q2:Name>ClearTextPassword</q2:Name><q2:SettingBoolean>false</q2:SettingBoolean><q2:Type>Password</q2:Type> 

I've been exploring the dot-notation, and can see the Default Domain Policy. But how do I drill down and capture the values I need?

$results.DocumentElement.ComputerResults.GPO | Where-Object {$_.Name -eq "Default Domain Policy"}

Name             : Default Domain Policy
Path             : Path
VersionDirectory : 9
VersionSysvol    : 9
Enabled          : true
IsValid          : true
FilterAllowed    : true
AccessDenied     : false
Link             : Link
SecurityFilter   : NT AUTHORITY\Authenticated Users
ExtensionName    : {{B1BE8D72-6EAC-11D2-A4EA-00C04F79F83A}, Security, Registry}



Triple-Hop Credential Issues

$
0
0

Hi,

Steps:

  • I have a server remoting into another server to launch a custom application.
  • The custom application then connects to a database using SSPI
  • Unfortunately, the context that is passed to the DB server is NT AUTHORITY\ANONYMOUS

The remote session is using the correct credentials and winrm and CredSSP are properly configured.

Question:

  • Why is the custom application not getting the correct user context to use with SSPI

Thanks

Powershell Script to Backup Cisco router configs

$
0
0

I am trying to create a PowerShell script to logon to a Cisco router, get into privilege mode and output the configs to a text file, however I get the following error:

A positional parameter cannot be found that accepts argument 'Successfully connected to router.example.com'.

Here is my script:

Import-Module SshShell

$time ="$(get-date -f yyyy-MM-dd)"
$filename ="config"
$ext =".txt"
$filepath ="C:\Backups"
$Hostname = "Router"
$Domain = "rns.xx.example.com"
$FQDN = $Hostname + $Domain
$elevatedPrompt = $Hostname + "#"
$user ="Joe"
$password ="Doe"
$c1 ="show run"

$s = New-SshSession -ComputerName $FQDN -User $user -Password $password
Send-SshCommand $s "enable" -Expect "Password:"
Send-SshCommand $s "$password" -Expect $elevatedPrompt
Send-SshCommand $s "sh run" | Out-File "$filepath$filename-$time$ext"

Close-SshSession $s


remote service restart from sqlserver agent through powershell. Error

$
0
0

Hello,

I am new to powershell. I am trying to stop remote server service from a sql server agent job through a powershell script.

The script fails at line 5 without much details.

Below is the script which i am running as it is from inside a sqlserver agent job:

$services = "wuauserv" $SvrName = 'MyRemoteServer' get-service -computername $SvrName -name $services | % { Write-host "$($_.Name) on $($Service.Machinename) is $($_.Status)" If ($_.status -eq 'stopped') { Write-host "Starting $($_.name) ..." Write-host "$($_.name) is started" $_.Start()} elseIf ($_.status -eq 'running') { Write-host "Stopping $($_.name)..." Write-host "$($_.name) is stopped" $_.Stop() } }

The script is running as a sqlserveragentuser which is a domain account who is administrator on the remote server.

Error:

Unable to start execution of step 1 (reason: line(5): Syntax error).  The step failed.

Gurus need you valuable inputs. Thanks



Powershell script to do automated deployments for SSRS 2014, error while setting a shared dataset

$
0
0

I am trying to write a Powershell script to do automated deployments for SSRS 2014.  My problem is linking the report to a shared dataset.  I keep getting the error:  [ERROR] Cannot convert argument "ItemReferences", with value: "System.Object[]", for 
[ERROR] "SetItemReferences" to type "SSRS.ReportingService2010.ItemReference[]": 
[ERROR] "Cannot convert the "SSRS.ReportingService2010.ItemReference" value of type 
[ERROR] "SSRS.ReportingService2010.ItemReference" to type 
[ERROR] "SSRS.ReportingService2010.ItemReference"."
[ERROR] At C:\Users\bshaw20\Documents\SSRS\Powershell Deploy\SSRS Deploy\SSRS 
[ERROR] Deploy\prototypev4.ps1:224 char:46
[ERROR] +         $rs.SetItemReferences($reportPath, @($myDataset))
[ERROR] +                                              ~~~~~~~~~~
[ERROR]     + CategoryInfo          : NotSpecified: (:) [], MethodException
[ERROR]     + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

Here is my script:

function LinkSharedDataSets {
  # Get a list of reports and link them with the shared datasets

$reportServerUri = "http://reportingdev.energytransfer.net/reportserver/ReportService2010.asmx?wsdl"

$rs = New-WebServiceProxy -Uri $reportServerUri -UseDefaultCredential -Namespace SSRS.ReportingService2010
$rpts = $rs.ListChildren($targetFolderRDL, $false)

  $newDataSetName = "/Interstate Apps/Commercial/Set/setSum"
  $myDS = "setSum"

  $rpts | ForEach-Object {
    $reportPath = $_.path
    Write-Host "Report: " $reportPath
    $dataSets = $rs.GetItemReferences($reportPath, "DataSet")
    $dataSets | ForEach-Object {
      if ($_.Name -eq $myDS) {
        $myDataset = New-Object -TypeName SSRS.ReportingService2010.ItemReference
        $myDataset.Name = $myDS
        $myDataset.Reference = $newDataSetName
        $myRefs += $myDataset
        $rs.SetItemReferences($reportPath, @($myDataset))
      }
    }
  }
}

PowerShell Gurus needed for July!

$
0
0

Come forth all you technical gurus and word wizards!

It's time to show us what you've got, what you know, what you found out!

Spare your fellow professionals from the same mistake!

Share your revelations and awesome ways of doing things!

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.

June's entries are with our judges right now, but here is a reminder of the previous month's winners.

Guru Award BizTalk Technical Guru – May 2016 
Gold Award Winner

Kjetil TonstadTop 10 Tips From a BizTalk Admin to BizTalk DevelopersTGN: “I love this, how to help each other. Well done Kjetil!”
JS: “Integration apps are a lot more than coding. Always remember these.”
SW: “Great article. With the current DevOps trend alignment between developers and administers is key!”
Ed Price: “This is a good set of tips, with a few helpful images, and the Reference links at the bottom give more context. Great job!”
Silver Award Winner

Eldert GrootenboerBizTalk Server: Processing large files (streaming)Ed Price: “Great mix of code, images, and descriptions. Although the code isn’t broken up much (with explanations of what the code does), all the code comments make up for it and make it super clear! Good to end with the See Also section!”
SW: “Streaming large message can be a challenge with BizTalk. This article provide guidance in that area. Very good!”
TGN: “I love this, well explained and a question that is very relevant to BizTalk”
Bronze Award Winner

SMSVikasKBizTalk Server 2013 R2 Dynamics CRM Online / On Premise CRUD Operations (Part 1)JS: “Seeing a lot of CRM lately. Good info for anyone who hasn’t worked with it before.”
SW: “CRUD om Dynamics guidance article. Good”
Ed Price: “Great description (I like CRUD) and fantastic use of images, although it would be better with more explanations in the text.”
TGN: “Why did you split these up into to articles? good article though”

Guru Award Forefront Identity Manager Technical Guru – May 2016 
Gold Award Winner

Peter GeelenFIM2010 / MIM2016: Run profile statistics with PowerShell and Excel Pivot TablesEd Price: “I love the code formatting with the scroll bar. Great explanations and use of images!”
Silver Award Winner

Peter GeelenFIM2010 / MIM2016: Run profile statistics with SQL and Excel Pivot TablesEd Price: “It’s great to have the downloads on TechNet Gallery!”

Guru Award Microsoft Azure Technical Guru – May 2016 
Gold Award Winner

Bhushan GawaleGetting Started with Azure Automation DSCAS: “Very good and helpful article! Thanks for publishing!”
Ed Price: “Great starting point for learning Azure Automation DSC! Good use of images and code, with excellent explanations!”
Silver Award Winner

Sibeesh VenuCreating Azure Mobile App With Visual Studio AS: “Good starting point, but for me all screenshots are broken – none of them is visible. I would find it particularly useful if you just have provided links to a more detailed article(s) on how to configure Visual Studio for windows Mobile development. And probably just show a sample with HTML/JS or UWP (if it is available)”
Ed Price: “What an important topic that’s very well described! The images add a lot of value!”
Bronze Award Winner

Sandro PereiraAzure Logic Apps: Tips and Tricks about the “new” Logic Apps DesignerAS: “A good overview of designer features! I would however also expect to see the less known fact that drop down lists are actually filtered and there is much more to discover when you begin typing into the search field.”
Ed Price: “The images are magnificently assembled to make this process incredibly clear. A very important topic! Great job!”
Guru Award Miscellaneous Technical Guru – May 2016 
Gold Award Winner

ChilbertoConnecting a BitBucket Repository to Visual Studio Team ServicesRichard Mueller: “Well explained. We need links/references.”
Ed Price: “Great use of images. This is a fantastic scenario! It could use a See Also section. “
Silver Award Winner

Carmelo La MonicaManage analog sensor with Raspberry pi2Richard Mueller: “Grammar needs work and we need links/references.”
Ed Price: “Thorough, and great to have the code and images! But it could benefit from breaking apart the code and explaining what it does more, as well as ending with See Also and References sections. Great to have the TOC.”

Guru Award SharePoint 2010 / 2013 Technical Guru – May 2016 
Gold Award Winner

Dan ChristianHow to build a custom report for SharePoint Server lists, libraries or sitesJohn Naguib: “Great one well done”
Margriet Bruggeman: “Great article with not only text, but also images and videos to make this very user friendly.”
Hezequias Vasconcelos: “Great article. Content technical good. Well detailed, great of attached reference materials. Excellent technical guide.”
Ed Price: “Fantastically thorough, with great images and explanations, and once again, your YouTube videos just blow me away, with how well they help tell the story and are integrated into the article like this! It’s a true art form!”
Silver Award Winner

Waqas SarwarSharePoint 2016 How to Change SuitBar’s Text PowerShellHezequias Vasconcelos: “Good content new platform SharePoint 2016. great scripts and well distributed in the Shell”
Ed Price: “Short and sweet! Fantastic scenario. It could use more references and links to other Wiki articles.”
Bronze Award Winner

Vivek JAGGAAlternative Solutions to the Deprecated Features in SharePoint 2016Ed Price: “I love how you’re very clear at the front of this article (as an overview) and then dig deeper into the specifics. Good references at the end.”
John Naguib: “Nice article you can add also the development area”
Margriet Bruggeman: “Useful article with good alternatives. “

Guru Award Small Basic Technical Guru – May 2016 
Gold Award Winner

Philip MuntsSmall Basic: Simpler and Cheaper Raspberry Pi GPIOMichiel Van Hoorn: “This is really Awesome (see also the original article). It opens up Small Basic to the real world. ”
Ed Price: “Building off his Raspberry Pi article, this article does an amazing job of digging deeper and showing you more options, such as Raspberry Pi Zero.”
Silver Award Winner

Nonki TakahashiSmall Basic: ImageMichiel Van Hoorn: “Really cool overview of working with Images (like photos) in SmallBasic. We good topic to inspire programming”
Ed Price: “Very thorough end to end overview of using Images!”

Guru Award SQL BI and Power BI Technical Guru – May 2016 
Gold Award Winner

Greg DecklerGood Ol’ VLOOKUP – The Ultimate Guide to Lookups in Power BIPT: “Quite a valuable and well-written article. Thank you for the extensive coverage of various lookup techniques.”
RB: “Interesting comparison of the lookup techniques available within Power BI.”
Silver Award Winner

Anil MaharjanHow to find a Calculated Measure and Calculated Dimension within a particular cubePT: “This submission a very brief and just mentions a little information that is common knowledge and easily discovered with a simple web search.”
RB: “Interesting tip, a screen dump of the result with all the columns would have been great.”

Guru Award SQL Server General and Database Engine Technical Guru – May 2016 
Gold Award Winner

ChervineStretching SQL Server 2016 tables to the Azure CloudJS: “Great article, your explanations and samples are spot on.”
Ed Price: “Super valuable scenario! Love the diagram, code snippets, and screen shots!”
Silver Award Winner

ShankyWhat Does Fragmentation Means In a Heap Table In SQL ServerEd Price: “Very thorough! Great references at the end.”

Guru Award System Center Technical Guru – May 2016 
Gold Award Winner

vishwanatham sridharSCOM Connector Design prototypeEd Price: “Great scenario with some helpful reference links!”
Silver Award Winner

Anders RodlandSCCM 2012 R2 step-by-step: upgrade of SP1 to current branch – Step by StepEd Price: “Missing the images. Very thorough steps! Great use of the TOC. Could benefit from references.”
Bronze Award Winner

Anders RodlandSystem Center Configuration Manager Build NumbersEd Price: “Good collection of builds and KBs!”

Guru Award Transact-SQL Technical Guru – May 2016 

Guru Award Universal Windows Apps Technical Guru – May 2016 
Gold Award Winner

Namrah KhurramTraffic Lights Simulation via LEDs on Raspberry PiTGN: “Man this is cool. Good information and well structured. well I’m impresses Namrah!”
Ed Price: “A cool scenario that’s masterfully explained! The code has great formatting. It could benefit from See Also and References sections at the end.”
Silver Award Winner

Manuel Cota“DrawIndexedInstanced and the Concepts behind a Home-Made Game Engine”Ed Price: “It could benefit from a TOC at the top and from See Also and References sections at the bottom, but I love how this breaks down the code and explains everything in depth! Great use of diagrams!”
TGN: “I learned a lot from this article. Well done, thanks for sharing!”
Bronze Award Winner

Sajid Ali KhanUWP: Things Required To Do Right After Creation of New ProjectEd Price: “Great use of images and good References section at the end! I love how the code is both on GitHub and MSDN Gallery and how the download links are given!”
TGN: “This can help a lot of people, my favourite this month! Thanks for sharing Sajid”

Guru Award Visual C# Technical Guru – May 2016 
Gold Award Winner

Emiliano MussoEntity Framework Introduction using C#, part IEd Price: “This is a masterful article, It’s thoroughly broken down, and it leverages images, great code formatting, and even a download and an Italian language version at the end!”
Jaliya Udagedara: “Great article with step by step explanation. If you are a newbie to EF, read this one article which will cover most of the basics. And you can download the sample code from MSDN Code Gallery.”
Carmelo La Monica: “Good and very impressive article, it explain in all parts Entity Framework 7, i attend second part “
Silver Award Winner

SYEDSHANUMVC ASP.NET Identity customizing for adding profile imageCarmelo La Monica: “Very good expression, good images and very detailed in all parts.”
Ed Price: “Very thorough steps! Great scenario!”
Jaliya Udagedara: “Good article explaining how you can manage your profile picture with a ASP.NET MVC application. Sample code is available in MSDN Code Gallery.”

Guru Award Wiki and Portals Technical Guru – May 2016 
Gold Award Winner

Peter GeelenWiki: Fixing table layout (table right side off page)Richard Mueller: “Great information that will help a great deal to fix tables in the Wiki. Good use of Wiki guidelines.”
Ed Price: “This is a fantastic solution from Peter!”

Guru Award Windows PowerShell Technical Guru – May 2016 
Gold Award Winner

Matt McNabbOffice 365: How to Manager User License Lifecycle with PowerShellEd Price: “Wow! Great description of these steps, and it ends well with several other links to dig into!”
Richard Mueller: “Good TOC. An excellent idea to code this and overcome limitations. This should be very useful.”
Silver Award Winner

Arleta WanatSharePoint Online: Get all checked-out files using PowershellRichard Mueller: “Good headings and TOC. Good ideas and well explained.”
Ed Price: “Great scenario and use of PowerShell code!”

Guru Award Windows Server Technical Guru – May 2016 
Gold Award Winner

Kia Zhi Tang (Ryen Tang)Nano Server: Using New-NanoServerImage with Show-Command to deploy Nano ServerMark Parris: “Excellent article on the deployment of Nano server. ”
JM: “This is an excellent article on building a new Nano Server, thanks for your contribution!”
Richard Mueller: “Good use of Wiki guidelines, with even horizontal rules and Return to top links. Show-Command is a very interesting feature I like a lot. Good references.”

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!

use filesystemwatcher to monitor file folder, send email alert if no file in folder for last 30 minutes,

$
0
0

I use filesystemwatcher object to monitor file folder, it works fine. I use timer object, that works too. But when I use both together, It does not work.

Within file create event of filesystemwatcher object, I have a timer. When I drop first file to the file folder, the Timer object starts. When I drop the second file to the shared folder, filesystemwatcher will not response until the timer job finish in 30 minutes. Anyone have done the similar task? 

Thanks in advance

suppressing the 'yellow' warning output?

$
0
0

Hello,

I know there are various ways to suppress the 'RED' error info, using -ErrorAction SilentlyContinue, or trap{}, etc... but for the first time I have run into a scenario where I get this 'YELLOW' warning output... how do I suppress it?

PS SQLSERVER:\sql> (gi wrongInstanceName -ea silentlyContinue) -eq $null
WARNING: Could not obtain SQL Server Service information. An attempt to connect to WMI on 'wds-smqs' failed with the following error: The RPC
server is unavailable. (Exception from HRESULT: 0x800706BA)
True

in example above, that output is yellow, the red error output is suppressed with -ea SilentlyContinue. Is there a way to also suppress this yellow warning output? I will be checking for and handling error cases in my script and I would rather not have this warning be output.


How to join 2 functions.

$
0
0

Hello i am quite new at powershell. But i try to learn it. I have to function at moment.

1) Folder Watch - will check new files in folder

2) Regex file and output new file.

What i want to do is when first script find new files in folder then second script start run and make regex and output new file.

Function Register-Watcher {

    param ($folder)
    $filter = "*.*" #all files
    $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
        IncludeSubdirectories = $false
        EnableRaisingEvents = $true
    }



    $changeAction = [scriptblock]::Create('
        # This is the code which will be executed every time a file change is detected
        $path = $Event.SourceEventArgs.FullPath
        $name = $Event.SourceEventArgs.Name
        $changeType = $Event.SourceEventArgs.ChangeType
        $timeStamp = $Event.TimeGenerated
        Write-Host "The file $name was $changeType at $timeStamp"



    ')

    Register-ObjectEvent $Watcher "Created" -Action $changeAction


}

 Register-Watcher "C:\site-download"

Function regex-inout { $input_path = "C:\site-download\input.txt"
$output_file = "C:\site-download\output.txt"
$regex = "(?<month>VPIP<\/span><span class=""right"">\d{2}.\d{1})"
$regex2 = "(?<month>Winrate<\/span><span class=""right"">\d{1}.\d{1})"
$regex3 = "(?<month>PFR<\/span><span class=""right"">\d{2}.\d{1})"
$regex4 = "(?<month>Winnings<\/span><span class=""right"">\-[0-9]{1,9})"
$regex5 = "(?<month>3Bet<\/span><span class=""right"">\d{1}.\d{1})"

select-string -Path $input_path -Pattern $regex -List | % { $_.Matches} | % { $_.Value } | Foreach-Object {$_ -replace '</span><span class=""right"">', ' = '} | Add-Content $output_file
select-string -Path $input_path -Pattern $regex2 -List | % { $_.Matches} | % { $_.Value } |Foreach-Object {$_ -replace '</span><span class=""right"">', ' = '} | Add-Content $output_file
select-string -Path $input_path -Pattern $regex3 -List | % { $_.Matches} | % { $_.Value } | Foreach-Object {$_ -replace '</span><span class=""right"">', ' = '} | Add-Content $output_file
select-string -Path $input_path -Pattern $regex4 -List | % { $_.Matches} | % { $_.Value } |Foreach-Object {$_ -replace '</span><span class=""right"">', ' = '} | Add-Content $output_file
select-string -Path $input_path -Pattern $regex5 -List | % { $_.Matches} | % { $_.Value } | Foreach-Object {$_ -replace '</span><span class=""right"">', ' = '} | Add-Content $output_file

} regex-inout

Help - I need PowerShell scripts for downloading and uploading files from remote FTPS site

$
0
0

Can anyone help me with creating a powershell script for downloading and uploading files from remote  FTPS site. 

I can upload and download the folder contents from a vanilla FTP site easily, but could not find a .net library that handles same from FTPS ( port 990) site. Has Microsoft abandoned FTPS?

Running batch file in remote machine

$
0
0

HI, 

Lets say i am in machine1. I want to execute a batch file which is in machine2, so that notepad.exe will be executed and a notepad will be opened onmachine2 

How can i do this using powershell script.


sekhar

Need Help with Powershell/WMI and SCCM 2007. Error with Put()

$
0
0

Dear colleagues,

I am currently struggling when trying to automate the creation of a SCCM Software Package by using Package Definition Files (*.sms) provided by our packaging team.

If I create the Software package filling manually the Attributes and Executing Put in the end, it works fine. Software Package is correctly created. (replace SCCM Server and XXX values below by yours)

$packageClass = [WMICLASS]"\\SCCMSERVER\root\sms\site_XXX:SMS_Package"
$newPackage = $packageClass.createInstance()
$newPackage.Name = "My Test Program"
$newPackage.Version = "0004.200"
$newPackage.Manufacturer = "TEST"
$newPackage.Language = "English"
$newPackage.Description = "Test package to test Powershell/WMI scripting Package Creation"
$newPackage.PkgSourceFlag = 2
$newPackage.PkgSourcePath = "\\SERVERNAME\SHARE$\TEST\PATH2PACKAGE"
$newPackage.Put()

If I manually Create the Package from the Console using the New Package from Definition it also works well (Package and Programs are correctly Created (Test.sms file used for the test copied below after my signature; It is dummy)

If I try to use Powershell/WMI to create the Package from the *.sms file using SMS_PDF_Package Class, when I get the package Object, after setting the PkgSourcePath and trying to execute Put, I get the following error:

Method invocation failed because [System.Management.ManagementBaseObject] doesn't contain a method named 'Put'.
At C:\Test\TestCreatePackagefromPDF.ps1:10 char:1+ $newPackage.Put()+ ~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (Put:String) [], RuntimeException+ FullyQualifiedErrorId : MethodNotFound

The code used is the following:

$PDFPackagePath = "C:\TEMP\Test.sms"
$PDFPackage = [IO.File]::ReadAlltext($PDFPackagePath)
$PackagePDFClass = [WMICLASS]"\\SCCMSERVER\root\sms\site_XXX:SMS_PDF_Package"
$PkgPDFID = $PackagePDFClass.LoadPDF($PDFPackagePath,$PDFPackage)
$Obj = $PackagePDFClass.GetPDFData($PkgPDFID.PDFID)
$newPackage = $Obj.PackageData
$Programs = $Obj.ProgramData
$newPackage.PkgSourceFlag = 2
$newPackage.PkgSourcePath = "\\SERVERNAME\SHARE$\TEST\PATH2PACKAGE"
$newPackage.Put()
If I compare the Objects $newPackage in both codes I get the same info. But in the first case I am able to save the Package by running Put() and in the second case I cannot as I get the error above.

The variable $Programs also contain an array to the 2 programs (install, remove) defined in the sms. I am not even able to process them as I couldn't manage to get the Software Package saved first.

Anyone could tell me what I am doing wrong??

Many thanks in advanve

Ramon

Test.sms content pasted below

[PDF]
VERSION=2.0

[PACKAGE DEFINITION]
NAME=Test Package for Powershell/WMI
VERSION=1.0
LANGUAGE=Multilanguage
PUBLISHER=TEST
COMMENT=Test package to test Powershell/WMI scripting Package Creation from PDF
MIFFILENAME=TEST_MSI_PROGRAM
MIFNAME=TEST_MSI_PROGRAM

programs=install,remove

[install]
NAME=TEST_MSI_PROGRAM install
COMMANDLINE=TEST_MSI_PROGRAM_INSTALL.cmd
UserInputRequired=False
AdminRightsRequired=True
DriveLetterConnection=False
CanRunWhen=AnyUserStatus
Run=Hidden

[remove]
NAME=TEST_MSI_PROGRAM remove
COMMANDLINE=TEST_MSI_PROGRAM_REMOVE.cmd
UserInputRequired=False
AdminRightsRequired=True
DriveLetterConnection=False
CanRunWhen=AnyUserStatus
Run=Hidden



Cheers Ramon Jiménez

Run Powershell Script From the Windows Form

$
0
0

Hi friends,

I am trying to  run a powershell script from a windows form.

I have created one button

This ran the bat file successfully.

 private void button1_Click(object sender, EventArgs e)
        {


            System.Diagnostics.Process.Start("C:\\Users\\Dan\\Desktop\\a.bat");

        }



But when i did this

 private void button1_Click(object sender, EventArgs e)
        {


            System.Diagnostics.Process.Start("C:\\Users\\Dan\\Desktop\\a.ps1");

        }



I only got it to open the a.ps1 like a text file

How can I run my power shell script from my button

Cheers Dan

Viewing all 21975 articles
Browse latest View live


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