Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

I seem to be having problems pulling a listing of connected monitor sizes

$
0
0

I'm trying to pull a listing of how many monitors are connected to each computer and the size of each monitor. When I run the script, using my local computer in the input file, the output looks like the following:

Computer855,24 20 --(which is how it's supposed to look)

When I run the script against a text file containing a list of all computers in my Organizational Unit, the output looks like the following:

@{Name=Computer12099},0
@{Name=Computer12954},0
@{Name=Computer12776},0
@{Name=Computer13875},0

(which is how it's NOT supposed to look, and it doesn't record the connected monitor sizes)

There is no difference in the input file, no additional spaces or carriage returns...

What am I doing wrong?

$computers = Get-Content c:\inputfiles\Complist.txt

foreach ($Computer in $computers) {

 

$output = [PSCustomObject]@{ComputerName = $Computer;MonitorSizes=''}

 

$oWmi = Get-WmiObject -Namespace 'root\wmi' -ComputerName $Computer -Query "SELECT MaxHorizontalImageSize,MaxVerticalImageSize FROM WmiMonitorBasicDisplayParams";

$sizes = @();

if ($oWmi.Count -gt 1) {

             foreach ($i in $oWmi) {

                           $x = [System.Math]::Pow($i.MaxHorizontalImageSize/2.54,2)

                           $y = [System.Math]::Pow($i.MaxVerticalImageSize/2.54,2)

        $sizes += [System.Math]::Round([System.Math]::Sqrt($x + $y),0)

             }##endforeach

} else {

             $x = [System.Math]::Pow($oWmi.MaxHorizontalImageSize/2.54,2)

             $y = [System.Math]::Pow($oWmi.MaxVerticalImageSize/2.54,2)

             $sizes += [System.Math]::Round([System.Math]::Sqrt($x + $y),0)

}##endif

 

$output.MonitorSizes = $sizes

$Msz = ([string] $output.MonitorSizes )

$strDone = "$computer,$Msz"

Add-Content c:\outputfiles\MonSizes.txt -value $strdone 

}


parallel port GPI and GPO

$
0
0

I'm sitting in front of a Dell Precision T5500 running Windows 7 Professional, 64bit.  It has a parallel port, (device manager describes it as "ECP Printer port LPT1"), with a driver provided by Microsoft, (c:\windows\system32\DRIVERS\parport.sys).  If I were to connect some dip switches and pull-up resistors to the data lines of the parallel port, can someone show me a sample powershell script that would read those switches--the byte established by those switches, and create a variable?  And If I were to connect some LEDs to the data lines of that port, can someone show me a sample powershell script that could send a byte to illuminate them?

Script to rename files

$
0
0

Hi I need a powershell script that renames a lot of .ftp files to .txt. Thanks

Can I use IExpress to pacakge a Batch file which calls a PS script ?

$
0
0

I used to package Batch file using IExpress.
The reason for this was that my co-worker would change my code, then complain that the
batch file not longer worked.  So packaging it into a nice EXE would prevent modification

Now that I'm starting to use PowerShell more and more I would like to share my scripts with my team
(I now work in a new company).  Since this place does not have any tools I used PS to create some.


I have a PS script which I can execute either by the console or calling it from a BatchFile.

I can package the batch file and PS script, however, when executed the screen comes up and goes away quick

I"ve tried other script with the same results

What am I doing wrong?

 

Thank you

 This is what I use in my batch file

PowerShell -NoProfile-ExecutionPolicy Bypass -Command"& '.\Get-RemoteInstalledApps.s1'"

This is a script which I call from my batch file

# Prompt Tech for the Hostname of the PC
$Workstation=Read-Host"Computer Name"

# NOTE: RemoteRegistry Service needs to run on a target system!
$Hive='LocalMachine'

# you can specify as many keys as you want as long as they are all in the same hive
$Key='SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
# you can specify as many value names as you want

$Value='DisplayName', 'DisplayVersion', 'Publisher', 'UninstallString'

# Enter computer name ensure you have access to the remote system adn remote registry is enabled
$ComputerName=$env:Workstation

# add the value "RegPath" which will contain the actual Registry path the value came from (since you can specify more than one
key)
$Value= @($Value) +'RegPath'

# now for each regkey you specified...
$Key | ForEach-Object {
# ...open the hive on the appropriate machine
$RegHive= [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $Workstation)

# ...open the key in that hive...
$RegKey=$RegHive.OpenSubKey($_)

# ...find names of all subkeys...
$RegKey.GetSubKeyNames() | ForEach-Object {
# ...open subkeys...
$SubKey=$RegKey.OpenSubKey($_)
# ...and read all the requested values from each subkey
# ...to store them, use Select-Object to create a simple new object
$returnValue= 1 | Select-Object-Property$Value

$Value
| ForEach-Object {
$returnValue.$_=$subkey.GetValue($_)
}

# ...add the current regkey path name
$returnValue.RegPath=$SubKey.Name

# return the values:
$returnValue

# close the subkey
$SubKey.Close()
}

# close the regkey
$RegKey.Close()
# close the hive
$RegHive.Close()

} | Out-GridView

Write-Host
"Press any key to continue ..."
$x=$host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Pipeline Variables

$
0
0

 

How do we assign the current value of one pipeline variable to another?

This works fine for me.

$hash = ((get-content .\hash.txt) -join "`n") | ConvertFrom-StringData

$hash.GetEnumerator() | % { 

$_.value 

}

Now how do I assign each value from the hash table to $_.UserPrincipalName in the following?

$hash = ((get-content .\hash.txt) -join "`n") | ConvertFrom-StringData

$MaxPassAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.days

$DaysToExpire = 25

$hash.GetEnumerator() | % { 

Get-ADUser -SearchBase (Get-ADRootDSE).defaultNamingContext -Filter {(Enabled -eq "True") -and (PasswordNeverExpires -eq "False") } -Properties PasswordLastSet | Select-Object givenname,SamAccountName,UserPrincipalName,@{Name="Expires";Expression={$MaxPassAge -((Get-Date) - ($_.PasswordLastSet)).days}} | Where-Object { $_.UserPrincipalName -eq $_.value } | Where-Object {$_.expires -gt 0 -AND $_.expires -le $DaysToExpire }

}

Any pointers are highly appreciated. Thanks

 

Form parameters

$
0
0

Hi,

I build a form with those parameters:

 

$form.Height=400

$form.Width=380

$form.Text="Box"

$form.FormBorderStyle=1

 

I know that there is a parameter that can open it on the center : $Form.StartPosition = "CenterScreen"

I need that the form will open on the right center of the screen.

 

Thanks

Lior 

 

 

Delete multiple files from reference file

$
0
0

Hello,

 

I would like to know the command to delete some files from  a particular directory. I have set of files which ends with .xml extension. I made a list of files to be deleted and saved it in a another reference file called tobedelete.txt.

How do I call PowerShell to delete the files that are listed in the file "tobedeleted.txt"

 

Please advise.

 

 

 

 

Merge Multiple .TXT files

$
0
0

Hello,

I need to merge multiple .txt files into one txt file. Can someone help with a powershell script for that? Also will it be possible to cut off the headers in each of the files and just have one? For example

File1.txt

© 2014 by Heathrow Capital, Inc.
HCMarketData 1234569 2233 FINAL    
G CCAVD 20141 9.4215
G FROOK 20141 9.8248
G RSVVP 20141 6.0302

File2.txt

© 2014 by Heathrow Capital, Inc.
HCMarketData 1234569 2233 FINAL    
R HHHH 20141 9.4215
R HHDG 20141 9.8248
R GGHD 20141 6.0302

Thanks,

 


richtextbox question

$
0
0

HI
when i am trying to copy from excel to the richtexbox. It is copying the tables also.
i just want it to get copied as the plain text.

Thanks

 

 

 

Cannot resume PowerShell Workflow (Job) after System Startup using Task Scheduler

$
0
0
Hello PowerShell gurus, I have a question that has kept me up the last two nights trying to find a solution. I hope someone can assist or provide some guidance. Thanks in advance for your assistance.

Description of Problem: Unable to resume a job (PowerShell Job) that is in a Suspended state using Task Scheduler(this job is running a PowerShell workflow). The Schedule Task runs successfully(I receive a message The operation completes successfully) and the PowerShell script executes to completion without any errors (from what I can see) but the job will not change state from Suspended to Resume. fyi: if I run the powershell script that the Task Scheduler executes from the POSH console using local administrator account (POSH console running in Admin Mode), the script runs successfully (ie, resumes the job) but that same script will not resume the job when running as a Schedule Task

Desired Behavior: Resume the PowerShell Job that is currently suspended by using Task Scheduler to execute a Powershell script at System Startup.

Troubleshooting:
Here are some things I've tried:
- the powershell script that the Schedule Task calls to resume the job, I inserted a "create directory" command in the script just so I can verify the script is being called and that works fine (ie, schedule task runs on time and creates a directory so I know the schedule task is actually executing the script)
- ran the script from the POSH admin console and it runs fine (the script resumes the job)
- i put a start/stop transcript in the script to capture any commands/output and added a "Get-Job" command (so I can see the suspended job). The transcript did not capture any Suspended Jobs. The Get-Job command runs successfully but transcript didn't pick up any jobs being suspended (nothing was captured in the transcript). I'm concerned that the PowerShell shell doesn't have visibility to the jobs on the system or simply the transcript isn't picking up Get-Job output
- I tried to hard code the Job name in the script (Resume-Job -name JobName) and my transcript log file reports that the Job isn't found even though I verified the job exists and currently is suspended.
- I tried running the task immediately from the Task Scheduler GUI and the message from Task Scheduler is the operations completed successfully but the job does not resume.


Details:
* new virtual machine (Windows 2012 R2) in Azure
* machine not on the domain (machine was newly created)

Down below is the schedule task information & powershell script
schedule task information (I built it with powershell)
 $resumeActionscript = '-WindowStyle Normal -NoLogo -NoProfile -File "C:\temp\resume-job.ps1"'
 $action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument $resumeActionscript
 $user = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest -LogonType ServiceAccount
 $trigger = New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:15
 $settings = New-ScheduledTaskSettingsSet
 $InputObj = New-ScheduledTask -Action $action -Principal $user -Trigger $trigger -Settings $settings
 Register-ScheduledTask ChangeSwapDiskTask -InputObject $InputObj
resume-job.ps1
start-transcript c:\temp\mylogfile.txt
get-job
write-output "get-job command executed"
resume-job -name TempStorageMove
stop-transcript

Particular String Bold in rich text box

$
0
0

$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(10,250)
$outputBox.Size = New-Object System.Drawing.Size(1160,590)
$outputBox.MultiLine = $True
$outputbox.font = "lucida console,9"
$outputBox.ScrollBars = "Vertical"
$outputbox.readonly = $true

I have an output box [richtextbox]. I have function that will display data into that. Is there any way we can have the selected string/word in bold ?

 

Getting MobileDeviceStats From O365

$
0
0

Hello,

I have a script that I have created to pull a list of all the Mobile devices and their statistics from our Office 365 environment.  When I execute this script manually, it completes without error and my report is generated.  When I create a scheduled job to run the script, it hangs at connecting to the MSOLservice.  I opened a ticket with O365 support and they reported that since it is a custom script they are unable to assist.  Have any of you ran into this type of issue with O365?  Are you able to run scheduled jobs to pull data on a regular basis?

Thanks in advance, here is the script.

 

<#
.Synopsis
Generates list of all MobileDeviceStats for devices in Office 365.

.DESCRIPTION
Generates list of all MobileDeviceStats for devices in Office 365.

.EXAMPLE
.\Get-MobileDeviceStats_v4.ps1

.NOTES
This script utilizes the ActiveDirectory PowerShell module, which must be available on the launching system.
This can be obtained from the Remote Server Administration Tools (RSAT) by Microsoft.
A RSAT for Windows 8 can be obtained here: http://www.microsoft.com/en-us/download/details.aspx?id=28972
#>

Import-Module MSOnlineExtended
Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 1 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has started.'
#STORED CREDENTIAL CODE
$AdminName="admin@domain.onmicrosoft.com"
$CredsFile="C:\ps\MobileDeviceStats\$AdminName-PowershellCreds.txt"
$FileExists=Test-Path$CredsFile
if ($FileExists-eq$false) {
Write-Host'Credential file not found. Enter your password:'-ForegroundColor'Yellow'
Read-Host-AsSecureString | ConvertFrom-SecureString | Out-File$CredsFile
$password=Get-Content$CredsFile | ConvertTo-SecureString
$Cred=New-Object-TypeNameSystem.Management.Automation.PSCredential-Argumentlist$AdminName,$password}
else
{Write-Host'Using your stored credential file'-ForegroundColor'Green'
$password=Get-Content$CredsFile | ConvertTo-SecureString
$Cred=New-Object-TypeNameSystem.Management.Automation.PSCredential-ArgumentList$AdminName,$password}

#Create remote session for O365 and Azure AD
$Session=New-PSSession-ConfigurationNameMicrosoft.Exchange-ConnectionUri https://ps.outlook.com/powershell/-Credential$Cred-Authentication'Basic'-AllowRedirection
Import-PSSession$Session
Import-Module MSOnline
Connect-MsolService-Credential$Cred

Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 2 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has initiated the remote session.'

#Set variables
$ExportedFilePath1="C:\ps\MobileDeviceStats\Reports\MobileDeviceStatistics_$((Get-Date).ToString('MM-dd-yyyy')).csv"
$Script:ExportedFile=$ExportedFilePath1

Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 3 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has successfully set the variables'

#Send email function
function sendmail
{
Send-MailMessage-To"user@domain.com" `
-From"PowerShell@domain.com" `
-Subject"Mobile Device Statistics" `
-Priority'Normal' `
-Attachments$Script:ExportedFile `
-Body"The attached CSV file contains the current list of Mobile Devices and their corresponding statistics.

Best Regards,
PowerShell

" `
-SmtpServersmtp.domain.com
}
#Send email update function
function sendupdate
{
Send-MailMessage-To"User2@domain.com" `
-From"PowerShell@domain.com" `
-Subject"Mobile Device Statistics" `
-Priority'Normal' `
-Body"The Get-MobileDeviceStats script has successfully completed and all remote sessions have been cleared.

Best Regards,
Your Friendly PowerShell Nerd

" `
-SmtpServersmtp.domain.com
}

Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 4 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, is beginning the data gathering process.'
#
#Add sleep http://support2.microsoft.com/kb/2881759
#
$MB=Get-MobileDevice-Resultsize unlimited
$MB | foreach {Get-MobileDeviceStatistics$_.identity; Start-Sleep-Milliseconds 2000} | Select-Object FirstSyncTime,LastPolicyUpdateTime,LastSyncAttemptTime,LastSuccessSync,DeviceType,DeviceID,DeviceModel,DeviceFriendlyName,DeviceOS,DeviceOSLanguage,Identity,DeviceAccessState,NumberOfFoldersSynced |
Export-Csv-NoTypeInformation$Script:ExportedFile

Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 5 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has completed the data gathering process.'

sendmail
Get-PSSession | Remove-PSSession
sendupdate
Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 6 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has completed.'

Copy-Item not working

$
0
0

 

 

 

 

 

 

In the following code, for some reason the copy-item event doesn't copy any of the event logs saved on a server.

The script is designed to make a copy of a server's event logs to a particular folder on that server and then those are copied to a central server in the server's subdirectory.  Another odd behavior with the copy-item is that I only want the files to copy to the destination but it also copies the folder structure from the source.

Thank you,

Kurt

**********************************************************************************

 

 

 

exit

 

 

 

Import-Module 

 

 

 

 ActiveDirectory

$LogsArchive

 

 

 

 

 

 

="\\server1\Utilities_f\event_log_save"

Function 

 

 

 

 

 

 

Get-Servers

{

 

 

 

$DomainControllers= @(

"domain1.local" 

"domain2.local"

)

 

 

$servers= @()  

foreach ($dcin$DomainControllers)

{

 

 

$servers+=Get-ADComputer-LDAPFilter"(&(objectcategory=computer)(OperatingSystem=*server*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(!(name=*w2k8*)))"-Server$dc|select Name

}

 

 

#$servers = $servers | sort Name 

$servers="server2" #testing  

return$servers

 

 

 

 

#end Get-Servers

Function 

 

 

 

 

 

Test-ComputerConnection

{

 

 

ForEach ($Computerin$Computers)

{

 

 

$Result=Get-WmiObject-Class win32_pingstatus -Filter"address='$computer'"  

If ($Result.Statuscode -eq 0)

{

 

 

if ($computer.length -ge 1)

{

 

 

Write-Host"+ Processing $Computer"  

Get-BackUpFolder

}

 

 

 

#end if 

else { "Skipping $computer .. not accessible" }

 

 

 

#end Foreach

 

 

 

#end Test-ComputerConnection

Function 

 

 

 

 

 

Get-BackUpFolder

{

 

 

$LocalPath="c$\ird_system\event_logs"  

$Folder="\\{0}\$LocalPath"-f$computer#"{1}_{0:MMddyymm}" -f [DateTime]::now, $computer  

New-Item"$LogsArchive\$computer"-type Directory -force|out-Null  

If (!(Test-Path"$Folder"))

{

 

 

New-Item"$Folder"-type Directory -force|out-Null

 

 

 

#end if 

else

{

 

 

Get-ChildItem$Folder-Include"*.ev*"-Recurse|Remove-Item

}

 

 

Backup-EventLogs($Folder)

 

 

 

#end Get-BackUpFolder

Function 

 

 

 

 

 

Backup-EventLogs

{

 

 

$Eventlogs=Get-WmiObject-Class Win32_NTEventLogFile -ComputerName$computer  

Foreach ($login$EventLogs)

{

 

 

$path="$Folder\{0}_{2:yyyyMMMMdd}-{1}.evt"-f$Computer, $log.LogFileName,[DateTime]::now  

$ErrBackup= ($log.BackupEventLog($path)).ReturnValue  

if ($clear)

{

 

 

if ($ErrBackup-eq 0)

{

 

 

$errClear= ($log.ClearEventLog()).ReturnValue

 

 

 

#end if 

else

{

 

 

"Unable to clear event log because backup failed" 

"Backup Error was "+$ErrBackup

 

 

 

#end else

 

 

 

#end if clear

 

 

 

#end foreach log 

Copy-EventLogsToArchive$Folder$computer

 

 

 

#end Backup-EventLogs

Function 

 

 

 

 

 

Copy-EventLogsToArchive($path, $computer)

{

 

 

$path=$path+"\$computer_*.*"  

Copy-Item-path"$path"-dest"$LogsArchive\$computer"-force-Recurse

 

 

 

# end Copy-EventLogsToArchive

# *** Entry Point To Script ***

$computers = Get-Servers

Test-ComputerConnection

 

check the admin$ of a machine?

$
0
0

I have a list of machines that I can ping but when I try to connect to them I can't.   I will open up Explorer and enter \\machinename\c$  or \\machinename\admin$  and it can't connect, yet I can ping them.

Using PowerShell can you mimic doing a \\machinename\admin$ ?  Yes, I can script it so it runs this from a command line, this is not want I want.  I want to know if there is a Powershell command to check the Admin$ or C$ on a remote machine?

 

 

Looping Problems

$
0
0

$NoPing = "Can't Ping Machine"
$erroractionpreference = “SilentlyContinue”
$a = New-Object -comobject Excel.Application
$a.visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = “Computer Name”
$c.Cells.Item(1,2) = “Computer OS Version”
$c.Cells.Item(1,3) = “Admin$”
$c.Cells.Item(1,4) = “Description”
$d = $c.UsedRange
$d.Interior.ColorIndex = 37 
$d.Font.ColorIndex = 1     
$d.Font.Bold = $True
$d.EntireColumn.AutoFit()
$intRow = 2
$NoPing = "Can't Ping Machine"

$machine = get-content 'c:\temp\tmp\ping\CMPing.txt'
foreach ($pc in $machine) {$getip = ((Test-Connection $pc -Count 1));
    if ($getip -like '*Source*')   {
           
     $computerOS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $pc | Select-Object -     ExpandProperty version;
            $admindollar = "Admin$ Reachable"
            $desc = (Get-ADComputer $pc -Properties Description).description
     $c.Cells.Item($intRow, 1) = $pc
            $c.Cells.Item($intRow, 2) = $computerOS
            $c.Cells.Item($intRow, 4) = $desc
            $intRow += 1
            $d.EntireColumn.AutoFit()  }

    Else {
        $c.Cells.Item($intRow, 1) = $pc;
        $c.Cells.Item($intRow, 4).Interior.ColorIndex = 6
        $c.Cells.Item($intRow, 4).Font.ColorIndex = 1  
        $c.Cells.Item($intRow, 4) = $NoPing
    }}

I have more code than this but this is the meat of the script.  Before this runs I have some code that opens Excel and creates the headers.

Here is my problem.   If the machine cannot be pinged then the ELSE should run and does.  The value for $NoPing is entered into cell .d but then 1 second later it is overwritten with the value from $desc.   I was watching this as it happened.   I see "Can't Ping Machine" and then 1 second later it is overwritten with the Description data from AD.

how come? 

 


HTML Body Extraction

$
0
0

Hi All,

Ok... so I got Powershell Studio for Christmas (cause I'm a sad geek lol) and I'm loving it. I wrote a program in it using powershell and .net. After fuzzing the stuffing out of it last night, I found an issue. Like a good boy I went to bed and promised to look into the problem today.

Today I awoke early, grabbed some tea and got stuck in...

...and nearly 12 hours later I'm still at it. I think I've googled the google out of google and I can't find an answer. I've tried regXing, I've tried splitting, I've tried offering my computer money.... I won't go on. Needless to say, I've had one of those days. I'm about to head off to bed. Today was my last day off, my brain aches and I have work in the morning!

Before I hit the sack and spend the first hour wondering what went wrong or even worse keeping myself awake by coding in my head (you've all done it too!), I thought I'd post up my problem. Hopefully some of you great guys n girls will leave me a few xmas gifts in the form of resolutions to my problem. So let me explain:

I wrote a program that does stuff. One of it's features is that in response to a given scenario it will pick up an html document on a hard drive and email it to me or another admin. The problem is, some email clients won't display the html email properly (including mine - stupid hotmail). I found a way around this by stripping all but the Body of the document out and then targetting the document. Now I want powershell to do this for me. Hey lets get even simpler... since any html document only has one body, I want powershell to look at any html document I point it towards and import the body, including the body tags.

I thought this would be simple, and probably is for you guys... but the issue has drained me!

Over to you! 

Many thanks and Merry Christmas!

Create line break in string/message

$
0
0

Hi guys, I'm using powershell to send an email which works fine, however I'd like to reformat the body a little.

I have a number of PC names in the array which I then join.

 

$merge = $PCs_in_array -join ", "

$body = @"

"Hello, these are the PCs in the list:"

$merge

"You will receive another email in 2hrs"

"@

 

The email looks like this at the moment:

Hello, these are the PCs in the list:

PC1, PC2, PC3, PC4

You will receive another email in 2hrs

 

What I'd like it look like:

Hello, these are the PCs in the list:

PC1

PC2

PC3

PC4

You will receive another email in 2hrs

 

How do I create that line break for each PC?

I need to create a script to install an executable on multiple remote 64 bit windows systems using PS

$
0
0

([WMICLASS]"\\$RemoteSystem\ROOT\CIMV2:win64_process").Create("cmd.exe /c C:/InstallSetup/Program.exe /s /v`" /qn")

write-host "Successfully installed" 

But even running this on a single system gives error

Where RemoteSystems =nyplab01 to nyplab10 ( 10 computer systems)

Path of the executable will be on my local desktop C Drive (C:/InstallSetup/Program.exe).

I also need to provide credentials for the admin for all windows.

there could be times where these is error incase the admin password changed by user then i need to display error because of this or maybe the system is 32 bit.

Now i am not sure of  installing this over the network would be good idea or first copy the executable and then run it locally on the remote computers.

HELP WITH how to extract last entry by pattern in files in directory

$
0
0

hello,

I have such isue:

Have directory with different logs. I need to select log with name daemon_DDMMYY.log (daemon_*.log) and extract just last entry with pattern "moneywrite" (if exists - not all files must contain such entry)
Aftewards I need to export in formated csv.


Im able to find all entries buth Im not able to find out how to use GET-CHILD Item in combination with foreach - to find just -last 1 entry in every file :(

My current sript which is able to find all entries in all files is :

cls
cd C:\log
$Out2 = ""
$Out2 = Select-String -path c:\log\daemon*.log -Pattern moneywrite -SimpleMatch|foreach{$_.Line}
$Out3 =$Out2 -replace "MoneyWrite: ","" -replace ", ",";" -replace '.log:','.log;' -replace " ",";"
$Out3 |Out-File C:\log\output2.csv
Import-Csv -Delimiter (';') -Path C:\log\output2.csv -Header date,time,R2€,R050C,R20,R5E,10C,20C,50C,1E,2E,5E,10E,20E,50E,100E |Export-Csv -NoTypeInformation  c:\log\form_out3.csv -Encoding ascii -Delimiter (';')


BTW: I need to short the time format (cut miliseconds)

raw data in daemon_DDMMYY.log is folow:

6.6.14 06:02:22.398 MoneyWrite: 201, 201, 96, 100, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0

Complex script for creating inbox rules

$
0
0

I am looking to create an inbox rule for all users in my environment. 

 

I am looking at users created in the last x days, and also verifying if the rule already exists. 

 

This is what I have so far, but there is no logic that checks if the rule exists. 


Appreciate the help!

 

Get-User -resultsize unlimited | where {$_.WhenCreated -gt (get-date).adddays(-7)} | foreach {new-inboxrule -Name Marketing -Mailbox $mbx.alias -SubjectContainsWords "[MARKETING]" -movetofolder ":\Junk E-Mail" -ExceptIfSubjectContainsWords ("RE: [MARKETING]","FWD: [MARKETING]") -StopProcessingRules $true -confirm:$false -Force}

Viewing all 10624 articles
Browse latest View live