Powershell

17K

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

Guys,

Can I put 2 -searchbase into a single line of code

I.E

$BranchGroups = Get-ADuser -searchbase "OU=Branch,DC=net,DC=company,DC=co,DC=uk" -filter {(title -like "*ASM Ambient*")
                            -or (title -like "*Collaboration Only*")
                            -or (title -like "*DM Retail*")
                            -or (title -like "*Food Hall Assistant*")
                            -or (title -like "*SM Operations*")
                            -or (title -like "*SPOC (Only)*")
                            -or (title -like "*Forum Rep (Only)*")
                            -or (title -like "*Out of Hours Duty*")
                            -or (title -like "*Shared Mailbox access nly*")}

Is it possible to put a second search base into this so it scans 2 OU's?

Thanks
Alex
0
Creating Active Directory Users from a Text File
LVL 8
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

Running Install-WindowsFeature Powershell cmdlet results in 'How do you want to open this file?'

Hi all,

I have a fresh Windows 2016 server build.  I am trying to install some Windows Features via Powershell.

When trying to run the Install-WindowsFeature cmdlet, it pops up with the 'How do you want to open this file?'

powershell.PNG
powershell2.PNG
Can someone help me resolve this?  Searching around Google, i have only come across a few mentions of other people experiencing this, but without an obvious fix.

E.G: https://www.reddit.com/r/PowerShell/comments/7o8nee/powershell_cmdlets_prompt_how_do_you_want_to_open/

This may or may not be significant, but I also noticed that when i press tab (to try and autocomplete the commands) it adds a ."\" to the front of the command.  It also seems to cycle through a list of files as opposed to the expected list of features.

Powershell-3.PNG
0
I need to do a powershell script to pull information from the HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* path for a list for a list of computers.  Problem is I'm not very good at this so it is only passing information for one item and ignoring the rest of the computers. Using the script below.  And I'd rather pull this from a Excel file and out to .csv - not from a text file and out to .txt

$Computers = Get-Content C:\Users\"User"[/b]\Documents\"file"

$Objs = @()

Foreach ($Computer in $Computers)

{

 $Obj = Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object $Computer, DisplayName, DisplayVersion, Publisher, InstallDate

}

$Objs += $Obj
$Objs | Out-File "C:\users\"User"\Documents\Servers.txt"
0
Can someone please show me how to export the data from the PowerShell script below to a file?  I cannot for the life of me get it done.  Only a blank file is produced.

Have also tried the export-csv cmndlet with same results.

The data comes up on the screen just fine.

Running the script on an Exchange 2013 server.

Thx,

--------------------

$Mbx = Get-CASMailbox -Filter {HasActiveSyncDevicePartnership -Eq $true -And -not DisplayName -like "CAS_{*"}; $mbx | foreach {$name = $_.name; $device = get-MobileDeviceStatistics -mailbox $_.identity; $device | foreach {write-host $name, $_.devicemodel, $_.devicephonenumber, $_.deviceid, $_.FirstSyncTime, $_.LastSuccessSync} | out-file -filepath C:\Temp\ActiveSyncDeviceInfoTake1.txt -inputobject $Mbx -encoding ASCII -append -width 120 }
0
Hi all,
Thsi powershell code that I retrieved from the link here https://social.technet.microsoft.com/Forums/windows/en-US/5aa53fef-5229-4313-a035-8b3a38ab93f5/unzip-gz-files-using-powershell?forum=winserverpowershell  really works to unzip  the .gz file ,  this was running fine until I have a requirement to unzip multiple files which I dont think this code will works, any recommendation or ideas how to allow this code to be use  to unzip multiples .gz file simultaneous ?


Function DeGZip-File{
    Param(
        $infile,
        $outfile = ($infile -replace '\.gz$','')
        )

    $input = New-Object System.IO.FileStream $inFile, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read)
    $output = New-Object System.IO.FileStream $outFile, ([IO.FileMode]::Create), ([IO.FileAccess]::Write), ([IO.FileShare]::None)
    $gzipStream = New-Object System.IO.Compression.GzipStream $input, ([IO.Compression.CompressionMode]::Decompress)

    $buffer = New-Object byte[](1024)
    while($true){
        $read = $gzipstream.Read($buffer, 0, 1024)
        if ($read -le 0){break}
        $output.Write($buffer, 0, $read)
        }

    $gzipStream.Close()
    $output.Close()
    $input.Close()
}

$infile='C:\Temp\DECfpc1new.csv.gz'
$outfile='c:\temp\DECfpc1new.csv'

DeGZip-File $infile $outfile

Open in new window

0
Hi,

How can I enable the dedup module in Windows 10? It should be possible: https://docs.microsoft.com/en-us/powershell/module/deduplication/enable-dedupvolume?view=win10-ps
But I don't have the enable-dedup cmdlet or import module dedup.
I'd like to use it for running hyper-v machines.

Please advise.

Thanks.
J.
0
I have laptop users on Win10 Pro ver1607 and would like to upgrade them not to ver1703, then ver1709, etc - I'd like to upgrade them from Win10 ver1607 straight to ver1803 (or whatever is the latest supported, you understand my intent).

1. Is it possible to upgrade to the last version, or do I have to incrementally upgrade to each version in turn?
2. Can I use Powershell to upgrade to the version(s) instead of WSUS or Group Policy? WSUS has been problematic at best for this, and I don't care to keep using WSUS unless I absolutely have to. (Group Policy is problematic for remote users, and I don't care to discuss GPOs for this, please do not recommend/spend time discussing)
 
Thanks!
0
I want to make sure that WinRM services are running on my environment on few server. and also enable it if they are not running.
What is the best method to get a list of computers ?
0
Hello Gents

I want a Script Powershell script that can extract all the mailboxes and their sizes and  I want those datas in CSV format

Platform : Exchange 2013

Rgds
0
Hi all,
I have following file Access-Logins-2018_05_20_Batch1.csv.gz and I need to know how do I unzip this zip file by using  powershell ? or can I achieve the same if I use SQL ssis package to unzip the file? After unzip this file going to load in sql server database
0
Improved Protection from Phishing Attacks
LVL 1
Improved Protection from Phishing Attacks

WatchGuard DNSWatch reduces malware infections by detecting and blocking malicious DNS requests, improving your ability to protect employees from phishing attacks. Learn more about our newest service included in Total Security Suite today!

Is there a way to find Lingering Objects in AD through Powershell commands on the DCs?
0
Guys.

I have following small  script in powershell to check all service running with name as  *sql* , In the output I have specify  4  columns which is  name,Displayname,status   comes from
get-service output, but the machinename was not there, how I do manage to get the output too from machinename ? and how many  more column  output like this  actually  that I can includes here  in my ps scripts ?

Get-Service -ComputerName  (Get-Content Servers.txt )| ?{$_.Displayname -like "*SQL*"}|select machinename,name,Displayname,status  | format-table -autosize
0
Hello EE,

I have been researching the Sql server management Object ( smo) via powershell  . I wanted to simply 'generate scripts'  , output to screen similar to SSMS using the options Script "views" . "store procedures" and "User defined functions" . I found I can retrieve the views , sp, user defind functions using a foreach loop .

However, I wish to script a "drop and create" and a script " object level permissions" . Specifically from SSMS advanced options;

Option : Script DROP and CREATE                Value: Script DROP and CREATE
Option : Script Object-Level Permissions   Value:      True

I checked through the scripter options and had no luck so far , I have been using this link as a working example https://blogs.technet.microsoft.com/heyscriptingguy/2010/11/04/use-powershell-to-script-sql-database-objects/  , any help would be appreciated.

$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("DB1")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $srv.Databases.Item("db_Test_Core")

$scrp = New-Object Microsoft.SqlServer.Management.Smo.Scripter($srv)
$scrp.Options.ScriptDrops = $FALSE
$scrp.Options.WithDependencies = $FALSE

foreach ($view in $db.Views){

$smoObjects = $view.urn
If ($tb.IsSystemObject -eq $FALSE)
   {
      $sc = $scrp.Script($smoObjects)
      Foreach ($st in $sc)
      {
      Write-Host $st
      }
   }
   }

Open in new window

0
Dear expert

I would like to build a script that do the server audit like this:
$Servers = Get-Content C:\temp\serverlist.txt
$result = Foreach ($server in $Servers) { gc "$server"       
}
if ($server-ne $null){write-host "File in $Server"}
}
The operation is simply check the server list in the txt files, if there is any files under the path list, write-host file in path.
Code above is not working as planned, the result always show the last line of the serverlist txt got a file in it and I checked, there is no files.
Any ideas?
0
PowerShell Script Requirement: Output in CSV required similar to "TreeSizeProfessional-x64" for local Harddisks Folder, Subfolder and File size in MB/GB.
Windows Server 2008/2012/2016/10
0
so I have the following powershell script, the script works however i would like to add a column to the front of the table that is simply 'date' and every line would have '$dMonth' in the beginning of the csv.

$dMonth= (Get-Date).AddMonths(-0).ToString("dd-MM-yyyy")
$DBServer = "cdiserv1"
$databasename = "SUBSCRIBER"
$Connection = new-object system.data.sqlclient.sqlconnection
$Connection.ConnectionString ="server=$DBServer;database=$databasename;trusted_connection=True"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand

$SqlQuery = @"
SELECT  isnull(B.AcctLineCode, '') AS OLC,
        isnull(B.AcctNum, '') AS OAN,
        isnull(A.AcctLineCode, '') as NLC,
        isnull(A.AcctNum, '') AS NAN,
        isnull(B.Name, '') AS ONA,
        isnull(A.Name, '') as NNA,
        isnull(B.UserField1, '') AS O1,
        isnull(B.UserField2, '') AS O2,
        isnull(B.UserField3, '') AS O3,
        isnull(A.UserField1, '') AS N1,
        isnull(A.UserField2, '') AS N2,
        isnull(A.UserField3, '') AS N3,
        case when A.AcctNum != B.AcctNum or A.AcctLineCode != B.AcctLineCode then 'ACCOUNT MOVED'
        when A.Name != B.Name then 'NAME CHANGE'
        when A.UserField1 != B.UserField1 OR A.UserField2 != B.UserField2 OR A.UserField3 != B.UserField3 then 'FEATURE CHANGE'
        when A.AccountID is not null and B.AccountID is null then 'ADDED ACCOUNT' 
        when A.AccountID is null and B.AccountID is not null then 'DEELETED ACCOUNT' end [Result]
FROM    

Open in new window

0
Not sure exactly how this happened but one VM turns off saying the license has expired while the other VM runs fine. The key on the side of the server is valid, know this because it's used for the host server and one VM. Called Microsoft with an installation ID which gave a failure. Now Microsoft says there's nothing that can be done until Monday morning when the licensing team is available. Now we're stuck babysitting a production server waiting on Microsoft for the next 24 hours.

Question, anyone know how to run a script to start a VM?
0
Good Morning,

Just a simple request I have a text file that has various header records and I want to be able to do a count on the header record ‘Order Number’.

Then output to a text file and sorted in A to Z with a total at the bottom. Example below

Order Number.        Total

GB088776               10
VB66666.                 12
HF56778.                 6

Total                          28
0
Using below script

Get-network adapter -vm (Then i list about 60 vms)

I then pipe it to a csv document, is there a handy way to pipe it in the first place from a csv?

Thanks,
0
Has Powershell sent you back into the Stone Age?
LVL 8
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

On a Windows 10 - 64 bit laptop running Windows 10 version (1709) I have been asked to re-register all .dll files to try solve a problem causing an exe-file not to start. In order to do so, I am opening the Windows Power Shell admin prompt (Cmd prompt) and type: for %1 in (%windir%\system32\*.dll) do regsvr32.exe /s %1

However I then get the following error: "At line: 1 char: 4
+ for %1 in (%windir%\system32\*.dll) do regsvr32.exe /s %1
+       ~
+ Missing opening '(' after keyword 'for'.

Se enclosed screen capture

I have seen this command with the same syntax at several offical Microsoft websites, so it is a bit strange!

What to do?
1
Hello ,
I have a folder with .jpg files inside. The files are pictures of users  and are named using their correspondent "EmployeeID" .  I have also exported to a csv file With  all users inside an OU with Name, SamAccountName, EmployeeID.  EmployeeID has 7 digits.  
Now, I need to for all files in the folder that have a file name with 7 digits to rename it to it's correspondent SamAccountName . If file name exists with SamAccountName, overwrite it.
I have this script for it:
$ht = @{}
Import-Csv -Path "C:\Temp\Exportedusers\AllUsers2.csv" | ForEach-Object {$ht[$_.EmployeeID] = $_.SamAccountName}
Get-ChildItem -Path "C:\Jabber Pictures\userid"  -Filter *.jpg | Where-Object {$_.BaseName -match '\A\d{7}\Z'} | ForEach-Object {
      If ($ht.ContainsKey($_.BaseName)) {
            Rename-Item -Path $_.FullName -NewName ($ht[$_.BaseName] + ".jpg") -Force
       
      } Else {
            Write-Warning "'$($_.Name)': no match in csv!"
      }
}

 But It can't rename a file if already exists as "SamAccountName.jpeg"  
I get this error:
"Rename-Item : Cannot create a file when that file already exists."

Can someone help me to achieve this.
Thanks,
0
Hello EE,

I wish to 'generate scripts' from a database in sql using powershell and save the TSQL to a text file /sql file . In Sql Server Management Studio ( SSMS) it looks like ;

right click db , "tasks', 'generate scripts' , choose 'select specific database objects' , select boxes ' views , stored procedures,  user-defined functions' . Then under 'Advanced' , I select Script Object-Level Permissions =       True ,  Script DROP and CREATE =       Script DROP and CREATE . I then select , " Save to new query window " and the script is available.

I wish to automate this in a script using powershell .
0
Is there a way to have Powershell read the contents of a text file, and if there are any numbers between 200 and 10000 (or anything over 200) on any of the lines in the file, send an email.  I will create a scheduled task to run the Powershell script against the text file every 15 minutes.
0
Any idea how to server the disk size and free space for VMware server (not the VM guests) with PowerCLI ?

Thx
0
Hello All,

We have file redirection set for Desktop and Documents to \\fileshare\userprof$\user\Desktop and \\fileshare\userprof$\user\Documents
We have Sync Center to sync offline files. Everything was working until the file share got too big and instead of increasing the volume, one of the sys admin used a file copy tool and moved everything over to another volume.

This caused users to have access denied issues. He added all the correct NTFS permissions but users were still getting access denied.
Users are able to UNC to the path and add/remove files as needed.

After investigating the issue, we found out that when he moved the folders he took ownership of the folders. This was causing the access denied.
I took ownership back for a few folders and it resolved the access denied issue. There is over 500 folders.

I've tried

icacls "\\cusfs01\userprof$\user1"		/setowner "domainname\user1"

Open in new window

But it errors out and says "This security ID may not be assisnged as the owner of this object"
The manual process of taking ownership works.

What I need help with is creating a powershell script to take ownership of the \\fileshare\userprof$\user folder and set the ownership to the owner.
The user folder is the same as the user ID for the users.

I've searched and found a few powershell script such as

This Article

But the script does not work …
0

Powershell

17K

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.