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

How to Export-CSV

$
0
0
This is absolutely doing my head in.
My script is to capture mailbox rules forwards so I need to catch contacts and external email addresses - all fine, managed to cobble a script together and I can see the results in out-file but I cant seem to export-csv.
I know this is something to do with my PSCustomObject but I cant seem to figure it out.

$domains = Get-AcceptedDomain
$orgmailbox=@()
$orgmailbox=Get-Content C:\Temp\MBX.txt
$rules=@()
$Props=@()
foreach ($mailbox in $orgmailbox)
{
$rules = Get-InboxRule -mailbox $mailbox -ErrorAction:SilentlyContinue | where{($_.forwardto -ne $null) -or ($_.redirectto -ne $null) -or ($_.ForwardAsAttachmentTo -ne $null) -or ($_.ForwardTo -match "EX:/") -or ($_.RedirectTo -match "EX:/") -or ($_.ForwardAsAttachmentTo -match "EX:/") -and $domains.DomainName -notcontains $domain}
if ($rules -ne $null) {
$Props += [ordered]@{
User = $($rules.MailboxOwnerId)
RuleName = $($rules.Name)
ForwardTo = $($rules.Forwardto)
RedirectTo = $($rules.RedirectTo)
ForwardAsAttachmentTo = $($rules.ForwardAsAttachmentTo)
}
}
}
$Props | Out-File c:\temp\out.txt
Invoke-Expression c:\temp\out.txt



Thanks, M

Maelito


Invoke-WebRequest returns and error 500 when doing a POST to icinga

$
0
0

I've made a script that will set a scheduled downtime for a host and its triggered children in Icinga 2.
But when I run it I receive

Invoke-WebRequest : The remote server returned an error: (500) Internal Server Error.
At line:31 char:1
+ Invoke-WebRequest -Headers $headers -Uri "$Uri" -Method Post -Body $b ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Even with debug logging enabled on the Icinga 2 server there is not much to go with.
The user logs in properly with the webserver and that's it. Nothing else.

I think the code is pretty OK, but perhaps I've missed something obvious making it not work.
To test it yourself, replace everything starting with "test-" to something in your environment.

Also, the first line has a comment about using the env:computername.
The idea of the script is to run it as a PreUpdateScript with Cluster Aware Updating to schedule downtime for the node when it it's turn to get updated.
A PostUpdateScript will need to be made that removes the downtime.

Further, this is just for the node, eventually I will add the iDRAC (in our case) and Spongebob (our canary VM because Canary and Dodo was already in use).

$hostname = "test-server" # ${env:COMPUTERNAME}.ToLower()

# Start and End time in epoch
$start_time = Get-Date -UFormat %s
$end_time = Get-Date (Get-Date).AddDays(1) -UFormat %s

# Authentication
$user = "test-user"
$pass = "test-password"
$pair = "${user}:${pass}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"

# Stuff to send to the webserver
$Uri = "https://icinga.network.net:5665/v1/actions/schedule-downtime?host=hv-$hostname&type=Host"
$headers = @{ "Authorization" = "$basicAuthValue"; "Accept" = "application/json" }
$body = @{
    author = 'test-user'
    comment = 'Cluster Aware Updating'
    child_options = 2
    start_time = $start_time
    endtime = $end_time
}
$body = $body | ConvertTo-Json

# Ignore self signed certificates
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

# Schedule the downtime
Invoke-WebRequest -Headers $headers -Uri "$Uri" -Method Post -Body $body

# Don't ignore self signed certificates anymore
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null

Excel Compare

$
0
0

Can powershell compare the the diff's between two .csv files, in specific columns, then write the output to a new file, that would contain the data for that entire record/row.

Example: we have two employee files, both contain social numbers for each employee. We would like to compare the files based on that SS# field, and output a file containing the complete record where there are no matching SSN's between the files.  The output would contain the record intact, not just the SSN field.

Returning an object from invoke-sqlcmd

$
0
0

Hi All.

I would like to know if this is the correct way to return a result as an object.

$server = "xxxxxxxxxxxxx"
$username = "xxxxxxxxxxxxxxl"
$pass= Get-Content "yyyyyyyyyyyyyyyyyyy"
$password = ConvertTo-SecureString -String $pass -AsPlainText -Force
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
$session = new-pssession -ComputerName $server -credential $credential -authentication credssp -Name 'DB'
$sb = {  $x = invoke-sqlcmd -Server DBServer -Database master -Query "select newid() as buildguid"

                   [pscustomobject]@{
                   buildguid = $x | select buildguid
                   
                   }

}


invoke-command  -Session $session  -Scriptblock $sb
Remove-PSSession $session 


start-process -verb Printto

$
0
0

Objective: Print adobe files from powershell to a specific network printer (not default printer).

$portname=\\printname\quename
Start-Process $Adobe -filepath $pdf -ArgumentList $arglist -Verb Printto($portname) -PassThru

Thanks


Change the value of bindingRedirect tag

$
0
0

Dear All,

I have the following tag in my web.config file

<runtime><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/><bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/></dependentAssembly><dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/><bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0"/></dependentAssembly></assemblyBinding></runtime>

I want to change bindingRedirect tag of Newtonsoft.Json so it should look like this

<dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/><bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0"/></dependentAssembly>

I tried to do like this

$webConfig = '.\web.config'
[xml]$web =  (Get-Content $webConfig)
$node = $web.SelectSingleNode('//bindings:bindingRedirect')
$node.oldVersion= '0.0.0.0-12.0.0.0'
$node.newVersion= '10.0.0.0'
$web.Save($webConfig)

It gives me error on SelectSingleNode. I think the syntax is not write.

Any help would be greatly appreciated.


powershell - compare active directory and local users group

$
0
0

Greetings,

I am banging my head against wall with super-simple script. The objective is to iterate through domain computers and check, whether regular user is also not a member of local admins group on the domain computer. I came up with this:

I have a test computer where domain user is also local admin, but I still get empty result nevertheless:

$plant = "plant_name"
$users = Get-ADUser -SearchBase "OU=Users,OU=$plant,OU=Plants,DC=company,DC=int" -Filter * | Select-Object -ExpandProperty SID
$computers = Get-ADComputer -Filter {Name -like "*computer1*"} #Get-ADComputer -SearchBase "OU=Computers,OU=$plant,OU=Plants,DC=ronal,DC=int" -Filter *

foreach($comp in $computers) {
    $ladmins = Invoke-Command -ScriptBlock { Get-LocalGroupMember "Administrators" } -ComputerName $comp.DNSHostName
    $sids = $ladmins | Select-Object -ExpandProperty SID
    Compare-Object -ReferenceObject $sids -DifferenceObject $users -ExcludeDifferent
}

I presume $sids and $users are both string arrays and for sure, there is a domain user member of local admin group on the computer.

Any help appreciated. Thank you!


Powershell Gallery Outage

$
0
0

Anyone else experiencing an outage with the PS gallery?

Trying to deploy a PS lambda and can't do so because PS Gallery is down.

Any ETA on it being back up?


Do you want to be acknowledged as Microsoft Windows PowerShell Guru? Submit your work to July 2019 competition!

$
0
0


What is TechNet Guru Competition?

Each month Microsoft TechNet Wiki council organizes a contest of the best articles posted that month. This is your chance to be announced as MICROSOFT TECHNOLOGY GURU OF THE MONTH!

One winner in each category will be selected each month for glory and adoration by the MSDN/TechNet Ninjas and community as a whole. Winners will be announced in dedicated blog post that will be published inMicrosoft Wiki Ninjas blog, a tweet fromMicrosoft Wiki Ninjas Twitter account, links will be published atMicrosoft TNWiki group on Facebook, and other acknowledgement from the community will follow.

Some of our biggest community voices and many MVPs have passed through these halls on their way to fame and fortune.

If you have already made a contribution in the forums or gallery or you published a nice blog, then you can simply convert it into a shared wiki article, reference the original post, and register the article for the TechNet Guru Competition. The articles must be written in July 2019 and must be in English. However, the original blog or forum content can be from beforeJuly 2019.

Come and see who is making waves in all your favorite technologies. Maybe it will be you!


Who can join the Competition?

Anyone who has basic knowledge and the desire to share the knowledge is welcome. Articles can appeal to beginners or discusse advanced topics. All you have to do is to add your article to TechNet Wiki from your own specialty category.


How can you win?

  1. Please copy/Write over your Microsoft technical solutions and revelations to TechNetWiki.
  2. Add a link to your new article on THIS WIKI COMPETITION PAGE (so we know you've contributed)
  3. (Optional but Recommended) Add a link to your article at the TechNetWiki group on Facebook to get feedback and tips from the council members and from the community. The group is very active and people love to help. You can even get direct improvements to your article before the contest starts.

Do you have any question or want more information?

Feel free to ask any questions below, or Join us at the official MicrosoftTechNet Wiki groups on facebook. Read More about TechNet Guru Awards.

If you win, people will sing your praises online and your name will be raised as Guru of the Month.

PS: Above top banner came from James van den Berg.


JAYENDRAN ARUMUGAM

HELP!! Newbie is stuck

$
0
0

Hi guys,

I've googled this as much as i can handle and without going cap in hand to the resident powershell gurus (who are insanely busy), i need help please.

We have setup many groups (900+) with the group scope of Domain Local, instead of Global. I know we can powershell them into universal groups, then into global groups, but i would like to pull all the groups into a .CSV and then run the command to convert from there.

How do i get a list of all groups with a specific naming convention, that have a specific Group scope out into the CSV?

e.g - GL_
        Domain local

Thanks


Delegate Rights to Add Computer Objects to a OU for one User with Powershell

$
0
0

Hi,

I would like to delegate this complex rights via Powershell.

The OU Name is OU=RDSH,OU=Clients,DC=XXX,DC=dom

The Username: svc_vm_join_ad

Access Right:

Reset password applied to Descendant computer objects

Read/write all properties applied to Descendant computer objects

I hope this description is ok.

I have write this part but I don't know that I must write for the user permission:

Import-Module ActiveDirectory
$rootdse = Get-ADRootDSE
$domain = Get-ADDomain

$guidmap = @{ }
Get-ADOject -SearchBase ($rootdse.SchemaNamingContext) -LDAPFilter '0(schemaidguid=*)' -Properties lDAPDisplayName, schemaIDGUID |
	ForEach-Object{
		$guidmap[$_.lDAPDisplayName] = [System.GUID]$_.schemaIDGUID
	}

$ou = Get-ADOrganizationalUnit -Identity 'OU=RDSH,OU=Clients,DC=XXX,DC=dom' -Server XXX-dc01.XXX.dom
$oupath="AD:\$($ou.DistinguishedName)"
$sid=(Get-ADGroup "RDSH").SID
$p = New-Object System.Security.Principal.SecurityIdentifier($sid)
$acl = Get-ACL $oupath
$ace=New-Object System.DirectoryServices.ActiveDirectoryAccessRule($p, 'WriteProperty,WriteDacl', 'Deny', 'Descendents', $guidmap['user'])
$acl.AddAccessRule($ace)
$acl|Set-ACL $oupath

Meaning of powershell script script that uses $variable.Id

$
0
0

I am new to Powershell and Azure and I am trying to understand the scripts I have been written. The scripts are pretty standard in that they build up the contents of variables and then execute them SO to understand what is happening I am trying to recreate  what the command line will look like at the bottom of thre script

New-AzureRMVM -VM $MyVM -ResourceGroupName $rg -Location $region

Working back up the scripts and replacing the variables with their contents.

for example:

$vNic = New-AzureRmNetworkInterface -Name $nicName -ResourceGroupName $rg -Location $region -Subnet $subnet

the vNic variable is later seen here:

$MyVM = Add-AzureRmVMNetworkInterface -VM $MyVM -Id $vNic.Id

What purpose is the .Id suffix? I have seen it elsewhere.

Also is there a way to run a powershell script in debug mode to see the resolve variables bit not execute

No such interface supported

$
0
0

Hi All,

When I am running a below powershell command I am getting an error message as "No such interface supported";

gwmi win32_operatingsystem -ComputerName "hostname"

I am able to access target host through RDC from the source host. I can telnet the host and its listening on 135. All windows firewalls are disabled. Trying with Admin account. 

Any idea how to get rid of this error?

Getting SQL version info from list of server names

$
0
0

I am wondering if there is a powershell script I can run against a .txt file with server names in it that will return the version of SQL on that list of servers. Any help is appreciated.

Thanks.


Chad Guiney

Restore-SqlDatabase fails when specifying -Credential

$
0
0

Hi

Im getting an error when running the below PowerShell. I need to run as a specific user, any ideas? I have tried replacing localhost for the server name but still no luck. The error i get is:

Restore-SqlDatabase : Failed to connect to server localhost.

$password = ConvertTo-SecureString '*********' -AsPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential ('testadmin', $password)

#Relocate the Database file

$RelocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("DB_training", "S:\Data\Testing.mdf")

#Relocate the Log file

$RelocateLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("DB_training_Log", "L:\Log\Testing.ldf")

#Restore the template database

Restore-SqlDatabase -ServerInstance "localhost" -Database "Testing" -Credential $cred -BackupFile "C:\Template\backup_V7_201810011430.bak" -RelocateFile @($RelocateData,$RelocateLog)

Thanks

Shane



set msExchUserAccountControl to 2 - based on a query of disabled users in AD

$
0
0

I have a problem that even though user account are disabled in AD, the msExchUserAccountControl value is not automatically set to 2-  Can anyone help me with a powershell query that will update the value of that attribute to 2 based on disabled accounts in AD?

I saw the article with this command:  Set-ADUser -Identity"<user name or DN>" -Replace @{msExchUserAccountControl="0"}

But we have thousands of accounts.  I want to filter <username or DN> with all disabled users.

Thanks!

Help with a command?

$
0
0

I get a .csv file export from my security office that has a list of computer host names in column A, and a list of applications that require my attention (Updates usually). 

I'd like a powershell command to look at the CSV file column A, then take those computer names and provide me a new .CSV file that shows the computer names along with the computer description, computer name and last login.

I have the following, but I know it's wrong. What I think it's doing is ignoring my CSV file and running the command against every PC in the domain....

Import-Csv -Path C:\Script\CName.csv | Get-ADComputer -Filter * -Properties *  | Sort LastLogonDate | FT Name, LastLogonDate -Autosize | Out-File C:\script\Export.csv

Script to remove System Center Agent

$
0
0

I have this script to remove the system center agent, but the Next options pop up as if I am manually removing the agent by choosing Change instead of Uninstall. I tried using the quiet option but that did not work.  How can I write the script so that it actually uninstalls with no popups as if I am changing the agent?

$SysCtr2007=Get-ChildItem-PathHKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall|`   

Get-ItemProperty| Where{$_.DisplayName-match"System Center Operations Manager 2007 R2 Agent"}

ForEach

( $verin$SysCtr2007) {  

If($ver.UninstallString ) {     

$uninst=$ver.UninstallString       

Start-Processcmd-ArgumentList"/c$uninst/quiet /qn "


    }

}

Use PowerShell to terminate user in AD

$
0
0

Hello Every One. 

we receive a sheet daily basis with employee status, from a HR tool workday. 

there is a column "employee status" the values are - Active, In Leave, Terminated.

I am trying to run a script which will see which all users has an employee state Terminated and export them to a different excel sheet / csv file. 

Can someone please help.

Regards

Sugata

Add another group with the same ACL

$
0
0

Hi i would like to know how to do the following :

i have some security groups and a fileserver.
Now i want to check NTFS permissions and add a second group that has the same ACL as an existing one.

So if a group "GG_FDR_test" has modify this folder only rights 
then i want to add a group "Remote_GG_FDR_test" that has modify this folder only rights

every group that starts with "GG_FDR_" als has an group that has the same name but starts with "Remote_GG_FDR_"


Get all Folderpermission 3 levels deep for groups that start with "GG_FDR_*"
for every group it finds copy ACL 
Add second group "Remote_GG_FDR_*" and set same ACL on this folder.

sorry for the lack of info but i dont know how to start with this.

Viewing all 21975 articles
Browse latest View live