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

PowerShell scripts in Visual Studio

$
0
0

Hello, 

I'm getting started with PowerShell scripting and i was wondering if powershell script can be assigned to a visual studio button to do its function. 

If so can someone please give me some examples or point me in the right direction? 

Thanks in advance

GeekzInside.


A String or not a String..... | MOC 10961B LABA from Module 10

$
0
0

Hi,

I'm a MCT and giving Powershell Classes. I'm teaching the Course 10961 for a while now, but I never figured something out, occuring in the LAB from Module 10 (Putting it all together):

in the Lab you get the "Old Ipaddress" via get-DHCPv4ServerLease and the MACAddress of that Server Core instance.

$OldIPaddress = get-DHCPv4Serverlease -Computername LON-DC1 -ScopeID 10.0.0.0 | where-object {$_.ClientID -eq "WA-TH-EV-ER-00"} | select -expandproperty IPAddress | select -expandproperty IPAddressToString


as a result you get the IP adress saved in the Variable $OldIPAddress.... if you pipe it in get-member you see its a [System.String]

but nonetheless, you have to "place the $OLDIpaddress variable in double quotationmarks, and assign the resulting string to $OLDIpaddress. This will convert the IP Address to a string Object" (Page 10-9 from the offical MOC Course-Book, Exercise 2, Task2, step number 10)

Alright it works... but I don't get why you need to do this.... because it is already a string!

If you do not do this, Setting the trustedHostsList will fail with [i]"cannot convert System.Object[] to System.String"[/i] even though get-Member (or the method gettype()) says that it IS ALREADY a System.String...

Set-Item WSMAN:\localhost\Client\TrustedHosts -Value $OldIPaddress

That really bothers me and I cannot explain this to my Students....

Can anyone help me?

Sorry for bad english... I'm German ;)

ADFS 2.0 No PowerShell SnapIn

$
0
0

Hello,

I installed the ADFS 2.0 server on a Windows 2008 R2 Enterprise server, and did all the updates. When I try to use the PowerShell SnapIn to do some commands I have this error :

PS> Add-PSSnapin Microsoft.Adfs.PowerShell

Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 2.0

At line:1 char:12

...

I installed and reinstalled ADFS 2.0 a lot of times, tried to follow a lot of work-around (e.g : Paresh's blog, doesn't work at the moment) and I have still the same problem. Maybe I forgot an important thing to do ?

When I type :

PS > get-module -listavailable

The ADFS module is not listed. Do you know how can I install these Adfs PowerShell modules ?

Thank you.

Powershell script to print right triangle with "*"

$
0
0

Hi, I am very new to this scripting thing. I want to print something like below,

*

**

***

****

For this I have written this code,

Clear-Host
for( $i = 1; $i -le 4; $i++)
{
  for( $j = 1; $j -le $i; $j++)
  {
     write-host "* "
  }
}

But not getting the desired output. please help me in finding the error and the correction for the same.

Thanks in advance.

Home Folder Permissions

$
0
0

Hi

I have the below script which works great, accept setting permissions on the home folder. Can anyone help with the exception at the end?

import-Csv .\users.csv | foreach-object {$userprinicpalname = $_.SamAccountName + "@castlemanor.local"

Import-Module ActiveDirectory

# Creates a new staff user in Active Directory

New-ADUser -SamAccountName $_.SamAccountName -UserPrincipalName $userprinicpalname -Name $_.name -DisplayName $_.name -GivenName $_.cn -SurName $_.sn -Department $_.Department -Company $_.Company -Homedrive $_.HomeDrive -HomeDirectory $_.HomeDirectory -Path"OU=Staff,OU=CL10,DC=castlemanor,DC=local" -AccountPassword (ConvertTo-SecureString "Microsoft~1;" -AsPlainText -force) -Enabled $True -ChangePasswordAtLogon $True -PassThru


# Adds the memeber to the Staff security group

Add-ADGroupMember "Staff" $_."SamAccountname";

# Sets the users home directory

Set-ADUser $_.SamAccountName -HomeDirectory $_.HomeDirectory -HomeDrive u;

# Creates the users home folder on the file server and build access rule to set permissions

New-Item -path $_.HomeDirectory -type directory -force
$Domain='castlemanor'
$acl = Get-Acl $_.HomeDirectory
$permission = "$_.SamAccountName","FullControl","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
$acl | Set-Acl $_.HomeDirectory
}

This is the exception I get:

Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity
references could not be translated."
At C:\Scriptfinalv1.2 - Restored.ps1:25 char:1
+ $acl.SetAccessRule($accessRule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : IdentityNotMappedException

Thanks for any advice in advance

Shane 

memberof value

$
0
0
Hi 

I am exporting attribute of users whch in in users.csv file

But while exporting Memberof value, its showing with full distinguieshed name in Horizontal form.

I need to be only group name and it should be vertical form.

Please advise or suggest to get this data

Import-Csv .\users.csv | % {Get-ADUser $_.name -server "contoso.com" -Properties * | select name,samaccountname,lastlogondate,modified,created,mail,PasswordLastSet,@{n="memberof";e={$_.memberof -join ";"}}}

script issue,Java install from script, push out to servers.

$
0
0

this is a non standard install for Java that has to be installed from a script.  basically this script will run against a given amount of servers, stop the required services ( pertains to the application that requires Java on the server), uninstall java, install java, configure java with correct parameters and security permissions then lastly output a log file to the server that is running the script (folder) of each server .  each server will have thier own text file.   so two issues first java uninstalls but does not install due to a permissions error, and the other  issue that is occuring is there should be a log file for each server the log file will have the server name as the file namey, the script will look at the server list and run the code on that server so basically the script will run at the same time on all the servers, and create log file for each server and put in the folder i designate.  - this is not occuring based on the Powershell script below. what parameter is missing below. thanks

$user = Read-Host 'Username:'
$pass = Read-Host 'Password:'
$result = "D:\Temp\" + $env:COMPUTERNAME +"_JavaUpdate.log"
$copyfinal = "\\wsive005pap\d$\BatchFiles\Java_Update\"

#Stop NCSB and Tomcat Services
Stop-Service Tomcat7
Stop-Service "NuanceCSB"

#Uninstall Java
Get-WmiObject -Class win32_product | ? {$_.Vendor -like "*Oracle*"} | % {msiexec /x "$($_.IdentifyingNumber)" /qn | Out-Null}
Start-Sleep -s 120
"Java 7 Uninstalled" | Out-File $result -append

#Install Java
$JRE = "D:\Installations\NVP 4.0 Install\jre-7u76-windows-i586.exe"

& $JRE /s INSTALLDIR=D:\Apps\Progra~1\Java\jre7\ /l D:\Temp\javainstall.log | Out-Null
Start-Sleep -s 240
"Java 7 Installed" | Out-File $result -append

#Configure Java
$pattern = "security.provider.10=sun.security.mscapi.SunMSCAPI"
$javasec = "D:\APPS\Program Files (x86)\Java\jre7\lib\security\java.security"
$viecore = "security.provider.11=cryptix.provider.Cryptix"

(Get-Content $javasec) |
    Foreach-Object{
        if($_ -match $pattern)
        {
            $_ 
            $viecore
        } else {
            $_ 
        }    
     } | Set-Content $javasec
"Java Configured" | Out-File $result -append

#Start NCSB and Tomcat Services
Start-Service Tomcat7
Start-Service "NuanceCSB"

#Updating log files and push to the central server
$javaver = gci "D:\APPS\Program Files (x86)\Java\jre7\bin\java.exe"
$tomcatver = "D:\APPS\Program Files (x86)\Apache Software Foundation\Tomcat 7.0_Tomcat7\lib\catalina.jar"

"*****Check Java and Tomcat Version*****" | Out-File $result -append
& $javaver -cp $tomcatver org.apache.catalina.util.ServerInfo | Out-File $result -append
"*****Check Services Started*****" | Out-File $result -append
Get-Service | Where-Object {$_.Name -eq "NuanceCSB"} | Out-File $result -append
Get-Service | Where-Object {$_.Name -eq "Tomcat7"} | Out-File $result -append
"*****Check Java Security File*****" | Out-File $result -append
Select-String -Path $javasec -Pattern "cryptix" | Out-File $result -append
"*****Print log file for CTI connections*****" | Out-File $result -append
Get-Content "D:\APPS\NuanceCSB\logs\stdout.log" | Out-File $result -append
"*****Print log file for connector*****" | Out-File $result -append
Get-Content "D:\APPS\NuanceCSB\logs\CSB.log" | Out-File $result -append


NET USE \\wsive005pap\d$ $pass /user:CORP\$user
Copy-Item $result $copyfinal
NET USE \\wsive005pap\d$ /delete



how check Powershell Version ?

$
0
0

Hi...all

I installed SQL Server 2008 Dev edition on XP sp3.(It Installs WPS)

I am very much new to PS..I started testing my Installation.

For example, I typed Get-PS and press the Tab key , 
the following cmdlets are appearing

Get-PSDrive
Get-PSProvider
Get-PSSnapin

But It suppose to show below list 

❑ Get-PSBreakpoint
❑ Get-PSCallStack
❑ Get-PSDrive
❑ Get-PSProvider
❑ Get-PSSession
❑ Get-PSSessionConfiguration
❑ Get-PSSnapin

Why some other cmdlets are missing...Help me how to resolve and how check the Present version of WPS.

Thanks in Advance




SNIVAS

Activate Outlook Anywhere with Powershell

$
0
0

Hello there,

i'm creating a Powershell script to startup the Exchange Management Shell and Activate Outlook Anywhere for a list of users. The script excist in two lines..

Line 1 to startup the Exchange Management Shell

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -version 2.0 -noexit -command ". 'D:\Programs\Microsoft\Exchange Server\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto";

and line 2 to active Outlook anywhere

Get-Content ./OutlookAnywhere.txt|foreach { Get-mailbox –identity $_ | set-casmailbox –mapiblockoutlookrpchttp:$false }

The script is working for 50%. He is starting up the Exchange Management shell but he is not executing the second line to activate Oulook anywhere.

Can you people see what I'm doing wrong?

Thanks.

Add member from specific group to another group as well

$
0
0

Hi,

I would like to add all members from specific groups ( with a naming pattern) to another group in AD.

So, I have parent groups like group1ABC , group2ABC,group3ABC ...etc ; inside these groups there are multiple groups with random names and loads of users.

I would like to find all the users belonging to these parent groups and add them to another group without removing them from these parent groups.

I'm trying with powershell script without success:

Import-Module ActiveDirectory
$fromgroup = Get-ADGroup -Filter {name -like "*ABC"}
$togroup = Get-ADGroup "specialgroup"

foreach ($member in Get-ADGroupMember $fromgroup)
{
    Add-ADGroupMember -Identity $togroup -Members $member
}

Can you help?

thx

Loop Question

$
0
0

Hello,

I have a powershell script, where I start a Special .exe file, mage.exe with start-process.

Now i have the Problem, that this script part should wait until the process is finished, but it did not.

The script wait not until the mage.exe tool is finished.

My idea is now, to check every then secounds, if the process mage is running, if is running, the powershell script should wait.

If the mage.exe is finished and the process doesn't exist in porcess, the script should go on.

How can I do this?

cls
$processvalue = get-process mage*
$processvalue
if (!$processvalue)
{Write-Host "Null"}
else
{Write-Host "Yes"}

I hope somebody can help me

Horst

$MageexeTool-ArgumentList$Params-LoadUserProfile-Credential$Cred-Wait


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

need help using -Filter with Get-ADUser in Powershell Script

$
0
0

I am trying to write a powershell script that finds a matched account in AD with the list of users from SharePoint site collection.  Here is a script (incomplete) that I am having an issue with.

Import-Module activedirectory
$WebApp = Get-SPWebApplication https://xxx.com
$site = get-spsite -WebApplication $WebApp
ForEach ($i in $site)
{
    $SID = get-SPUser -web $i.url | select sid
    ForEach ($i in $SID)
    {
       $acc = Get-ADUser -Filter {SID -eq $i}
        #Write-Host $acc
        #If ($acc -eq $Null) { Write-Host "User $i deos not exist in AD" }
        #Else { Write-Host "User $i found in AD" but $acc.enabled status.}
    }
}

Get-ADUser : Invalid type 'System.Management.Automation.PSCustomObject'.
Parameter name: objectSid
At F:\Temp\Apple\RemoveOrphanedUser\OrphanedUser-temp2.ps1:9 char:25
+        $acc = Get-ADUser <<<<  -Filter {SID -eq $i}
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : Invalid type 'System.Management.Automation.PSCustomObject'.
Parameter name: objectSid,Microsoft.ActiveDirectory.Management.Commands.GetADUser

When i ran this script, I get an error.  However, if run "Get-ADUser -Filter {SID -eq x-xx-xx-xxxx}instead of using a parameter, it works.  I tried a different filter term "DisplayName", but the same result.  So i don't know what needs to be fixed in the script in order to find matched AD account.

Thanks in advance.

dos command x86 vs x64

$
0
0

I am trying to out info using the netsh command as follows

$showready = netsh mbn show ready *

this works fine if I run it in the x64 powershell. However if I run it in powershell (x86) i get the output "The following command was not found: mbn show ready *." why is it cutting off the netsh?   I am trying to execute the script through sccm so I figured it would run the x64 powershell since both sccm and the target os are 64bit. When I look at the logs I see this.

Running "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NonInteractive -ExecutionPolicy Bypass "C:\WINDOWS\ccmcache\26\Untitled1.ps1" with 32bitLauncher

why does it run 32bit? and can I force it to run 64bit? better yet why do I get different output between the two? is there a way to get the correct output with the 32bit powershell?

thanks


Shaun

Appending a csv column exported from Active Directory

$
0
0

Hi Guys

We have a new access control system. The DB of the control system needs to be updated with new people from Active Directory. It has an import tool to this. I want to automate it to do it every hour. So I started writing a powershell script to export any users that have changed in the last day. Here is what I have so far:

Get-ADUser -Filter * -Properties * | Where {$_.Modified -ge $(Get-Date).AddDays(-1)} | select rcscardcode | Export-Csv -path C:\Users\johncolfer\Desktop\TempStuff\Active-dir\export12.csv

So as you can see I have selected a property "rcscardcode". It is a custom attribute in AD. An example of 1 of these numbers in the exported csv file is "1141410511000000" I need to be able to change this number to "1141410511" and all subsequent numbers in that column of the csv file. Is this possible? 

Any help would be great.

Thanks

John

Outlook - Mark All As Read

$
0
0

How does one mark all emails (folders and subfolders) as read in an Outlook mailbox?

I tried this code:

$MyFolders = $outlook.Application.GetNamespace("MAPI").Folders.item("").folders.item("Inbox").Folders

ForEach ($MyFolder in $MyFolders) { ForEach ($Item in $MyFolder.Items.Restrict("[unread] = true")) { $Item.UnRead = $false } }


But it errors with the following:

You cannot call a method on a null-valued expression.
At C:\Users\blashmet\Desktop\Read.ps1:1 char:47
+ $MyFolders = $outlook.Application.GetNamespace <<<< ("MAPI").Folders.item("1_
Employees").folders.item("5_Misc").Folders
    + CategoryInfo          : InvalidOperation: (GetNamespace:String) [], Runt
   imeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\Users\blashmet\Desktop\Read.ps1:3 char:79
+ ForEach ($MyFolder in $MyFolders) { ForEach ($Item in $MyFolder.Items.Restric
t <<<< ("[unread] = true")) { $Item.UnRead = $false } }
    + CategoryInfo          : InvalidOperation: (Restrict:String) [], RuntimeE
   xception
    + FullyQualifiedErrorId : InvokeMethodOnNull

I've tried different combinations of arguments for Folders.item and folders.item. Note that I've renamed my Inbox to "5_Misc".




Fetch client IP addresses from the Netlogon.log file of all domain controllers in the domain

$
0
0

Hi,

The event ID 5807 is logged in the system logs of domain controllers as a result of which the IP addresses for the missing subnets are logged in Netlogon.log under %systemroot%/debug. The end goal is to fetch the IP addresses along with rest of the respective attributes from the Netlogon.log for all the domain controllers in the domain. I have the following script however, it gives me a 0KB file despite the fact that the Netlogon.log on the DC contains ample entries from last two months. 

function GetDomainControllers {
    $DCs=[system.directoryservices.activedirectory.domain]::GetCurrentDomain() | ForEach-Object {$_.DomainControllers} | ForEach-Object {$_.Name}
    return $DCs

}

function GetNetLogonFile ($server) {
    $path= '\\' + $server + '\c$\windows\debug\netlogon.log'
    try {$netlogon=get-content -Path $path -ErrorAction stop}
    catch { "Can't open $path"}
    #reverse the array's order to the end of the file
    [array]::Reverse($netlogon)
    $IPs=@()
    foreach ($line in $netlogon) {
        #split the line into pieces using a space as the delimiter
        $splitline=$line.split(' ')
        #Get the date stamp which is in the mm/dd format
        $logdate=$splitline[0]
        #split the date
        $logdatesplit=($logdate.split('/'))
        [int]$logmonth=$logdatesplit[0]
#last month and this month
        if (($logmonth -eq $thismonth) -or ($logmonth -eq $lastmonth)) {
            #only push it into an array if it matches an IP address format
            if ($splitline[5] -match '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'){
                $objuser = new-object system.object
                $objuser | add-member -type NoteProperty -name IPaddress -value $splitline[5]
                $objuser | add-member -type NoteProperty -name Computername -value $splitline[4]
                $objuser | add-member -type NoteProperty -name Server -value $server
                $objuser | add-member -type NoteProperty -name Date -value $splitline[0]
                $objuser | add-member -type NoteProperty -name Time -value $splitline[1]
                $IPs+=$objuser
            }
        } else {
            #break out of loop if the date is not this month or last month
            break
        }
    }
    return $IPs
}

#Get last month's date
$thismonth=(get-date).month
$lastmonth=((get-date).addmonths(-1)).month

#get all the domain controllers
$DomainControllers=GetDomainControllers
#Get the Netlogon.log from each DC
Foreach ($DomainController in $DomainControllers) {
    $IPsFromDC=GetNetLogonFile($DomainController)
    $allIPs+=$IPsFromDC
}

$allIPs | Sort-Object -Property IPaddress -Unique | Export-Csv "E:\bin\NetlogonIPs.csv"

PLEASE HELP!!

WSUS Computer Count not Adding Up

$
0
0

I have generated some WSUS reports using PowerShell and for some reason the number of computer targets I am receiving does not match what's in the Update Services administrative console.

When I select the "All Computer" node in the Update Services console I am told there are2219 computers total. When I run the following PowerShell code my output is1839.

Any idea why this is happening?

$ComputerName = 'localhost'
$UseSSL = $False
$Port = 8530
$TargetGroup = 'All Computers'

[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | out-null
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer($ComputerName,$UseSSL,$Port)

$UpdateScope = New-Object Microsoft.UpdateServices.Administration.UpdateScope

$ComputerTargetGroupId = $wsus.GetComputerTargetGroups() | Where {$_.Name -eq $TargetGroup} | Select-Object -ExpandProperty Id
$ComputerTargetGroup = $wsus.GetComputerTargetGroup(”$ComputerTargetGroupID")
$ComputerTargets = ($ComputerTargetGroup).GetComputerTargets()

$ComputerTargets.Count

How to find what is the current windows update setting via powershell.

$
0
0

Hi All,

I have a task where i need to check on machines what is the current Windows automatic update setting on the Windows server machines.

I used get-windowsupdateconfig as mentioned in various blogs but it did not work.

Is there any possibility that powershell can do this?


Gautam.75801


Query DNS for srv records

$
0
0

Hi,

Is there a way that PowerShell can query a DNS server for srv records for a domain? Bear in mind, I'm using version 4 of PowerShell on Windows 2008 r2, not the Windows 2012 version, so there is no "get-DNSResourceRecord" cmdlet available. I've thought about using the "Invoke-Command" cmdlet with nslookup, but I don't even know where to start with that.

Any assistance would be appreciated.

Thanks.


how to show result with > 4 columm

$
0
0

I using this to show result     

$result += [PSCustomObject]@{  
        ServerName = "$computername"
        CPULoad = "$($AVGProc.Average)%" 
        MemLoad = "$($OS.MemoryUsage)%" 
        CDrive = "$($vol.'C PercentFree')%"
    }

i need result with 5 columms, but when i add more line to code, result format change to list, how to keep format on table

thank u

Viewing all 21975 articles
Browse latest View live


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