Powershell

15K

Solutions

7K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.

Share tech news, updates, or what's on your mind.

Sign up to Post

I have been tasked with quickly finding a way to run a report of failed logins to our O365 user mailboxes. I'm a complete Exchange powershell noob. I've enabled auditing on my own mailbox using   set-Mailbox -Identity "scott" -MailboxLogin $true and I have verified that it is enabled by checking the mailbox extended properties. I have not found the correct syntax for enabling the -MailboxLogins audit.

PS C:\Program Files (x86)\AppRiver\Pshell for O365> set-Mailbox -Identity "scott" -MailboxLogin $true
A parameter cannot be found that matches parameter name 'MailboxLogin'.
    + CategoryInfo          : InvalidArgument: (:) [Set-Mailbox], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Set-Mailbox

So three questions:
1. Can someone correct my syntax?

2. Is there a link to documentation that gives syntax  examples better than those I've found on technet? I've found nothign specifically related to enabling the -MailboxLogins audit other than the overview doc at https://technet.microsoft.com/en-us/library/dn879651.aspx#actions

3. Is the -MailboxLogins parameter going to enable me to see failed logins?

Thanks all.
0
On Demand Webinar: Networking for the Cloud Era
LVL 9
On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Hello, I'm stuck and need help!

I want to record the number of handles of a specific process into a txt file.   The script will run an timed interval, maybe once a day.
After sometime I will see if there is a handle leak on this specific process (I'm using 'explorer' as an example).

Here is my attempt with Powershell (Trying to learn Powershell):

$ProcessHandles = Get-Process explorer | Format-Table -HideTableHeaders -Property Handles
$TheDateandTime = Get-Date -Format "yyyy/mm/dd - HH:mm  : "
$TheLogFile = "c:\temp\processhandle.log"

write-output $TheDateandTime $ProcessHandles | Out-File -FilePath $TheLogFile -Append

Open in new window



Take a look at the screenshot attached.   The log file has unwanted CR and LF.   Hopefully the screenshot explains what I'm getting and what i'm trying to get too.

Thanks for your time to look at this.

--Paul
002163.png
0
This script gets the services on a set of systems, and returns the service name, 'logon as' and server it is on, then exports it to a csv file. This works fine.
I tried adding a where-object to it to remove "local System"  "Network Service" "LocalSystem" any by themselves do nothing, with a -or also does nothing. My attempts have been in vain, is there an easy way to filter out the chaf?
$datetime = (get-date -f yyyy-MM-dd-HH-mm)
Get-Content systems.txt| Foreach-object  {
  Write-Host "Retrieving Servers for $_ "    
  Get-WmiObject win32_service -ComputerName $_  | select Name,
  @{N="Service Account";E={$_.StartName}},
  @{N="System Name";E={$_.Systemname}}}|where-object { $_.StartName -notlike "LocalSystem"} |export-csv -path  D:\path\$datetime-Services.csv -nti

Open in new window

0
Hi,

There are some remote W7 machines (different domain) which I need an software inventory of.
Tried to enable remote powershell but it fails on some machines so I better stick to wmi.

Script below works fine, but my output is not yet what I need = Excel with all pc's and their software (pivot table).
The output is now in a ormat which I'd like to convert to:
computer01 software01
computer01 software02
computer01 software03
computer02 software02

So I can export it to Excel then make the pivot table.
My questions: how to continue  + is the WMI query showing all software or should I add extra queries?
Thanks!
---
This is the script so far:

$Workstations| ForEach-Object {
       
       Write-Host "Getting sofware of $_"      
       $Software = Get-WmiObject -Class Win32_Product -ComputerName $_
       $Overview += [PSCustomObject] @{
              Computer = $Software.pscomputername
              Software  =  $Software.caption
            }    
}
 $Overview

Computer                                                                                        Software                                                                                      
--------                                                                                        --------                                                                                      
{Computer01, Computer01, Computer01, Computer01...}                                                         …
0
Currently, my script has code similar to:
$ServerDatabasePairs = @"
Server,Database
server1,database1
server1,database2
server2,database3
"@ | convertFrom-CSV

Open in new window

I am wanting to process data from a configuration file. This file is in a key,value format. I want to have a key named ServerDatabasePairs that has a value something like:
ServerDatabasePairs,"server1|database1,server1|database2,server2|database3"

Open in new window

and ultimately parse it the same as the existing code above (e.g. into a two-dimensional table).
Not sure how to accomplish this.
0
Can you please help me in deleting the Key named "Certificates" located in the following path using PowerShell Script.

"HKEY_LOCAL_MACHINE\Software\Microsoft\SystemCertificates\SMS"

 Registry
We are using Windows Server 2012 R2
0
Hi all,

I have a Powershell script that copies AD group memberships from one user account to another. The script is as follows:

 
Import-Module ActiveDirectory

$copy = Read-host "Enter user to copy from"
$Sam  = Read-host "Enter user to copy to"
 Function Copymembership {

$members = Get-ADUser -Identity $copy -Properties memberof
foreach ($groups in $members.memberof){
if ($members -notcontains $groups.sAMAccountname)
{Add-ADGroupMember -Identity $groups -Member $sam -ErrorAction SilentlyContinue
Write-Output $groups} 
}
}
copymembership

Open in new window



Running the script prompts for both the source account and the target account to be entered, before going off and 'doing the do'.

I now have the requirement to copy AD account memberships for hundreds of users. I have a CSV with the data, an example of the formatting is below...

SourceUser, TargetUser
TestUser1,TestUser1NEW
TestUser2,TestUser2NEW  


I have been trying to find a way to import the CSV into the original script above, and go through the list copying memberships from each source user to their target account.

Any pointers/help/advice would be greatly appreciated.

Cheers
0
Hi All,

Greetings...

According to my work, I need to zip files present in a folder using batch script without using any 3rd party software.

I tried with below code ,but getting the error.error also attached below.

Any help regarding this would be highly appreciated.
'Get command-line arguments.
Set objArgs = WScript.Arguments
Set FS = CreateObject("Scripting.FileSystemObject")
InputFolder = FS.GetAbsolutePathName(objArgs(0))
ZipFile = FS.GetAbsolutePathName(objArgs(1))

'Create empty ZIP file.
CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)

Set objShell = CreateObject("Shell.Application")

Set source = objShell.NameSpace(InputFolder).Items

objShell.NameSpace(ZipFile).CopyHere(source)

'Required!
wScript.Sleep 2000

Open in new window


This code is present in zip.vbs file. We have to zip the files into Outputfile.zip file.
in command prompt  , I have entered below command

C:\Users\abc>Cscript zip.vbs input path  output path\OutputFile.zip

While executing this ,I got below error. " Path not found error" for both the input and output file path.

It will be helpful if anyone corrects me the mistake which I made in this script.
2
I am trying to follow the instructions within the the https://social.technet.microsoft.com/wiki/contents/articles/24541.powershell-bulk-create-ad-users-from-csv-file.aspx#Code_Used webpage to import username information from a .CSV file to create usernames within Server 2016 Active Directory but every time I try to do this I receive the following error messages:

When I run the following command within PowerShell (running as an administrator) .\un.ps1 I get the error message

 “ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is null.
At C:\Support\UN\UN.ps1:12 char:232
+ ... scription" -AccountPassword (ConvertTo-SecureString $Password -AsPlai ...
+                                                         ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [ConvertTo-SecureString], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is null.
At C:\Support\UN\UN.ps1:12 char:232
+ ... scription" -AccountPassword (ConvertTo-SecureString $Password -AsPlai ...
+                                                         ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [ConvertTo-SecureString], ParameterBindingValidationException
    + FullyQualifiedErrorId : …
0
I have a PowerShell 5.0 script that runs fine as a standalone script.  It logs on to Office 365 Exchange and does a Connect-MSolservice.  However, when I call this script from within Microsoft Access 2016, I get the following error:

Import-Module : Could not load file or assembly 'file:///C:\Windows\System32\Wi
ndowsPowerShell\v1.0\Modules\MsOnline\Microsoft.Online.Administration.Automatio
n.PSModule.dll' or one of its dependencies. An attempt was made to load a
program with an incorrect format.
At S:\PCA2\ScriptsAndSuch\503_Test.ps1:18 char:4
+    Import-Module C:\Windows\System32\WindowsPowerShell\v1.0\Modules\M ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Import-Module], BadImageF
   ormatException
    + FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Co
   mmands.ImportModuleCommand

Windows Server 2008 R2 x64
0
WatchGuard's M Series Appliances - Miecom Approved
WatchGuard's M Series Appliances - Miecom Approved

WatchGuard's newest M series appliances were put to the test by Miercom.  We had great results and outperformed all of our competitors in both stateless and stateful traffic throghput scenarios! Ready to see how your UTM appliance stacked up? Download the Miercom Report!

I had this question after viewing Active Directory PowerShell: Remove manager from User object(s) located in a specified OU folder..

I would like to scan through the users in active OU's and remove the manager attribute of any of those users whose manager is in my Inactive OU.
0
Having trouble with the following script - specifically the first foreach loop:

#Prompt user for the mailbox owner's username 
$mailbox = Read-Host -Prompt 'Input mailbox owners username' 
 
	$devices = Get-ActiveSyncDeviceStatistics -Mailbox $mailbox 
	 
	#If the current mailbox has an ActiveSync device associated, loop through each device 
	if ($devices)

    {
		foreach ($device in $devices)
        {
		  
			#Remote wipe mobile device and remove active sync association
			Clear-ActiveSyncDevice -identity $device.DeviceID –NotificationEmailAddresses ‘user@acme.com'
                        Remove-ActiveSyncDevice	-identity $device.DeviceID			
						
		} 
    	 
	}

#Remove from all distribution groups
$DGs = Get-DistributionGroup

foreach( $dg in $DGs)

    {

    Remove-DistributionGroupMember $dg.Name -Member $mailbox -EA SilentlyContinue -Confirm:$false

    }

#Hide email address from Global Address list
Set-Mailbox -Identity $mailbox -HiddenFromAddressListsEnabled $True
#Disable AD account
Disable-ADAccount -Identity $mailbox
Write-Host 'Script complete'

Open in new window


The problem is that the Activesync device supposedly cannot be found.  Here's the error I get:

The ActiveSyncDevice J07GTPSONH6FJ58A0JM0E0U9QG cannot be found.
    + CategoryInfo          : NotSpecified: (0:Int32) [Clear-ActiveSyncDevice], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : CF83F532,Microsoft.Exchange.Management.Tasks.ClearMobileDevice
    + PSComputerName        : exchange.acme.local

Open in new window


However, when I look for the device ID, that is the correct "DeviceID" for the device associated with the account I'm testing (Username "ttester")

Should I instead be using some other method of identifying this mobile device?
0
Greetings experts.  I have a service that is causing problems and while I research the underlying issue, I need to have the service (s[tracev4) restart every morning around 5am.  The script will check to see if the service is running, if it is, it will stop it, then start it.  If the service isn't running when the script checks it, it will start it.

Please write this in powershell as I've begun the task of moving everything from batch to PS.  Thanks in advance.
0
I have a simple script to check up down of ips. I have it displaying the way I would like, I would also like to save all of those up/downs to a text file. ( I have to send the results to someone else.) When I try to pipe it after the write-hosts are done, I get "An empty pipe element..."
Is there a simple way to get both?

Get-content c:\path\names.txt | %{
	If (Test-Connection $_ -Quiet -Count 2){
	write-host -foregroundcolor black -backgroundcolor green "$_ is UP"
	}
	Else{
	write-host -foregroundcolor black -backgroundcolor red "$_ is Down"
	}
}
|Out-File c:\path\result.txt

Open in new window

Thanks!
0
I'm trying to remove some folders but there were files created with Mac that the filenames are too long for Windows. Does anyone know how to force a folder delete no matter what is in it.

The file names are literally a sentence.

Below is the message I'm getting on PS.




PS C:\Users\david.mundt> Remove-Item -path "E:\Shared\Client Projects\Adobe" -recurse
Remove-Item : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less
than 248 characters.
At line:1 char:1
+ Remove-Item -path "E:\Shared\Client Projects\Client" -recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (E:\Shared\Client Projects\Client:String) [Remove-Item], PathTooLongException
    + FullyQualifiedErrorId : RemoveItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
0
Dear,
I have to copy 2 files containted in one folder to dynamic set of sub folder.
Let's say
files are stored in c:\template
Destination folders are c:\Documents\A .......; c:\Documents\Z

I want the 2 files into all subfolders of c:\Documents
I have this but seems not working...


Get-ChildItem -Path c:\template | ?{ $_.PSIsContainer } | Copy-Item c:\documents $_.fullname
0
Hi everyone,

I have the following Powershell script that searches a list of servers for windows patches and their status.  However, the current output returns ALL installed patches, whereas I would like the the ability to just search on certain patches (KBs).  Can anyone tell me how I could modify this script to implement that feature?

$sb = {
    # remove the last pipe with the ft cmdlet, i.e.:
    # | Format-Table -AutoSize -Wrap
 
    $Session = New-Object -ComObject Microsoft.Update.Session
    $Searcher = $Session.CreateUpdateSearcher()
    $HistoryCount = $Searcher.GetTotalHistoryCount()
 
    $Searcher.QueryHistory(0,$HistoryCount) | ForEach-Object -Process {
        $Title = $null
        if($_.Title -match "\(KB\d{6,7}\)"){
            # Split returns an array of strings
            $Title = ($_.Title -split '.*\((?<KB>KB\d{6,7})\)')[1]
        }else{
            $Title = $_.Title
        }
 
        $Result = $null
        Switch ($_.ResultCode)
        {
            0 { $Result = 'NotStarted'}
            1 { $Result = 'InProgress' }
            2 { $Result = 'Succeeded' }
            3 { $Result = 'SucceededWithErrors' }
            4 { $Result = 'Failed' }
            5 { $Result = 'Aborted' }
            default { $Result = $_ }
        }
        New-Object -TypeName PSObject -Property @{
            InstalledOn = Get-Date -Date $_.Date;
            Title = $Title;
            Name = $_.Title;
            Status = $Result
        }
    } | 
    

Open in new window

0
Server 2012 R2 Powershell as administrator
So I believe I'm doing something wrong with the powershell command it works to create a parent and then a child in the parent but unable to create child inside of child or however it would be labeled

DC Test.local
OU Parent Test1
OU Child Site1
Unable to create Computers inside of Site1

new-adorganizationalunit -name "Computers" -path "OU=Test1, OU=Site1, DC=test, DC=local"

What is the issue here ?
0
I have a dynamic distribution group that includes all Exchange email users but have a few users I don't want in the group.  I want to use extensionAttribute to exclude these users.  What is the powershell command I use to do this?
0
NFR key for Veeam Agent for Linux
LVL 1
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

I need a script to continuously ping a specific computer until it pings successfully and send a reboot command to reboot the same computer.

I know this is an odd request to reboot a computer when it first comes up but I need to do this to complete an install.

Any help is greatly appreciated.
0
Hi,

I have a Powershell Studio project, tool which is linked to the current domain.
Variables are hardcoded in the tool, f.e. $SCCMServer = oursccmserver.ourdomain.com, $RDSServer = ourrdsserver.ourdomain.com
I'd like to use the tool in another domain so need to extract all the variables and would like to put them in a textfile.
So that file would contain:
#SCCM server, fill in here
$SCCMServer =
etc

To give you an example, vcheck works this way:
https://github.com/alanrenouf/vCheck-vSphere
But I wonder howto transfer my current script the least painful way (kind of search and replace way)

How to achieve this the best way?
Please advise.
J.
0
So the current system used stores users "My Documents" and other files in a personal drive and on a server. We use Microsoft's Sync Center to ensure both "My Documents" and the personal drive contain the most current data.

The problem is since users files are also available offline sometimes remote users don't connect to our server(they need to access our VPN to do so). This causes a problem with synchronization. It's very time consuming to check one person at a time on Microsoft's Sync Center.

Is there a way to automate detection? Maybe a Cmdlet?
0
Hi All

I have a script that checks for certain event viewer logs and if they occur it reboots the PC.

However, I want it to force a log off instead

If I change from:

Restart-Computer -Force

TO

Shutdown /l /f

Is that correct as I would not want to schedule this as a task and end up finding computers shut down instead of logged off.
0
Hi All

This relates to an earlier post with regards to generating email alerts from event viewer.

However, we are experiencing multiple windows events matching the below criteria and the only way to refine would be to refer to a piece of text in the General or Details tab.  I have checked the add/remove columns option to get an ID for either of these but they do not exist by the look of it, is it possible to do this?

$Events = Get-EventLog -LogName "Application" -Source "SelfServicePlugIn" -EntryType Error,Warning, Information -After (Get-Date).AddMinutes(-120) -ErrorAction SilentlyContinue | Where-Object {$_.eventID -eq 1} 
    #write-host $Events.Count
    if ($Events.Count -gt 0)
    {
    $hostname = $env:Computername
    $From = "noreply@xxxx.xxx.xx"
    $To = "x.x@xxx.xxx.xx"
    $Subject = "Potential xxxxxxxxxxxxx Database Connection Loss"
    $Body = "The Windows event of 'xxxxxxxxx' has occurred on $hostname.  This xxxxxxxxxx may have lost connection to the database  and has been restarted."
    $SMTPServer = "mail.xxxx.xxx.xx"
    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer
    #Restart-Computer -Force
    }
    else {exit}

Open in new window


Note - "SelfServicePlugIn is an example regular event I am using for testing.
0
This one has baffled me and I haven't been able to figure this out within powershell. (I'm able to dump the results to a file)

I've tried these variations on the command:
$iplist = 1..5 | %{"10.0.0."+$_}

$a = $iplist | %{Test-Connection $_}

$b = Test-Connection $iplist

$job = Test-connection -ComputerName $iplist -asjob
$c = Receive-Job $job

Open in new window


The first two run the command and then when I try and view the variable it seems to test the connection again. The one where I run as a job completes immediately and when I try and view the retrieved results it seems to run the test again.

Does anyone know why this happens (I can't think of anything else I've used in Powershell that behaves like this) and how I can store the results of the test?
This occurs on Windows 2008 R2 through current that I've seen.
0

Powershell

15K

Solutions

7K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.