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

Variable property subtraction | $a gathered property minus $b gathered property

$
0
0

Hello, guys

I'm looking suggestion how to use subtraction between variables.

I mean I'm getting all properties from $A.

$A=get-winevent-LognameMicrosoft-Windows-TaskScheduler/Operational|Where-Object{$_.ID-eq"200"-and$_.message-match|"content validation"} selecttimecreated,ID,Message|ft*-Autosize

Results (needable property - "Timecreated":

Also im getting Time created propertie from another variable.

$b=get-winevent-LognameMicrosoft-Windows-TaskScheduler/Operational|Where-Object{$_.ID-eq"201"-and$_.message-match"content validation"}|selecttimecreated,ID,Message|ft*-Autosize

Question: How I can subtract newest gathered data and time from variable $A from newest gathered time from variable $B and get difference?




How to read NTFS permissions in a list of shares from a text file

$
0
0

Hi,

I’am trying to get it easier to use on file servers. I would like to import a file called shares.txt

in that shares.txt there are for example lines
e.g folder name -> root folder and share name -> sub folder

    \\10.10.15.240\folder name\share name

    \\10.10.15.240\folder name\share2 name

    \\10.10.15.240\folder name\share3 name


    \\10.10.15.240\folder2 name\share name

    \\10.10.15.240\folder2 name\share2 name

    \\10.10.15.240\folder2 name\share3 name

and so on. 

And i would like to create the output to:
Outputs the data to a text file on \\10.10.15.240\output\ using the folder name and share name as part of the file name

     \\10.10.15.240\output\Company_name_$folder name_$share name.csv
     \\10.10.15.240\output\Company_name_$folder name_$share2 name.csv
     \\10.10.15.240\output\Company_name_$folder name_$share3 name.csv


     \\10.10.15.240\output\Company_name_$folder2 name_$share name.csv
     \\10.10.15.240\output\Company_name_$folder2 name_$share2 name.csv
     \\10.10.15.240\output\Company_name_$folder2 name_$share3 name.csv

and continue 

Do you know how to import this in your script? I tried several things but they all comes up with errors. Like i said iam a newbie to powershell.

Script : 

I want to write the permissions list to a CSV file instead of writing it directly to Excel.

$ErrorActionPreference = "SilentlyContinue"
$a = New-Object -comobject Excel.Application 
$a.visible = $True

$b = $a.Workbooks.Add()

$intRow=1
$c = $b.Worksheets.Item(1)
$c.Cells.Item($intRow,1) = "Folder"
$c.Cells.Item($intRow,2) = "Compte/groupe"
$c.Cells.Item($intRow,3) = "Type d'Acces"
$c.Cells.Item($intRow,4) = "Droits"


$d = $c.UsedRange
$d.EntireColumn.AutoFit()|Out-Null
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True


remove-variable arrayOfPath
$depth=2
$RootFolder="\\MySRV\Folder"

for($i=0; $i -le $depth;$i++)
 {
 $arrayOfPath += ,$RootFolder
 $RootFolder=$RootFolder+"\*"
 }
$arrayOfPath |get-childitem |%{get-acl $_.fullname}|
 %{
 $intRow=$intRow+1  
 $c.Cells.Item($intRow, 1)=$_.path.tostring().replace("Microsoft.PowerShell.Core\FileSystem::","")
 $droit=$_.access
 $droit|%{$c.Cells.Item($intRow, 2)=$_.IdentityReference.tostring();$c.Cells.Item($intRow, 3)=$_.AccessControlType.tostring();$c.Cells.Item($intRow, 4)=$_.FileSystemRights.tostring();$intRow=$intRow+1}}

$d.EntireColumn.AutoFit()|Out-Null


PowerShell Gurus, step up and be known!

$
0
0

August Gurus step up and show us your knowledge on the latest and the greatest technologies Microsoft have to offer!

And for your efforts, eminent leaders in your technology will evaluate your contributions and award real virtual medals!

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.

Below are June's mighty winners and contenders!

 BizTalk Technical Guru – June 2016 
Gold Award Winner

SMSVikasKHow to Re-create BizTalk Server Project Artifacts from a DLL or an Assembly from an existing projectEd Price: “Great detail! Great job walking us through the images! Glad to have the code download link! As Shashidharan wrote in the comments, “Nice Article Vikas. Very helpful :)” Great job on this!”
Sandro Pereira: “Nice article, very useful! This problem happens more often that you can imagine. Another option will be BizTalk NoS add-in but is great to know other ways!”
SW: “Very useful and informative article.”
Silver Award Winner

Johns-305BizTalk Server: Sending Control Messages to Long Running ProcessesSW: “Excellent article!!!”
Ed Price: “Strong introduction and great use of images! Great to have the sample on MSDN Gallery! It could use a See Also section (links to other Wiki articles) and References.”
Sandro Pereira: “Great article.”
Bronze Award Winner

SMSVikasKBizTalk Custom Pipeline Component to Add, Update, Remove Target Namespace, Qualified Prefix for every elementSandro Pereira: “Again very useful article. This is a common problem and you will find several examples of pipelines to change the target namespace but I think this is the first time I see all 3 operations combined. However, I will follow a different approach and set a property to specify the operation in the pipeline for better clarification”
Ed Price: “Good job on this article. Good use of images and formatted code. Great to have the source code downloadable!”
SW: “Very useful and informative article.”

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

Dileepa KariyawasamUse Azure Active Directory to Custom Brand Your Office 365 Sign In Page – Step by StepEd Price: “This is an incredibly valuable scenario that’s executed well! It could be improved with a TOC and References and See Also sections at the end.”
Silver Award Winner

ChervineSchedule PowerShell Scripts to Manage Azure Virtual MachinesAS: “The article represents good overview of the Azure Automation service. However it is suggested best practice to use service principals in Azure AD instead of a regular users. And use certificate to authenticate the service principal.”
Ed Price: “Wow! Fantastic solution, great write-up, good use of headers/sections, formatting, a diagram, images, code formatting, and a solid References section! As AS mentions, this could be improved with the Azure AD perspective. Great article!”
Bronze Award Winner

Michel JatobáConfiguring Client VPN PowerShell on Microsoft Azure (ARM)Ed Price: “Good job on this. The Introduction, “Configuring VPN Certificate” section, and use of images… really stand out. This article is similar to an Azure doc one (https://azure.microsoft.com/en-us/documentation/articles/vpn-gateway-howto-point-to-site-rm-ps/), but it’s done a little differently, and the images help. It could be improved with See Also and References sections at the end, as well, as little more refinement on the code formatting (which admittedly, should be easier to do). Good job on this. “

Guru Award Miscellaneous Technical Guru – June 2016 
Gold Award Winner

SYED SHANUMVC Dashboard with Chart using AngularJS and WEB APIPhilippe Levesque: “Excellent ! The use of animated gif is really good”
Richard Mueller: “Lots of well thought out code. Grammar needs work.”
Ed Price: “Powerful article with a great use of code! The images won’t show for me. I love the Download section at the end for the MSDN Gallery item!”
Silver Award Winner

Santhakumar MunuswamyDisqus Integration in Asp.Net MVCEd Price: “Beautiful job with the structure, images, and code. Good to have the reference link. ”
Richard Mueller: “Good images. We need more references.”
Philippe Levesque: “”
Bronze Award Winner

Dileepa KariyawasamOffice 365 Journaling Workaround – How to GuideRichard Mueller: “Interesting solution. I like that this is not first person or personalized. Could there be references?”
Philippe Levesque: “”
Ed Price: “Also a good topic. This could be improved with section headers, and with See Also and References sections. Great use of images!”

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

Waqas SarwarSharePoint 2016 Site Use Confirmation and Deletion( real world example)Hezequias Vasconcelos: “It is an excellent content for file management. Helps administrators manage and better optimize disk space in the database.”
TN: “That’s ok to be published even it’s a very basic article”
John Naguib: “Good one”
Silver Award Winner

Waqas SarwarSharePoint 2016: Checklist for Successful InstallationJohn Naguib: “Good CheckList, it is better to upload as excel ”
Hezequias Vasconcelos: “It is an excellent content for SharePoint 2016 installation management I miss about updates to the SQL, and Windows SharePoint and Language packs that are important also in the installation of products. Reference: https://technet.microsoft.com/en-us/library/mt715807(v=office.16).aspx”
TN: “That’s ok to be published even it’s a very basic article”
Bronze Award Winner

Waqas SarwarSharePoint 2016 Managing Registered Accounts and Shell Admin access( Real World Example)John Naguib: “Nice article”
Hezequias Vasconcelos: “Perfect maintenance and account management in SharePoint 2016. Good Job.”
TN: “That’s ok to be published even it’s a very basic article”

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

Nonki TakahashiSmall Basic: MouseEd Price: “I love this series! Nonki takes us end to end on using the mouse in Small Basic. I love the definition! Very strong See Also section.”
Michiel Van Hoorn: “Nonki again delivered a great article on a SB function (MOUSE). Very useful if you want to interact with mouse”
Carmelo La Monica: “I don’t know small basic, but this is good point to learn. Congrats.”
Alan Carlos: “”
Silver Award Winner

DevaSmall Basic VideosCarmelo La Monica: “Very good videos, good fo to learn Small Basic. Congrats for all videos.”
Alan Carlos: “Good guidance, very helpful!”
Michiel Van Hoorn: “Nice overview of available videos”
Ed Price: “Great to have this list on the Wiki! Thanks!”

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

Thomas LeBlancAnalysis Services: Solving Hierarchy Errors of UniquenessPT: “Thanks for the article, Thomas. You’ve explained the use case and steps for creating a hierarchy very plainly. This is a good piece.”
Ed Price: “Great scenario and use of images! It could be improved with headers and a TOC, and with References and See Also sections at the end. This is a powerful topic.”
Silver Award Winner

Sudeep RajIntegration Services: Using DB Mail to send HTML format mailPT: “Thank you for explaining this technique; simple and effective.”
Ed Price: “Fantastic topic from Sudeep, with solid colouring on the code formatting! Could be improved with References and See Also sections.”
Bronze Award Winner

Jens VestergaardExtracting SSAS MD Database(s) XMLA w/ PowerShellPT: “This is a useful script that I’ll probably use in the future. This is a good start but the post could use a little more structure to be complete; an introduction, objective statement and conclusion. Thanks for your contribution.”
Ed Price: “Good PowerShell solution. Could benefit from more of a breakdown of the code. “

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

Hezequias VasconcelosSQL 2016 – Install SSMS Management StudioUR: “Why is an installation instruction of an “old” version of SSMS in June a WIKI? The latest version isn’t a preview anymore. An installation step by step isn’t worth a WIKI entry. I would have seen more details about the differences between SSMS 2016 previous version. What are the differences? What will work better? What (and there is a lot!) is not working good?”
Ronen Ariely: “A great subject for article. Screenshot images of each step helps simplify the instructions, makes the article more useful for new users. There is some room for improvement. See article comment section.”
Silver Award Winner

FLaufferSQL Server Troubleshooting: How to remove a bad execution plan from plan cacheRonen Ariely: “A nice article of a simple case study and a solution. It’s very short and has potential to be even better with a bit more expansion”
UR: “I am missing a more detailed explanation WHY a plan can go wrong. Basically it is more “story around DBCC FREEPROCCACHE”.”

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

Digvijay S RajawatSCVMM 2012 R2 & Hyper-V: Storage Migration in Microsoft Private CloudEd Price: “Wow! Great formatting and sections. Very good use of tables. Could use a See Also section (to link to other Wiki articles). The processes are very clear and incredibly detailed. Fantastic article!”
Carmelo La Monica: “Fantastic topic, very nice in all parts, good images explain in all parts. Good”
Alan Carlos: “Nice article! Congratulations!”
Silver Award Winner

C Sharp ConnerSCORCH – Custom Activity OIP Limitations – C# EditionCarmelo La Monica: “I read this article, i don’t know System center, but is very detailed in all part.”
Alan Carlos: “”
Ed Price: “Good list of limitations. It would have been good to get into the code too. Another good topic!”
Bronze Award Winner

C Sharp ConnerSolution – Install Fresh Data Warehouse on Post UR Updated SCSM EnvironmentEd Price: “A lot of great detail! This could be improved with sections. Great topic!”
Carmelo La Monica: “Good explain, good work. Congrats.”
Alan Carlos: “”

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

Carmelo La MonicaSerial Class for UWP Part oneEd Price: “Great article! Good topic, well-written, great breakdown of sections/headers/TOC, good use of images and code, and good requirements sections! It could use a See Also section at the end with links to related Wiki articles.”
Silver Award Winner

Santhakumar MunuswamyUnderstanding AppBar and CommandBar in UWPEd Price: “Great topic. Good write-up. Good use of images and code! It could be improved with sections/headers/TOC and with See Also and References sections at the end to link to other articles.”
Bronze Award Winner

Damien AllanLaunch your App Differently from Secondary Live TilesEd Price: “Short and sweet. Good use of code and reference links. Could use improved formatting and sections/headers.”

Guru Award Visual Basic Technical Guru – June 2016 
Gold Award Winner

.paul.VB.Net – QR Code CreatorEd Price: “I love the QR Code creator! Incredibly valuable. Great job with the code, formatting, and download!”
MR: “Nice and easy! Would love to know how to generate a QR code from scratch!”
Richard Mueller: “Very useful. Simple but effective code.”

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

Emiliano MussoEntity Framework Introduction using C#, part II – Code-First and MigrationsRonen Ariely: “Excellent article! I loved the idea of writing series of articles. Moreover, the author translated the articles into another language. Great use of the capabilities of the TechNet WIKI.”
Ed Price: “Wow. This is an amazing article! It has it all… a great topic, fantastic formatting with headers, great code formatting, good descriptions, screenshots, references, a link to the MSDN code gallery to download the code, and an Italian version! This is a high-quality article! Other writers (including myself) should look at this one for ideas of how to achieve quality!”
Jaliya Udagedara: “Now this is a fantastic article. Well explained, filled with images, code snippets and the full sample code is available in MSDN Code gallery. Awesome job!”
Silver Award Winner

Sabah ShariqSearching data in Elasticsearch using C#Ronen Ariely: “Great article. I really enjoyed to read it. posting the code ready for download is very useful.”
Ed Price: “Great job breaking down the sections and explaining the code! Could be improved with References and See Also sections. ”
Jaliya Udagedara: “Haven’t used Elastic search before and this article contains instructions for everything that you need to get started. Nice!”
Bronze Award Winner

Sibeesh VenuWorking with API help page controller action description in Web APIEd Price: “A good topic with solid code, but it would be good to breakdown the code more and explain it in chunks.”
Jaliya Udagedara: “If you are having trouble showing descriptions in Web API help pages, this article should help you out.”

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

Carsten SiemensTranslation Wiki: Getting startedRonen Ariely: “This article gave me new information regarding the Translation Wiki Community. This information should be published in any communication channel we have. This is a “must to know” in my opinion.”
Ed Price: “I love it. This is a great process. Thanks to Carsten for building it and Peter for compiling, editing, and publishing!”
Richard Mueller: “Very informative. The images are good, but I had to zoom them. This must have required some research. Perhaps there should be a link to the blog site.”
Silver Award Winner

Peter GeelenWiki: Before you post your article – Quick check listRichard Mueller: “Great use of Wiki guidelines. An excellent guide for all Wiki authors with great advice. I like the emphasis on researching the topic, collecting links for references, and preparing offline.”
Ronen Ariely: “Very useful, very important, and most of all: I love the way it’s organized as a check list”
Ed Price: “This is a fantastic check list to go through before you get started! It will up the quality if we use this!”
Bronze Award Winner

Peter GeelenMicrosoft Security Compliance Manager (SCM) PortalRonen Ariely: “The TechNet WIKI based on portals as an index to navigate the website. This is nice list of articles that act as portal to the Microsoft Security Compliance Manager ”
Ed Price: “Great portal. Good job getting all these links compiled for us!”
Richard Mueller: “Great links. Maybe a few words would be useful.”

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

Richard MuellerPowerShell: Problems with the -ne Operator in Active Directory CmdletsPG: “Nice article, good quality and nice to read. Great!”
Ed Price: “Wow! I love the quality here. You get a ton of explanation for each code excerpt. Plus the Return to Top links provide easy navigation. And it ends with immersive See Also and Other Resources sections!”
Silver Award Winner

Prashanth JayaramPowerShell-List-and-Export-Installed-Program(s)-Local/Remote-system(s)PG: “Except for some introduction, the scripts need more in depth explanation.”
Ed Price: “Love the sections! It would be good to break the code down more and activate the References links at the bottom.”
Bronze Award Winner

Digvijay S RajawatUse PowerShell to Create an Azure VM report with nice lookPG: “Nice quick tip, but please keep in mind that TNWiki is not a personal blog. Better remove the personalisation.”
Ed Price: “Good topic, but it could use more explanations. Good formatting on this article!”

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

Ryen TangNano Server: Deploying MySQL Database ServerMark Parris: “Nice compact article on the new technology that is Nano Server.”
Philippe Levesque: “Excellent article, easy to follow step and well-written!”
JM: “This is a great article on deploying MySQL on Nano, thanks for your contribution!”
Richard Mueller: “Good use of Wiki guidelines, with code, images, and references. Good to have detailed steps.”



#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!

migrating on premise site collections to SharePoint online using powershell

$
0
0

Hi folks,

Intention:-migrating on premise site collection to SharePoint online.

Is there any power-shell script or list availabe products.

Please give idea and let me know that script.

Thanks,

Run new-mailboxsarch queries in succession

$
0
0

I have written out almost 50 queries for search terms, I am now trying to figure out a way to run them in succession.  If I run two at a time they fail, this is the reason for running one at a time.  I am trying to do a do/while statement, but have been unsuccessful they still run at the same time.  Any pointers would be great:


$var = New-MailboxSearch -Name "list 1" -TargetMailbox email -SearchQuery {info} -MessageTypes email -LogLevel full
Do {$var ; start-mailboxsearch "list 1"} until ((Get-MailboxSearch -Identity "list 1" | select status) -eq "Succeeded" -or “Failed” -or “PartiallySucceeded”)

$var2 = New-MailboxSearch -Name "list 2" -TargetMailbox email -SearchQuery {info} -MessageTypes email -LogLevel full
Do {$var2 ; start-mailboxsearch "list 2"} until ((Get-MailboxSearch -Identity "list 2" | select status) -eq "Succeeded" -or “Failed” -or “PartiallySucceeded”)



Run Windows Scheduled Task on a Remote Server?

$
0
0

PowerShell almost-noob...  Can a PS script run on Server A start a Windows Scheduled Task on Server B?  I want to call the PS script from a SQL Server Agent job step on Server A.  

Thanks.

Interacting with app on a specific desktop session

$
0
0

hi guys

I'm new to powershell, but learning to like it. However I have an issue....

Background: We are automating the deployment of our legacy software estate by using Octopus Deploy. Mostly good, however we have a windows forms application which acts as a service that needs to be properly shut down and started up again. This application requires a login, and then a button press to get it started, and this application lives in a desktop session on a server.

My Issue: I can open the application in the correct place using powershell by utilising PsExec. This allows me to open the application within a specific windows desktop session on a machine. What I would like to do now, is login using SendKey commands.

Current script:

$filePath = "C:\Temp\Apps\TheApp.exe"
$psexec = "C:\Temp\PsExec.exe"

Start-Process $psexec " -s -i 1 -d ${filePath}"
Start-Sleep -Seconds 30

$myshell = New-Object -com "Wscript.Shell"

$myshell.AppActivate('Login')
$myshell.SendKeys("mylogin")
$myshell.SendKeys("{TAB}")
$myshell.SendKeys("Test1234")
$myshell.SendKeys("~")

This works perfectly fine in ISE run locally, but when run as a service via an octopus tentacle, the send keys go down a black hole?

Can anyone help? 

changing default printer only works once

$
0
0

Does anyone know why if I try to print a file to a printer then change the default printer and print the file again it goes to the printer that was first selected instead of the new default despite the fact that it changes the default successfully?

Here is the code I am using.

    (Get-WmiObject -ComputerName . -Class Win32_Printer -Filter "Name='RECEPTION-MFC-C'").SetDefaultPrinter() | %{sleep 20;$_}
    Start-Process -FilePath "S:\PrintJobs\ToPrint\*" –Verb Print | %{sleep 3;$_} | kill | %{sleep 10;$_}


    (Get-WmiObject -ComputerName . -Class Win32_Printer -Filter "Name='REEDSTECH-MFC-C'").SetDefaultPrinter() | %{sleep 20;$_}
    Start-Process -FilePath "S:\PrintJobs\ToPrint\*" –Verb Print | %{sleep 3;$_} | kill | %{sleep 10;$_}


    (Get-WmiObject -ComputerName . -Class Win32_Printer -Filter "Name='AR-MFC-C'").SetDefaultPrinter() | %{sleep 20;$_}      
    Start-Process -FilePath "S:\PrintJobs\ToPrint\*" –Verb Print | %{sleep 3;$_} | kill



Issue with piping this data and writing it to SQL server

$
0
0

Hi All

I have a function which pulls out all the members of the local administrators group, i want to collect this data and store it in a SQL server table. There is a function called Write-Datatable which takes any data and than the data can be loaded onto a SQL table.

The rule is that any data can be written by Write-Datatable as long as 

any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.

I have these 2 functions

Function Get-LocalServerGroupMembers
{
    Param(
        [string]
        $server = "."
    )
    Try
    {
        $computer = [ADSI]"WinNT://$( $Server ),computer"
        $computer.psbase.children |
            where {
                $_.psbase.schemaClassName -eq 'group'
            } |
                ForEach {
                    $GroupName = $_.Name.ToString()
                    $group =[ADSI]$_.psbase.Path
                    $group.psbase.Invoke("Members") |
                        foreach {
                            $memberName = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) -replace "WinNT:", ""

                            $props = @{
                                "LocalGroup" = $GroupName"MemberName" = $memberName"ComputerName" = $server
                            }

                            $obj = New-Object -TypeName psobject -Property $props
                            Write-Output $obj
                        } # foreach members
                } # foreach group
    }
    Catch
    {
        Throw
    }
}

And also

Function Get-MyLocalGroupMembers
{
param(
[Parameter(ValuefromPipeline=$true)][array]$server = $env:computername,
$GroupName = $null
)
PROCESS {
    $finalresult = @()
    $computer = [ADSI]"WinNT://$server"

    if (!($groupName))
    {
    $Groups = $computer.psbase.Children | Where {$_.psbase.schemaClassName -eq "group"} | select -expand name
    }
    else
    {
    $groups = $groupName
    }
    $CurrentDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().GetDirectoryEntry() | select name,objectsid
    $domain = $currentdomain.name
    $SID=$CurrentDomain.objectsid
    $DomainSID = (New-Object System.Security.Principal.SecurityIdentifier($sid[0], 0)).value


    foreach ($group in $groups)
    {
    $gmembers = $null
    $LocalGroup = [ADSI]("WinNT://$server/$group,group")


    $GMembers = $LocalGroup.psbase.invoke("Members")
    $GMemberProps = @{Server="$server";"LocalGroup"=$group;Name="";Type="";ADSPath="";Domain="";SID=""}
    $MemberResult = @()


        if ($gmembers)
        {
        foreach ($gmember in $gmembers)
            {
            $membertable = new-object psobject -Property $GMemberProps
            $name = $gmember.GetType().InvokeMember("Name",'GetProperty', $null, $gmember, $null)
            $sid = $gmember.GetType().InvokeMember("objectsid",'GetProperty', $null, $gmember, $null)
            $UserSid = New-Object System.Security.Principal.SecurityIdentifier($sid, 0)
            $class = $gmember.GetType().InvokeMember("Class",'GetProperty', $null, $gmember, $null)
            $ads = $gmember.GetType().InvokeMember("adspath",'GetProperty', $null, $gmember, $null)
            $MemberTable.name= "$name"
            $MemberTable.type= "$class"
            $MemberTable.adspath="$ads"
            $membertable.sid=$usersid.value


            if ($userSID -like "$domainsid*")
                {
                $MemberTable.domain = "$domain"
                }

            $MemberResult += $MemberTable
            }

         }
         $finalresult += $MemberResult
    }
    $finalresult | select server,"localgroup",name,type,domain,sid
    }
}

The issue i am  having is that wen I do this. No data gets written onto the table.

$dt = Get-LocalServerGroupMembers

Write-DataTable -ServerInstance "My-Server" -Database "data_import" -TableName "dbo.test" -Data $dt


invoke-webrequest : The operation has timed out.

$
0
0

Getting a exception when I try to pull data from this webrequest.

$headers = @{Authorization=$access_token}

$MyURI = "https://apis.accela.com//v4/inspections"

$ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($MyURI)

$result = invoke-webrequest -Method GET -Headers $headers -Uri $MyURI

$ServicePoint.CloseConnectionGroup("")

Script to send email report of time-sync (W32tm /Monitor) status for multiple domains.

$
0
0

Hi Friends,

Need your urgent help in this regard.

Looking for a automation script (Powershell) to send mail after capturing the W32tm /Monitor report for multiple domains in a forest. just targeting on DC in forest should capture the all the domains or child roots nested to it.

ex: w32tm /monitor /domain:[domain name]

Explored couple of other scripts but the readable formatting is not simple.


Script 1:

$Servers = "ntp.xxxxx,ntp.xxxxx,dc1,dc2,dc3,dca,dcb,dcc"
$ListDomains = "domain1","domain2"

Foreach ($Server in $ListServers) {
    $time = (w32tm /stripchart /dataonly /computer:$Server /samples:1)[-1].split("[")[0]
    "$Server`: `t $Time" #| out-file $timeFile -append
    $time = ""  


ForEach ($Domain in $ListDomains) {
    "** $Domain **"
    w32tm /monitor /domain:"$Domain.unisa.edu.au" /nowarn /threads:5
}

Script 2:
 $output1 = & w32tm /monitor /domain:yourdomain.com /threads:5
    $stdOutStart = 8
    $output = $output1[$stdOutStart..$output1.Length]
    $timeInfos = @()

    for ($i = 0 ; $i -lt $output.Length ; $i+=4) {
        $server = $output[$i].Split(' ')[0]
        $icmp = $output[$i+1].Trim().Split(' ')[1]
        $offset = $output[$i+2].Trim().Split(' ')[1]
        $timeInfos += New-Object PsObject -Property @{
            Server = $server
            ICMP = $icmp
            Offset = $offset
        }
    }

    $timeInfos

Script 3:

$output = & w32tm /monitor /domain:mylab.com /Threads:5
$output

Script 4:
$output = & w32tm /monitor /domain:mylab.com /threads:5
$output | Where-Object{!$_.StartsWith("Analyzing") -and !$_.StartsWith("           ") -and !$_.Contains(" of ") -and !$_.StartsWith("Stratum") -and !$_.StartsWith("delayoffset")}""


Ravi Ch

PS query all windows servers in AD and specific services

$
0
0
Trying to write script that goes out against AD and does a get-adcomputer looking for any Windows Server operating system, then goes and looks at 3 specific NT service names Healthservice, MsMpSvc, and Netbackup Client Service and report if installed or not as well as report if start or not with server name listed and exported to excel. I would be using elevated domain permissions to run the script. 

Silent Install of .net 4.5 in powershell issue

$
0
0

Hi All,

I am trying  to install dot netframework 4.5.2 on remote machine also getting 16389 error

$DotNetInst="E:\temp\IE11andPowershellv4\NDP452-KB2901907-x86-x64-AllOS-ENU.exe"

$process = (Start-Process -FilePath $DotNetInst -Argumentlist "/q /norestart" -Wait -Verb RunAs)
Write-Host -Fore Red "Errorcode: " $process.ExitCode

 $process.ExitCode returns 16389

Invoke-Command -ComputerName "Server01" -ScriptBlock { Start-Process -FilePath $DotNetInst -ArgumentsList "/q /norestart" } -Crdential $cred

Can anyone help me out on the same?

Get-VM Details from Hyper-V Server

$
0
0

Dear All ,

Could we get Hyper-V VMs Details like VMname,IP Address,operating system,CSV path, memory ,hard disk,virtual FC etc. in Cluster environment .


Best Regards, Hussain

Powershell to Inject Hostname into a Hyper-V based VM before Network Configuration

$
0
0

Hello Team,

I am looking for a powershell way of Injecting Hostname [Or lets say computer name rename] of a VM running on a Hyper-V Host. There is no Network Configuration on this VM, so PSremoting is not the option here, and not looking for unattended answer file injection into VHD.

I am looking for any Hyper-V WMI Class method to inject hostname into the vms running on top of this hyperv host or if there is any other way, please mention.


Thank You.

Regards,

Subhash


Regards,
Subhash Konduru
------------------------------------------------------------------------------------
Please remember to mark the replies as answers if they help and unmark them if they provide no help.


Placing new forms while running

$
0
0

Goooood morning technet!

I've got a little issue there:

I'm making some user interface for my script and I would like to add a form at the end of ma main form each time the user press a button. But is seems that the coordinates of the new created form depends of my position on the main form. So If i press let's say "create a new textbox at X;Y" , the first text box will be created and everything will be great in a world of unicorns. Now if I scroll down and press again "create a new textbox at X;Y", then again, no problem the next text box will be created AFTER the previous one (although X and Y are the same) but if i don't scroll, then the text box will stack one on an other. Now if i set the second text box like "create a new textbox at X;Y+100", we've got the opposite problem, if I scroll down on my main form before pressing the button, the second text box appear too far from the previous one, If I don't then it works fine.

So basically it seems that the new forms are created not form the position 0;0 of the main form but from my actual position on the form, have you guys any solution to that issue?

If not, an alternative would be to change my position on the main form each time I press the "create a new textbox at X;Y" button, and going back on the coordinate 0;0, that way I would just increment the coordinates each time I create a new text box and just avoid the issue BUT, I don't know the command to change the position on the main form, does that exist and does anyone knows it?

Thank you so much for helping!

Yann

Generating IIS Machine Keys with PowerShell

$
0
0

Hi - I have written a PowerShell script to update machine keys for a suite of web applications. I've used the "Generate-MachineKey" function found here: 

https://support.microsoft.com/en-us/kb/2915218#AppendixA

When I generate an HMACSHA512 validation key with this function I get a 256 character output string. But if I use Microsoft IIS admin utility to generate the same key I get a 128 character output string. 

I also notice both the IIS gui and the PowerShell function generate a 128 character output string for HMACSHA256 (so in PowerShell the output for HMACSHA512 is twice the length of HMACSHA256 but in IIS gui both are 128). 

I tested my apps with the PowerShell generated keys and everything works fine. But can anyone explain to me why the output is different lengths from different MS tools and not matching up with the lengths they say these values should be? I want to make sure this PowerShell function is good before I deploy these keys to production web apps. I have spent hours searching and can find no info about this. Any insight would be much appreciated. 

According to this article the lengths should be as stated below: 

https://msdn.microsoft.com/en-us/library/w8h3skw9(v=vs.100).aspx

  • HMACSHA256 requires a 256-bit key (64 hexadecimal characters).

  • HMACSHA384 requires a 384-bit key (96 hexadecimal characters).

  • HMACSHA512 requires a 512-bit key (128 hexadecimal characters).


get user groups

$
0
0

Hello

Is that possible to check in which groups was user certain time ago? for example:

Get-QADMemberOf user1 | (Get-Date).AddMonths(-1)  or something like that?


Shota Tadumadze

Invoking PowerShell.exe with "-Command -" (reading input from StdIn) broken in Windows 10 14393?

$
0
0

I have a C# app that contains an embedded PowerShell script.  Not that this matters, it could be external--the important point is that I execute the script by invoking powershell.exe with "-Command -".  That is, using the -Command parameter followed by a hyphen, which allows you to then provide the body of the script to execute through StdIn.

I like this technique, and I've been using it for over a year as, among other reasons, the script doesn't have to be a single command, it can span many lines, declare functions etc, all the while without ever having the script written to disk in plain text or base64-encoded.

After having installed the Anniversary Update of Windows 10 (1607 aka build 14393), this appears to be broken; the captured StdErr shows it complains about missing function bodies, while StdOut shows--and I find this part rather mind-blowing--the script got mangled in such a way that *all* lines that contain a function declaration, and the following opening *and* closing curly braces, are gone.  The rest of the script appears intact.  Obviously that would cascade into all sorts of errors.

I managed to write a short(-ish) sample that demonstrates this problem.  The same EXE demonstrates that it's broken on Windows 10 14393 (all 3 machines I have that run this version exhibit the same behavior), but it works perfectly fine on Windows 10 10586 as well as Windows 7.

One thing I've discovered is that if I substitute the CR/LF characters from the script with a single space, the error goes away, but what happens then is that the StdOut stream I capture comes back empty--even on other OSes that otherwise previously managed to handle the unmodified script just fine--rather than containing the expected output, which comes from one of the script's functions (which simply does a Write-Host).

Another thing I've discovered is that if I add "-version 2.0" as an argument when invoking powershell.exe, everything reverts back to normal behavior.  While this works around the immediate problem, obviously I'd like to remain version-agnostic, so even though I tend to write my scripts so they can run against the "lowest common denominator", I'd rather not explicitly restrict myself in this fashion, as I may eventually need to write a script that relies on some features that have only been introduced in more recent versions.  So I don't view this as a long-term or permanent solution.

If anyone with a compiler cares to try this out, here's my sample cut-down C# program.  It just needs to be built as a console EXE.

Is anyone else getting the same results?  Any workaround that doesn't require me to change the script itself (as I won't necessarily have any knowledge of what the scripts provided to me actually do, other than the fact that they're all expected to end with a single Write-Host as the final output value I'm interested in)...

using System;
using System.Text;
using System.Diagnostics;

namespace PsTest
{
	class Program
	{
		static void Main( string[] args )
		{
			string strMyScript = @"
function GetFunctionValue()
{
	# This comment is in the GetFunctionValue function
	return $true
}

function ShowValue( [string] $theValue )
{
	# This comment is in the ShowValue function
	Write-Host $theValue
}

# This comment is at the script level, before the function call
ShowValue( GetFunctionValue )

# This comment is at the script level, after the function call
";
			//strMyScript = strMyScript.Replace( "\n", " " ).Replace( "\r", " " );
			//strMyScript = strMyScript.Replace( Environment.NewLine, " " );
			RunScript( strMyScript );
		}

		private static string RunScript( string strScriptBody )
		{
			var stdOutBuilder = new StringBuilder();
			var stdErrBuilder = new StringBuilder();

			int nExitCode = 0;
			using ( var p = new Process() )
			{
				p.StartInfo = new ProcessStartInfo( "powershell.exe" )
				{
					Arguments = " -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -Command -",
					// The following line makes the problem go away, even on Win10 14393, unlike the line above
					//Arguments = " -version 2.0 -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -Command -",

					CreateNoWindow = true,
					WindowStyle = ProcessWindowStyle.Hidden,
					UseShellExecute = false,
					RedirectStandardInput = true,
					RedirectStandardOutput = true,
					RedirectStandardError = true,
					Verb = "runas" // Elevate
				};

				p.OutputDataReceived += ( sender, e ) =>
				{
					if ( !String.IsNullOrEmpty( e.Data ) )
						stdOutBuilder.AppendLine( e.Data );
				};
				p.ErrorDataReceived += ( sender, e ) =>
				{
					if ( !String.IsNullOrEmpty( e.Data ) )
						stdErrBuilder.AppendLine( e.Data );
				};

				try
				{
					p.Start();
				}
				catch ( System.ComponentModel.Win32Exception x )
				{
					Console.WriteLine( "Process.Start() threw a Win32Exception:  " + x.Message + Environment.NewLine + x.StackTrace );
					return String.Empty;
				}
				catch ( Exception x )
				{
					Console.WriteLine( "Process.Start() threw an exception:  " + x.Message + Environment.NewLine + x.StackTrace );
					return String.Empty;
				}
				p.BeginOutputReadLine();
				p.BeginErrorReadLine();

				var sw = p.StandardInput;
				sw.WriteLine( strScriptBody );
				sw.Close();

				p.WaitForExit();
				nExitCode = p.ExitCode;
				p.Close();
			}

			string strError = stdErrBuilder.ToString().TrimEnd();
			if ( !String.IsNullOrEmpty( strError ) )
			{
				Console.WriteLine( $"stderr contains the following" + Environment.NewLine + ">>>>>" + Environment.NewLine + strError + Environment.NewLine + "<<<<<" );
				Console.WriteLine( Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine );
			}

			string strOutput = stdOutBuilder.ToString().TrimEnd();
			Console.WriteLine( "stdout contains the following" + Environment.NewLine + ">>>>>" + Environment.NewLine + strOutput + Environment.NewLine + "<<<<<" );

			return String.Empty;
		} // RunScript()
	} // class
}


Here's the expected output on a working machine:

stdout contains the following>>>>>
True<<<<<

...and here's the output on 14393.  Notice the very messed up script body in stdout, at the very end:

stderr contains the following>>>>>
At line:1 char:28+ function GetFunctionValue()+                            ~
Missing function body in function declaration.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordExce
ption+ FullyQualifiedErrorId : MissingFunctionBody

At line:1 char:41
+ function ShowValue( [string] $theValue )+                                         ~
Missing function body in function declaration.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordExce
ption+ FullyQualifiedErrorId : MissingFunctionBody

GetFunctionValue : The term 'GetFunctionValue' 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, ver
ify that the path is correct and try
again.
At line:1 char:12
+ ShowValue( GetFunctionValue )+            ~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: (GetFunctionValue:String) [], Comm
andNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException<<<<<





stdout contains the following
>>>>>
        # This comment is in the GetFunctionValue function
        return $true
        # This comment is in the ShowValue function
        Write-Host $theValue<<<<<


Delete only a portion of an object

$
0
0

I am very new to powershell and trying to get my feet wet. I'm trying to convert specific objects from an .lst file to a .csv. All of the objects I want to convert begin with "Description=" and I would like to omit these words prior to the conversion.

Here is the script thus far:

Get-Content I:\xxxxx\xxxxxxx\Test.lst | Select-Object -Index 42, 46, 50, 58, 230, 414 | Set-Content I:\xxxxx\xxxxxxx\Test.csv

The output I get is an excel file and the lines display:
Description=Adobe
Description=Office2013
Description=Rhapsody
...Etc,etc,etc

I cannot alter the .lst file so need a script to copy portions of that data. The only thing I haven't been able to find is how to omit is the "Description=".

Hope this is clear enough to get some help. let me know if you need anything else.

Viewing all 21975 articles
Browse latest View live