Powershell

19K

Solutions

8K

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

Hello experts,

I have a script which works good and get me almost what I need.  it output the data into csv file. but it shows size in KB. I want to change that in MB. Also how to include headers into CSV?

I tried adding MB at the end of measure command, but size less than 1 GB it shows 1

Any suggestions?

Regards

Powershell
 $File = "C:\Data.csv"  
  $Exclusions = ("Administrator", "Default", "Public")  
 $Profiles = Get-ChildItem -Path $env:SystemDrive"\Users" | Where-Object { $_ -notin $Exclusions }  
 $AllProfiles = @()  
 foreach ($Profile in $Profiles) {  
      $object = New-Object -TypeName System.Management.Automation.PSObject  
          $FolderSizes = [System.Math]::Round("{0:N2}" -f ((Get-ChildItem ($Profile.FullName + '\Documents'), ($Profile.FullName + '\Desktop') -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB))  
      $object | Add-Member -MemberType NoteProperty -Name ComputerName -Value $env:COMPUTERNAME.ToUpper()  
      $object | Add-Member -MemberType NoteProperty -Name Profile -Value $Profile  
      $Object | Add-Member -MemberType NoteProperty -Name Size -Value $FolderSizes  
      $AllProfiles += $object  
 }  
  [string]$Output = $null  
 foreach ($Entry in $AllProfiles) {  
      [string]$Output += $Entry.ComputerName + ',' + $Entry.Profile + ',' + $Entry.Size + [char]13  
 }  
 $Output = $Output.Substring(0,$Output.Length-1)  
  Do {  
      Try {  
           $Output | Out-File -FilePath $File 

Open in new window

0
C++ 11 Fundamentals
LVL 13
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Hello Experts
I need a batch file or script to add map driver for network location with letter x for example and ask for credential
and another batch or script to remove that mapped drive and credential for that network address
The scenario information
server IP: 192.168.1.254
shared folder on that IP: Home
Domain name: Private.local
1
I've had assistance with this function in the past, but I need to address a bit more criteria now.
I need to ensure that the passed parameter is either
a) A 6-character string, with the first character being a letter among (a,n,s,x) and the remaining 5 being numeric
b) All 7 being numeric
c) a valid email format - and from valid domains.  I have an array $validdomains to compare that against


function Format-UserID { 
    param ([string]$UserID)
    try {
            $uid = $UserID.Substring(0,7).trim()
            if ($uid.Length -eq 6) {
                If ($uid -match "\A(?<Prefix>[ANSX]?)(?<ID>\d{6}).*\Z") {  
                    $prefix = 'A' 
                } else { 
                    $Prefix = $Matches['Prefix']
                }
                return "$Prefix$($Matches['ID'])"
            } else {
                if ($uid.Length -eq 7) {
                    try {
                        if (get-aduser $uid -ErrorAction stop) {
                            return $uid
                        }
                    } catch {
                        'User ID {0} is not a valid ID!' -f $uid| Log-Verbosely 
                        return 'error'
                    }
                } else {
                    'User ID {0} is not a valid ID!' -f $uid| Log-Verbosely
                    return 'error'
                }
            }
    } catch {
    }
}

Open in new window

0
Hi EE,

When running this portion of a PowerShell script:  
Write-Host ""
        Write-Host -ForegroundColor Cyan "Closing existing DB connections. Please wait..."
        Try {
            Invoke-Sqlcmd -ServerInstance $sqlinstance -InputFile $SqlUATconn
            Write-Host -ForegroundColor Green "Connections closed"
        }

Open in new window


I get the following error:

I:\Admin\Scripts\Invoke-Refresh_IsaacMod.ps1 : The 'Invoke-Sqlcmd' command was found in the module 'SqlServer', but the module could not be loaded. For more 
information, run 'Import-Module SqlServer'.
At I:\Admin\Scripts\Invoke-Refresh_IsaacMod.ps1:215 char:13
+             Write-Error $_.Exception.Message
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-Refresh_IsaacMod.ps1

Open in new window


What I don't get about this is I am running PowerShell version  5      , 1,       14393,   2363 and I have already installed the SqlServer module.

Also, the following command was executed on the machine: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned.

Checked to see to the 'invoke-sqlcmd' module is installed by this command; Get-Command -Module SqlServer, it is.

Stepping through the script, it errors out on line 17  SQLServer.psm1 file see attached

I thought there may be a conflict between the SQLPS module and the SQLServer module both are installed (according to get Modules) but when I try to uninstall the SQLPS module I get the following error:

PS C:\Windows\system32> Uninstall-Module -Name sqlps
PackageManagement\Uninstall-Package : No match was found for the specified search criteria and module names 'sqlps'.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:2157 char:21
+ ...        $null = PackageManagement\Uninstall-Package @PSBoundParameters
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power...ninstallPackage:UninstallPackage) [Uninstall-Package]
   , Exception
    + FullyQualifiedErrorId : NoMatchFound,Microsoft.PowerShell.PackageManagement.Cmdlets.UninstallPackage

Open in new window


So I removed the sqlps module using the remove-module command.

Then ran this command:


Open in new window

0
is there a way to move just a calendar from one user's mailbox to another user's mailbox.  

Office Manager Jane has a calendar in her personal mailbox that holds the vacations for all the employees in that office.  Jane has since transferred so she is no longer working in that office but the new manager would like to have that calendar is there a way using powershell to make a copy of that calendar and move it to the new office manager?
0
Dear all experts,

I run the following command in PowerShell and would like to obtain the security log details,

Get-EventLog -LogName Security -InstanceId 4662

however, I found that the result is not same as the event log,   Object name in PowerShell result becomes a SID but in event log it is showing the full DN of the object.

Is there anyway to convert the SID to DN in PowerShell.
Result in PowerShell3.PNG
1
Hi,

I have one variable that reads some veeam jobs.

I want to compare the "endtime" attribute between the jobs :

$seshlistBKID | fl endtime


EndTime : 11/04/2019 07:35:07

EndTime : 10/04/2019 14:58:19

EndTime : 10/04/2019 15:14:52

Open in new window


I want the most recent one and send it to a variable.

I don't know how to do it, I think about export-csv but this is to much for something maybe simple.

Thanks you!
1
Dear expert
Please read the code  below, now at the end I don't know how to code the way I want, if the search found ^01 I want it to create a file with same name as the original file in $intv6return, any idea? And the Out-File $intv6s + $filename seems not work as well... And the pattern variable is wrong too. Please help me to correct this, thanks

This is the file flow:
Scan the folder $intv6er
check if there is file with content ^01 or ^02, if found ^02 create file name as $filename, and fill the file with the row ^02 to $intv6s. if found ^01 create file name copy the file to the $intv6return without the row ^02.

$intv6return = "\\server\Payments\Return"
$intv6s = "\\server\PaymentReportImport\S"
$intv6er = "\\server\PaymentReportImport\E"
$pattern = "^01, ^02"
$date = (get-date).adddays(1).ToString("yyMMdd") 
$filename = "S_00e321." + $date + ".T39"
$search = Get-ChildItem $intv6er | Select-String -Pattern $pattern | 
foreach {
        Select-Object Line}

if($pattern -eq "^02" ){
$search | Out-File $intv6s + $filename }
if($pattern -eq "^01" ){
$search | where {$_ -eq "^01"} | Out-File.........}

Open in new window

1
Hi EE,

I am running a backup in PowerShell:

# Backup existing SQL databases
		Write-Host ""
		Write-Host -ForegroundColor Cyan "$(Get-Date) - Backing up $($DbName[0]) databases. Please wait..."
		Try {
			$DbName | Foreach-Object {
				Backup-SqlDatabase -BackupAction Database -BackupSetDescription "Data refresh from Prod" -CopyOnly -Database $_ -Path $SqlPsPath -BackupFile ($BackupPath + $_ + "_" + (Get-Date -UFormat %Y%m%d-%H%M%S) + ".bak")
				Write-Host -ForegroundColor Green "$(Get-Date) - $_ database backup completed."
			}
		}

Open in new window


It's parsing in the databases just fine, but the process keeps showing up as SUSPENDED in the SQL Server and stays like that never resuming I have waited for 17 minutes no go.

The server it's has very little activity on it as it is a UAT environment.

Any ideas as what could be causing this or commands to drill into the cause of the suspension any assistance is welcome.

Attached is metadata from sysprocesses.

Additional ran the following query get some insight:
SELECT r.wait_type
	   command,
            s.text,
            start_time,
            percent_complete,
            CAST(((DATEDIFF(s,start_time,GetDate()))/3600) as varchar) + ' hour(s), '
                  + CAST((DATEDIFF(s,start_time,GetDate())%3600)/60 as varchar) + 'min, '
                  + CAST((DATEDIFF(s,start_time,GetDate())%60) as varchar) + ' sec' as running_time,
            CAST((estimated_completion_time/3600000) as varchar) + ' hour(s), '
                  + CAST((estimated_completion_time %3600000)/60000 as varchar) + 'min, '
                  + CAST((estimated_completion_time %60000)/1000 as varchar) + ' sec' as est_time_to_go,
            dateadd(second,estimated_completion_time/1000, getdate()) as est_completion_time
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s
WHERE r.command like '%Backup%'

Open in new window


Results of the query attached as well nothing seems wrong to me.

Thank you.
SPID-Details-1.csv
SQL-Diagnostic-Query.csv
0
We incorrectly enabled an Archive mailbox for a cloud user, we are in a hybrid setup.  It was enabled via O365 portal and not on-prem as a hosted Archive Service first.

Now when we try to disable it online, we have to Disable In-Place Archive and get this error:

Exchange cant disable the mailbox <mailboxname> because it is on in-place hold. ComplianceTagHolderApplied: false, DelayHoldApplied: false, OrganizationalPolicies Applied: mbxjkldjlky539sm4kje3ds42jh509so8dlk3:2, UserPolicies Applied: . For more information, please see the powershell cmdlets, Get-OrganizationConfig <> | fl inplace*, and Get-Mailbox <> | FL

Get-Mailbox <mailboxname> | FL *archive*
ArchiveDatabase             : NAMPR03HSD34-db099
ArchiveGuid                 : 65d78ae3-dc7b-61e9-475b-97ad31a8f74d
ArchiveName                 : {}
JournalArchiveAddress       :
ArchiveQuota                : 110 GB (118,111,600,640 bytes)
ArchiveWarningQuota         : 100 GB (107,374,182,400 bytes)
ArchiveDomain               :
ArchiveStatus               : Active
ArchiveState                : Local
AutoExpandingArchiveEnabled : True
DisabledArchiveDatabase     :
DisabledArchiveGuid         : 00000000-0000-0000-0000-000000000000
ArchiveRelease              :

Ive tried to disable the hosted archive on prem, then synced to the cloud, even tried clearing the msExchArchiveStatus attribute and syncing... We just cant seem to revert this so that we can enable it the right way, via Exchange On-Prem.
0
Exploring SQL Server 2016: Fundamentals
LVL 13
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

I am looking to write a script for pulling IEVersion for computers on a txt file can anyone assist with Powershell or Quest Powershell  if possible?
0
I nned a Powershel lscript to help me get all 2008 servers that are currently disabled in AD and export the list to a csv file with Server name  and OS name ver
1
For Exchange online, how do I change the primary SMTP for all email accounts including resources, shared mailboxes to "newdomain.com"  and have a secondary domain to be "newdomaingroup.com" in bulk using Powershell?
1
I am importing a text file that has a header row of the column names.

How do I skip the first row and import from the 2nd row down?  I have a ForEach looop to step through every row of the text file.

$filePatterns = Get-Content "\\shea-x400s01\data\medd_quality\PUBLIC\DataWatch\DenialLetters\91-1104421C\Data_CAS\EDW_Gold_CAS_PAL.txt"

ForEach ($pattern in $filePatterns) {
    Write-Host "-------------------------"
    Write-Host "pattern = " $pattern
    $member,$fullname = $pattern.split('|')[1,-1]
    Write-Host "fullname= " $fullname
    $file =$fullname.Split('\\')[-1]
    Write-Host "file= " $file
    $fileName =$file.Split(".")[0]
    Write-Host "filename= " $FileName
}

Thanks
1
A client email address seems to be sending out emails to clients asking for bank account changes etc.

The client is on a laptop using all the AVG products plus a a/v provided by solar winds.

Two clients have gotten these emails one that was not specific and one that asked for the exact invoice
that was due.

Sent items on a computer and in owa don't show that email being sent but I have message id's when I do an office 365 search
showing that they have been sent.

Below is the message headers...

Was this done via powershell or did the account get hacked?  I only see one reference to http
and I see this Transport-CrossTenantHeadersStripped:  part which I don't understand...

Both are office365 clients

I can generally figure these things out but the client has had the password changed and is running those software suites which while
not the best,  do pick up some bad activities.  

Anyway we are trying to sniff out this in the right direction and would love to be told what I am reading wrong or where I should be looking

Thank you



Received: from BL2P131MB0002.NAMP131.PROD.OUTLOOK.COM (2603:10b6:208:71::29)
by BL2P131MB0001.NAMP131.PROD.OUTLOOK.COM with HTTPS via
BL0PR01CA0016.PROD.EXCHANGELABS.COM; Thu, 4 Apr 2019 16:33:35 +0000
Received: from BN6P131CA0004.NAMP131.PROD.OUTLOOK.COM (2603:10b6:423:5f::18)
by BL2P131MB0002.NAMP131.PROD.OUTLOOK.COM (2603:10b6:221:22::21) with
Microsoft SMTP Server (version=TLS1_2,
0
Hi EE

Does anyone have a script to share that will copy the samaccountname from one group and add them to another group in a different domain ?

So basically I need Domain1\Group1 have the same members copied to Domain2\Group1

I have this need for multiple groups .
0
Hey Experts!  I have a powerful script that I would like to add a little more details to the log file but am not sure how to put the lines into the existing code.  Any help would be appreciated.

Get-ADComputer -Filter 'Name -like "TRN3*"' -SearchBase "OU=COMPUTERS,OU=TRAINING,DC=LOCAL" -Property * | Select-Object -ExpandProperty name | out-file c:\tools\logs\testlog.csv

$computerList = Get-Content c:\tools\logs\testlog.csv
$logFile = 'C:\Tools\logs\profiles2.csv'

$computerList | ForEach-Object {
	$computerName = $_
	Write-Host "Processing $($computerName) ..."
	If (Test-Connection -ComputerName $computerName -Count 2 -Quiet) {
		Try {
			$diskC = Get-WmiObject  Win32_LogicalDisk -Filter "DeviceID='C:'" -ComputerName $computerName -ErrorAction SilentlyContinue
			$diskSize = [math]::Round($diskC.Size / 1GB, 2)
			$freeSpaceBefore = [math]::Round($diskC.FreeSpace / 1GB, 2)
			$profiles = Get-WmiObject -Class Win32_UserProfile -Filter "(Special='False') And (Loaded='False') And (Not (SID Like '%500'))" -ComputerName $computerName -ErrorAction Stop
			If ($profiles) {
				$profiles | ForEach-Object {
					$out = $_ | Select-Object -Property @{n='ComputerName'; e={$computerName}}, LocalPath, Result
					Try {
#						[void]$_.Delete()
						$out.Result = "Profile deleted"
					} Catch {
						$out.Result = "ERROR: $($_.Exception.Message)"
					}
					$out
				}
			} Else {
				[PSCustomObject]@{ComputerName=$computerName; Result='Found no profiles to delete'}
			}
			

Open in new window

1
Just wondered if anyone knows how I can improve my script below so I can see the output\results of each batch file that is run via invoke-command to a remote server.  

Thanks in advance. Love ya work ;-)

My sample script is below.


foreach ($server in (Get-Content "D:\_ServerLists\Servers.txt")) {
   
    $session = New-PSSession $server
    Copy-Item "D:\SpotFix8\Batchfile.bat" -Destination D:\temp\ -force -ToSession $session

    Invoke-Command -Session $session -ScriptBlock {
   
     Set-Location "D:\temp\
     Start-Process cmd -ArgumentList "/c .\Batchfile.bat"

    }
}
1
Hi EE,

I am running the following script (the script function is essentially to refresh databases from prod to UAT environments) see attached with the following command:

./Invoke-Edited.ps1 -Environment Test -ScriptBlock {param($p1, $p2)} -ArgumentList $ComputerName, $SQLBackupPath

I am running the scripts remotely and I am getting the following error

Cannot find an overload for ".ctor" and the argument count: "1".
At C:\Invoke-Edited.ps1:54 char:9
+         [ValidateNotNullOrEmpty('DC1PRDSQLFCI02')]

Any assistance is appreciated.

Thank you.
Edited.ps1
0
Exploring ASP.NET Core: Fundamentals
LVL 13
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Hi There,
I am running a server 2012 r2, of which I broke up the nic team to test performance difference. Now I am stuck with a virtual ethernet adapter that I need to remove in order to redo the teaming. The cmdlt for "vmnetworkadapter" is not working.
0
Hello,
The goal is to get the data into a sql table. I just need help parsing the text file into 2 columns, multi row.  I don't care how they are delineated I can figure out the import side.
 I have written python, t-sql and powershell so ideally the solution would use one of those tools.

The files are not large and are text files.  Assume I'll need to run process once a month but not consistently.
Data between {} is one record, 2 columns.  No cr at row end.

There can be any number of filenames in the text file with 0 to 30 pieces of information so empty [] is a possibility.  
I want each comma separated value in information to be a new row.  i want all {'': to be removed

example:Input  shows 2 records
{'filename':'colors','information':[red,blue,yellow]}, {'filename':'colors','information':[pink,orange]}, etc.

required output  for first one
filename    Information
colors        red
colors        blue
colors        yellow
0
Dear all,

I would like to know how to add a user to an exchange distribution group by matching the user's from a text file. My text file is as following

Group,Email

My current powershell is as following

$Users = Import-Csv "C:\Scripts\Users.csv"
foreach ($User in $Users){
$member = $user.email
group =$user.group

if($group -like "CertainExchangeGroup"){
Add-DistributionGroupMember -Identity  "CertainGroup@domain.com" -Member $member{
}
Write-Host $member has been added to $group -ForegroundColor Green}
}

Open in new window


At the moment this doesn't work and gives the following error
A positional parameter cannot be found that accepts argument '
'.
    + CategoryInfo          : InvalidArgument: (:) [Add-DistributionGroupMember], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Add-DistributionGroupMember
    + PSComputerName      

I would appreciate any help to fix this
Thank you
1
Hi EE,

I have some trouble running some PowerShell scripts that access SQL servers, below is a picture of the error.

As you can see already have the SQLserver module installed what should do to troubleshoot?

Below is the code used to import the module into the script:

		# Load SQL PowerShell module 
		$MyLoc = Get-Location
		Import-Module SQLSERVER
		Import-Module SQLSERVER -Cmdlet Backup-SqlDatabase
		Import-Module SQLSERVER -Cmdlet Restore-SqlDatabase
     
		Set-Location $MyLoc

Open in new window


Thank you
Powershell-Error.PNG
0
Hey Experts.  Trying my hand at a script that will clean-up profiles on the Windows 7 pc's in our training lab.  

I thought a script that pulled the computer names from the OU, put them in a text file and then perform a few actions on each pc in that file while recording the failure/success of the actions.  Something like A) ping the pc's to see if they are online and B) remove profiles. I put together a starting script but struggled with the profiles being removed from the computers that are pingable.

Get-ADComputer -Filter 'Name -like "TRN3*"' -SearchBase "OU=COMPUTERS,OU=TRAINING,OU=DEPTS,DC=LOCAL" -Property * | Select-Object name | out-file c:\tools\logs\output.txt

get-content -path c:\tools\logs\output.txt | foreach-object { ping $_ } > c:\tools\logs\pingresult.txt

Open in new window


End goal: powershell script that creates a logfile of computer names from the OU specified, verifies the computer is online via ping and if it is, removes the user profiles on each computer listed in the logfile.  Logging results to verify success.  

Again, any constructive criticism is welcome and I appreciate your time.

(edited for clarification)
0
How can you switch Azure AD directories in Powershell?
It is simple to switch thru the web interface, but say I need to run commands via Powershell with an account that is federated between the Prod and Dev environments?
0

Powershell

19K

Solutions

8K

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.