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

find user by extensionAttribute2 and add to a group

$
0
0

I have a CSV with users' extensionAttribute2 values. I want to locate each user, and then add that user to a specific group (all are going to the same group). I don't have a problem finding by extensionAttribute2, but how do I retrieve a userPrincipalName for each specific user and then add that user to the group I specify? Thanks.

Ron Proschan


Ron Proschan


powershell filtering data

$
0
0

I am merging two of my family's video collections. both are two big to go through by hand. I have manged to  get a text file with the movies that need to be imported into the main folder but the file has a lot of information in it that needs to go. what I am trying to write is a program that will grab just the file names out of the text file and then I can come up with another script  to import though movies in one go. The way the txt file is I need a script to take information from between a : and .mp4 file extension. 

NOTE: there is a space between the : and the filename

Get-ChildItem C:\Users\AgentN\Desktop\simplemovielist.txt|Where-Object {$_.name -like "*.mp4"}|format-list|Out-File -filePath C:\Users\AgentN\Desktop\Movienames.txt

simplemovielist.txt is the file with the names and other file information in it

movienames.txt is where I was trying to put just he movies names

I would be very grateful is someone could help me

Check for SQL then acquire version

$
0
0

We have around 250 virtual servers in our VM environment and I need to determine which of these servers are running SQL, then I need to determine the version on those that are. I'm having difficulty in finding anything on just how to determine if the box has it.

I did find a snippet about determining version, but I need a query of some type to determine if it is even there.


# When I wrote this script only God & I knew what I was doing.

# Now, only God Knows!

New powershell guy. I can't figure out what Im doing wrong with this script.

$
0
0

As the title says Im new to power shell and can't seem to find the right way to write this script. 

My Goal - Search a specific OU for all computers running windows 7 and windows xp (two different scripts) and then move those findings to a different OU. 

Get-ADComputer -filter 'operatingsystem -eq "Windows 7 pro" -searchbase 'ou=test,dc=blank,dc=com

I would then expect to | with move said computers to new OU. Any help in the structure of this script would be a huge help.

Thanks


Powershell to query all DiskControllers and its associated diskdrives

$
0
0

We have a requirement to get diskcontrollers(SCSI or IDE or other) and its associated diskdrives using WMI and Powershell. Have seen the documentation of WIN32_SCSIController ,Win32_IDEController and WIN32_DiskDrive. Can somebody advise how to connect/relate the information between controller class and driveinfo class using powershell.

thanks in advance


c

Send Update records to file

$
0
0

I have a question.  How do I send an output update records to log or file in powershell.  The script work.  I need help on how to send only update records to a file.  Thank you

$objTable | Export-Csv c:\scripts\carddata.csv

Import-Module ActiveDirectory
ForEach ($User in $objTable)
{
   $OUDomain = "OU=ABC,DC=KA,DC=Com"
   $Last = $User.LastName
   $First = $User.FirstName
   $Badge = $User.SSNO
   $Result = Get-ADUser -Filter '(Surname -eq $Last) -and (GivenName -eq $First)' -SearchBase $OUDomain -Properties employeeID,givenname,sn,extensionattribute5 | ForEach {If ($Badge -ne $_.extensionAttribute5)
     {$_ | Set-ADObject -Replace @{extensionAttribute5=$Badge}
  }
    }
}

How do you access values from a checkbox or textbox from powershell code

$
0
0

Hi,

I can build a form with buttons on it, but I am not sure how to capture the values on clicking a button. I want to write some logic code to do things depending on which checkboxes are checked. How can this be achieved?

Thanks.

Modify Registry values on multiple workstations

$
0
0

Hope someone can help me out with my PowerShell code.

I have a list of Workstations that I need to update with two registry keys for each machine. Each key is unique (the value is different) per workstation. I have input csv input file with the following: ComputerName , AcctName, AcctPwd.

My code below will update the only one workstation and will not move to the next and the values for  $newPwd = $autoComp.AcctPwd and $compName = $autoComp.compName are not being passed.

Thanks,

$cred = Get-Credential 'Domain\UserID'

$autoComps = Import-Csv -Path c:\Scripts\AutoLogon\autoLogon.csv | select CompName, AcctName, AcctPwd
 ForEach ($autoComp in @($autoComps))
 {
 $newName = $autoComp.AcctName
 $newPwd = $autoComp.AcctPwd
 $compName = $autoComp.compName
Invoke-Command -ComputerName $compName -cred $cred -ScriptBlock {
$Comps = Import-Csv -Path c:\temp\autologon.csv | select AcctName, AcctPwd
ForEach ($Comp in @($Comps))
 {
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" -Name "DefaultUsername" -Value $newName
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" -Name "DefaultPassword" -Value $newPwd
Write-Output $newName
}}

}





Isaac Oben MCITP:EA, MCSE,MCC <a href="https://www.mcpvirtualbusinesscard.com/VBCServer/4a046848-4b33-4a28-b254-e5b01e29693e/interactivecard"> View my MCP Certifications</a>


Files/folders enumeration

$
0
0

I can use the following to enumerate every file and folder. How to bypass some folders (not enumerating their children) if their names ended with 4-digit number (e.g. foler1111, folder 2222)?

Get-ChildItem -rec | ForEach-Object -Process {$_.FullName}

How To Get Deleted Item Count and Associated Item Count And LastLogOn and LogOff Time For A Mailbox In Exchange Using EWS

$
0
0

Using Powershell cmdlet i get  all the details..But i want to get these Details by using EWS Managed Api.Is It Possible to do???

Powershell Cmdlet,

Get-MailboxStatistics -Identity Username, Using this cmdlets all the details will get displayed.

DeletedItemCount:5 //Here how this count comes.In My OutlookWebApp the deleteditems folder contains 13 items in it..But the count shows only 5.

TotalDeletedItemSize:5.465 Kb//Even this value too does not match with DeletedItems Folder size in owa.

AssociatedItemCount:12

LastLogOnTime:11/11/11 12:43PM

LastLogOff Time:11/11/11 2:43PM

In EWS,

By Looping through all folders i can get the total item count and total item size.Even i can get deleteditems  count .But that value does not match  With the powershell value.Even the TotalDeletedItemSize Doesnt match.

Using EWS Managed Api ,Looping through folders i can get ItemCount,TotalitemSize,(DeletedItems,TotalDeleteditemSize(These TwoValues Does not match with values comes from powershell))

Now how to get the Associated item count and lastlogoff and logon time using EWS managed Api.Is it Possible???

And even y the deleteditems count and size values varies between EWS and powershell.

Extract date

$
0
0

Hi,

I wish to extract the date from a file name and I didn't find a way to do it because the length of the file is variable.

Here is the file name : 1040#FIDI#FIDI-+-E-BILLING#20140311#151445#92798379#5135475.txt

The only constant thing is that the date is always between the 3rd and 4th "#".

Can you help me ?

Best regards

GenePatton

Select file with operator sign in name

$
0
0

Hi,

I Have a little problem with my powershell and it's driving me crazy. The goal of the script is to move file base on a filter.

The name file : 4456#FIDI#FIDI-+-ASSURANCE#20140407#093415#71545176#5266875.wav

The filter : #FIDI#FIDI-+-ASSURANCE#

Here is my code :

$directory_origine8 = "R:\RECORDS_ALL\OLD_RECORDS\other records\ALL_FIDI"
$directory_destination8 = "R:\RECORDS_ALL\FIDI\Assurance"
$filter8 = "#FIDI#FIDI"-+-"ASSURANCE#"
$filter8
foreach ($file8 in (Get-ChildItem -Path $directory_origine8 -Recurse | Where-Object { $_.Name -match $filter8} ))
{
    $filter8
    $fichier = $file8.Name
    $fichier
    $path_fichier = $file8.fullname
    $path_fichier
}

At the end of the execution I get "#FIDI#FIDI"-+-"ASSURANCE#" which is line 4. I have plenty of files matching the filter.

Can you help me ?

best regards

GenePatton

Automatically turn off display for a short period of time to protect Eyes

$
0
0

Hi,

I have very little idea about what Powershell is so please ignore this if my question is irrelevant. 

I want my laptop screen to turn off or turn black for let's say 10 seconds every 10 minutes. I want to be able to run this code at Startup and be able to disable it easily.

I have a software to do that but I hate to install too many programs unless if they are portable.

Thanks in advance :)


Exception calling "GetSmoObject" with "1" argument(s):"Attempt to retrieve data for object failed for ManagedComputer 'txdsepsn123'."

$
0
0

Hi,

  I am using below powershell script to  disable Shared Memory Protocol 'SM' in Sql Server

Import-Module"sqlps"-DisableNamechecking


 


######################################################

# Function to Enable or Disable a SQL Server Network Protocol

#

#

###############################

function ChangeSQLProtocolStatus($protocol,$enable){

try


{

[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement")

}

catch{throw"Exception occurred when we refer smo and SqlWmiManagement assembly, and its $_.Exception"}

   

try


{

 


   

 

   

Write-Host"Initialize WMI object"


$wmi=new-object('Microsoft.SqlServer.Management.Smo.WMI.ManagedComputer')

Write-Host"Generation URI"


$uri = "ManagedComputer[@Name='" + (get-item env:\computername).Value + "']/ServerInstance[@Name='MSSQLSERVER']/ServerProtocol"


   

 


   

   

Write-Host"Creating protocol settings"


 $prtocolSettings = $wmi.getsmoobject($uri + "[@Name='$protocol']")

Write-Host"Created Protocol smo  object"


   

$prtocolSettings.IsEnabled=$enable    

   

$prtocolSettings.Alter() 

try


{



[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement")

Get-Service-Name"MSSQLSERVER"|Restart-Service-Force#Restart SQL Services


       

$logstring="Restarting sql service"

$mc=New-Object-TypeNameMicrosoft.SqlServer.Management.Smo.Wmi.ManagedComputer


               

$svc=$mc.Services["MSSQLSERVER"]


               

#Stop this service


$svc.Stop()

$svc.Refresh()

while($svc.ServiceState-ne"Stopped")

{

$svc.Refresh()

$svc.ServiceState

}

#Start this service


$svc.Start()

$svc.Refresh()

while($svc.ServiceState-ne"Running")

{

$svc.Refresh()

$svc.ServiceState

}

 


           

 

}

catch

{

 


   

 

throw"Starting Sql server service failed in server $_.Exception"


}

}

catch

{

 

 $error[0]


   

 

}

}

Above script is running successfully in powershell version 4.0.But when I run that script in Powershell version 2.0,It is throwing below error

Exception calling "GetSmoObject" with "1" argument(s):"Attempt to retrieve data for object failed for ManagedComputer 'txdsepsn123'."

$ERROR[0] | FORMAT-LIST -FORCE

Detailed error given below

Exception             : System.Management.Automation.MethodInvocationException: Exception calling "GetSmoObject" with "1" argument(s):
                        "Attempt to retrieve data for object failed for ManagedComputer 'txdsepsn123'." ---> Microsoft.SqlServer.Man
                        agement.Smo.FailedOperationException: Attempt to retrieve data for object failed for ManagedComputer

                        'txdsepsn123'. ---> Microsoft.SqlServer.Management.Smo.MissingObjectException: The ServerInstance 'MSSQLSERVER' does n
                        ot exist on the server.
                           at Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer.GetSmoObjectRec(Urn urn)
                           at Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer.GetSmoObjectRec(Urn urn)
                           at Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer.GetSmoObject(Urn urn)
                           --- End of inner exception stack trace ---
                           at Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer.GetSmoObject(Urn urn)
                           at GetSmoObject(Object , Object[] )
                           at System.Management.Automation.MethodInformation.Invoke(Object target, Object[] arguments)
                           at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, Metho
                        dInformation methodInformation, Object[] originalArguments)
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pip
                        e outputPipe, ArrayList& resultList, ExecutionContext context)
                           at System.Management.Automation.StatementListNode.Execute(Array input, Pipe outputPipe, ArrayList& resultLis
                        t, ExecutionContext context)
                           at System.Management.Automation.TryStatementNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList
                        , ExecutionContext context)
TargetObject          :
CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : DotNetMethodException
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
PipelineIterationInfo : {}
PSMessageDetails      :

How to resolve this issue?

 

Office 365 edit user details using powershell

$
0
0

Hi,

I am trying to write a short script to add mobile numbers to multiple office365 users. Each time I run the script I get different results. Sometimes it will work, sometimes it looks to work but does nothing, and sometimes it says 'the command was run successfully but user ** was not changed'

Could someone please let me know what is wrong with my script - I am new to powershell!

Import-CSV c:\telephone.csv | Foreach{Set-user $_.AccountName -MobilePhone $._MobilePhone}

Many thanks


.dwg to .vss mass convert. Help Please!

$
0
0

I have about 800 .dwg files on Autocad2002 that I need to turn into Visio files (.vss) for the convenience of some costumers. Is there a way I can convert them all at once?  Doing it one by one will take all week.
Thanks!

Powershell - Deleting Hyperlinks from a dox/docx file.

$
0
0

Hi, I would like to create a script that goes into doc/docx files and deletes the hyperlink and the hyperlink formatting. This is what I have so far -

add-type -AssemblyName "Microsoft.Office.Interop.Word" #Adding the assembly for working with word documents to allow us to change paper size and orientation later

Get-ChildItem $path -Recurse -include *.doc, *.docx | #For loop to retreve information about the documents such as their name, file path and the number of hyperlinks inside it
    ForEach-Object{
        $document=$application.documents.open($_.fullname) #opening the documents
        write-host "Processing $($document.name)" -ForegroundColor green #letting the user know what document the script is working on currently
        $objSelection = $application.Selection #select the document
        $a = $objSelection.EndKey($wdStory, $wdMove)
        $docprops=@{
            Name=$_.Name
            Path=$_.DirectoryName
           LinkText=$null
            LinkAddress=$null
            }
            $document.Hyperlinks | #for each loop working on the hyperlinks
            ForEach-Object{
                $docprops.LinkText=$_.TextToDisplay
                $docprops.LinkAddress=$_.Address
                New-Object PSObject -Property $docprops #Printing out the document properties such as hyperlink text and its address
                $fpath = $document.path;
                $newaddress= $fpath.SubString(0,($fpath.LastIndexOf('\')+1))
                $faddress = $_.Address
                }
                $document.save()
                $document.Close() #close the document
                [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($document) #Release the write lock on the Word document
         }
         $application.quit()
         [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($application) #Release the write lock on the application

This code searches for doc/docx files in the folders provided in $path/$subfolder, then opens them and searches them for hyperlinks. If they are found, print them out to screen. What I would now like to do is remove the hyperlinks found and the hyperlink formatting if that's possible?

Any Help out there?

Thanks.

Consultant IDs & create group

$
0
0

Hi Team,

I am planning below command to fetch only Par-time & Freelancer IDS from AD using below command
Get-Aduser -filter {EmployeeId -contains "PAR*" or Employeeid -contains "FREE*"} 
Please correct my above command.

Also in the same command I want to add all above users into one AD group "GenericGroup". Please help me.

 

Setting the proxyAddresses attribute using Powershell from a C# app

$
0
0

Greetings All,

I developed a C# app that creates Active Directory Distribution Groups and sets certain attributes. I'm doing this by calling Powershell from within my app. For some strange reason, I cannot set the proxyAddresses attribute. Here is my code...

powershell.AddStatement().AddCommand("New-ADGroup").AddParameter("Name", "<DG Name>")

.AddParameter("GroupScope", "Universal").AddParameter("GroupCategory", "Distribution").AddParameter("path", "<OU>")

.AddParameter("DisplayName", "<Display Name>").AddParameter("Server", "<Server Name>");

The above code works fine.

But when I add the following to the end of the statement...

.AddParameter("OtherAttributes", "@{proxyAddresses="<Email Address>"}

It does not work. Has anyone experienced this before?

Thank you,

Stefan

Applocker Remote reporting.

$
0
0

Hi Guys

I may have missed something blatantly obvious forgive me if I have.

I am trying to pull some Applocker information from client machines to create a report for now I want to pull a list of every program that has been run on a remote machine.

Im new to powershell so dumbing down may be required.

So far I have this.

#To get event entries from remote machine

$events=get-winevent-computer "Computer"-logname"Microsoft-Windows-AppLocker/EXE and DLL"

# For each object $events returns process the following

$events|ForEach-Object{$Appevent=[xml]$events[0].toxml()} {$appevent.Event.UserData.RuleAndFileData|select-objectfilepath|sort-Unique}

pretty sure the loop logic is incorrect but the main problem here is instead of returning the filepath for each object it seems to only return the file path for one and repeats it equal number to the events.

Also

If I run

$events=get-winevent-computer "Computer"-logname"Microsoft-Windows-AppLocker/EXE and DLL"

$Appevent=[xml]$events[0].ToXml()

$appevent

PS returns a list of all the even object but only shows a date time and event ID

If try and drill down to the event details I need PS only returns one random event...

$appevent.Event.UserData.RuleAndFileData

Any help or an actual script that has been done already would be much appreciated.


Viewing all 21975 articles
Browse latest View live


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