Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

Help me to filter myCollection data

$
0
0

Hi,

I'm really stuckwithmy PowerShell output...
I have a piece of code that will fill my $OutputCollection.
When I print $OutputCollection to my screen I get something like:

ServerA KB3032359
ServerB KB3032359
ServerB KB3033889
ServerC KB3033889
ServerA KB3034196
ServerB KB3034196
ServerC KB3034196
ServerC KB890830
ServerA KB890830
ServerB KB890830
ServerA KB890830
ServerB KB890830
ServerA KB890830
ServerC KB890830
ServerA KB890830

What I need is to get an output (let's say as HTML page) that will result in:

  PATCH          ServerA   ServerB   ServerC   
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
KB3032359          x           x              -      
KB3033889          -           x              x     
KB3034196          x           -              -
KB890830            x           x             x

The members in my $OutputCollection are 'Server' and 'PATCH'

Can anybody tell me how to do this?

Thanks in advance!
LeonBns


delete old items older then 30 days from user mail box (exchange 2013)

$
0
0

Hi,

I'm trying to run this command (exchange 2013), delete mails that are older then 30 days:

[int]$numberOfDays=30

[DateTime]$date=[DateTime]::Now.Subtract([TimeSpan]::FromDays($numberOfDays))

Get-Mailbox -Identity $m |Search-Mailbox -SearchQuery {(Received -ge $date) } -DeleteContent

 

$m is the mailbox  identity.

$date is the date ,that mails that older or equal to  $date I want to delete.

 

I get this error:

Search-Mailbox : Could not load file or assembly 'Microsoft.Ceres.NlpBase.RichTypes, Version=16.0.0.0, Culture=neutral, PublicKeyToken

=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

At line:1 char:27

+ Get-Mailbox -Identity $m |Search-Mailbox -SearchQuery {(Received -ge $date) } -D ...

+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [Search-Mailbox], FileNotFoundException

    + FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.Exchange.Management.Tasks.SearchMailbox

need help with this issue.
Thanks,
Lior

 

Need to push a file to a remote machine (not in a domain)

$
0
0

Im a little new to Powershell.  Have scripted in VB and written some basic Apps in C# so I don't think what Im asking here is difficult in anyway.  Just need advice on how I should approach this in powershell. 

Scenario

HomeComputer

MyCloudServer 

 

(no workgroup or domains between the 2)

 

All I need to do is push a file to the server.  I've played with Invoked-Commands remotely and can makes changes on the server.  Example script here. 

    Try
    {
    Invoke-Command -ConnectionUri https://mycloudserver.net:5986 -ScriptBlock { Restart-    Service Themes } -credential TestUser
    }
    Catch
    {
     write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
     write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
    }
    Finally
    {
     write-host "Finished!"
     }
This all works.  But what if I want to copy a file from HomeComputer to MyCloudServer.  Copy-Item is executing on the remote computer it seems.  Is there a way I can pass in a reference back to my HomeComputer file while it has the remote powershell session with MyCloudServer running? 
Also been lookiing at Start-BitsTransfer but havent been able to got that to work. 
Start-BitsTransfer D:\testfile1.txt https://MyCloudServer.net:5986/testfolder/testfile1.txt -TransferType Upload -Authentication "" -Credential ""
I get requested URL doesn't exist on destination (which is obvious because Im trying to upload it).  The only thing that doesn't exist in the 'https://MyCloudServer.net:5986/testfolder/testfile1.txt' path is the testfile1.txt file
I feel like I'm missing a better way to do this.  Seems like it should be pretty simple. 
Appreciate any help.  Thanks!

How to run multithreaded Exchange powershell?

$
0
0

 

Does anyone have any examples of this?

I'd like to run this command on many computers simultaneously. If I can use code that is like c sharp thread start even better.

Thread t =newThread(newParameterizedThreadStart(myMethod));
t.Start(myParameterObject);

Thanks

ForEach ($server in $servers)

{

   Set-MailboxServer $server -DatabaseCopyActivationDisabledAndMoveNow $true;
    Set-MailboxServer $server -DatabaseCopyAutoActivationPolicy Blocked;

}

Conditional Operator Error PS Version 2.0

$
0
0

I am working on a script to terminate three processes for all users except IT and System accounts. I managed to get the script working just fine on my machine, but when I run it on the server I receive an error (see below).

I found that the issue is my conditional operator "-notin". This operator is not available in version 2.0 of PS, and unfortunately the server has no upgrade path to a new version of PS.

I would greatly appreciate any input on how I can work around this issue.

 

$SafeSysUsers = @("NT AUTHORITY\NETWORK SERVICE","NT AUTHORITY\LOCAL SERVICE","NT AUTHORITY\SYSTEM")


$SafeUsers = @("User1","User2","User3")


$SafeAll = [array]$SafeSysUsers + $SafeUsers


Get-WmiObject win32_process -Filter "name='cmd.exe' OR name='calc.exe' OR name='notepad.exe'" | %{IF($_.GetOwner().User -notin $SafeAll){$_.Terminate()}}

 

 

ERROR:

Your must provide a value expression on the right-hand side of the '-' operator.  At line:1 char:121

Unexpected token 'notin' in expression or statement. At line:1 char:122

Unexpected token 'SafeAll' in expression or statement. At line:1 char:128

 

 

simple script not working

$
0
0

I'm trying to pass a list of values through a simple command.  I have shortened my script to show where my error is.

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

clear

$computerlist = import-csv C:\SMALL.csv

foreach ($storepos in $computerlist)

{

Get-ACL $storepos

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

ERROR i'm getting:

Get-ACL : Cannot find path '@{storepos=\\computername\c$\SQLBackups\}'

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

SMALL.csv is this

storepos,

\\computername\c$\SQLBackups\,

\\computername_a\c$\SQLBackups\,

\\computername_b\c$\SQLBackups\,

\\computername_c\c$\SQLBackups\,

\\computername_d\c$\SQLBackups\,

 

Why doesn't the value $storepos = \\computername\c$\SQLBackups ?

 

Thanks in advance

Get Shares and Security Permissions

$
0
0

Hello,

I am looking to extract the shares and security permissions located across remote machines.

For eg,

\\server1\abc\

\\server2\xyz\

etc

I just want the shares and security permissions for the shares (abc and xyz as above) and not the subfolders.,i.e, who all have permissions with the access type. ( user john with read only access or user mark with read/write)

I tried icals,get-acl, etc but not able to generate desired output.

Could anyone plase help with this. Thanks

 

 

Adding one month to a date when the date is March2015 format

$
0
0

I'm trying to do this but it throws an error, if MMMMyyyy is April2015 I want to get May2015

Ta

Jonathan

$Plus1Month=((Get-Date-FormatMMMMyyyy).AddMonths(+1)).Date


Remove part of a output

$
0
0

Hi everybody,

 

I´m very close to going really crazy because I cant figure out whats wrong ...

I have the following query:

 

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

$User = Get-ADUser -Filter {name -like "ABC1*"} | sort-object -property name -descending | Select -Exp Name -First 1 | ft name

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

This is my result:

ABC1234

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

Then I try to make this:

$User.Remove(3,0)

but I get the following error message:

 

Fehler beim Aufrufen der Methode, da [Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData] keine Methode mit dem Namen "Remove" enthält.
In Zeile:1 Zeichen:1
+ $User.Remove(3,0)
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

 

What I need is, just to "cut" the numbers (in this example 1234) and increase this +1.

 

Can somebody please help me?

 

Many thanks

Best regards

Sempai0815

Select value in dropdown menu on website

$
0
0

Hi guys,

I want to automate an annoying task that has to be done every month. So what needs to happen is:

1. Open website with url.

2. Click on a hyperlink.

3. Select value in dropdown menu.

etc..

 

Steps 1 and 2 are working, I just can't get step 3 to work. When I inspect the site, the dropdown name is as follows:

<select name="host_id" onchange="applyGraphPreviewFilterChange(document.form_graph_view)">

<option value="0">Any</option>

<option value="46" selected="">SOME OPTION HERE</option>

Some other options are:

<option value="12">ANOTHER OPTION 1</option>

<option value="14">ANOTHER OPTION 2</option>

 

So what I want is to select option 14 for example. What I have now is:

$IE.document.getElementById(“host_id”).Value="ANOTHER OPTION 2"

also tested it with value 14. I get back:

You cannot call a method on a null-valued expression.

 

I hope you guys can help me out.

 

Kind regards,

Toeter

How to store text in AD attributes of type String(Unicode)

$
0
0

In our company, we store the name of the building in which an employee works in one of the ActiveDirectory attributes named extensionAttribute# where # represents a number form 1-15.  I want to be able to store the names of buildings in the AD attribute named "buildingName". According to the buildingName attribute in the MSDN library, the syntax is "String(Unicode)".

buildingName attribute - https://msdn.microsoft.com/en-us/library/ms675250(v=vs.85).aspx

String(Unicode) syntax - https://msdn.microsoft.com/en-us/library/ms684455(v=vs.85).aspx

When I try something that seems simple to write some text into this attribute such as

Set-QADUser jdoe -ObjectAttributes @{buildingName="My Building Name"}

I get an error that says "Set-QADUser : The requested operation did not satisfy one or more constraints associated with the class of the object."

 

I have been searching forums and code libraries for a solution to this issue, but I do not understand why I can't store string data into this attribute. I did try the following code snippets to try to convert the string to Unicode (and UTF-8) before I wrote to the buildingName attribute, but I still get the same error.

$text ="My Building Name"
$enc
=[System.Text.Encoding]::Unicode
# $enc = [System.Text.Encoding]::UTF8
$encText
= $enc.GetBytes($text)
$encText
Set-QADUser jdoe -ObjectAttributes@{buildingName=$encText}

Has anyone else had this issue or know how to overcome it? I can, of course, continue to use the extensionAttribute in which I currently have the data stored, but I really want to free it up and use the "buildingName" attribute.

Convert to HTML Ok but fails as an email body

$
0
0

Hi,

 

I wrote a script that goes through accounts that are being deleted to find applications where the users are not controlled by AD.  So they need to be removed from those systems.  I wanted to have the output be the body of an email so I create it as a text file, read each line in to a PSObject and then convert it to HTML.  It converts to HTML great, I can see that as I output the file to sanity check it was creating it properly.  The script errors though when I try to insert the $Fileline as the email body with the error message posted below the script.

Cheers

Jonathan

 

##Groups that need to be checked

Param(

  [array]$Applications= @("xa_AdobeWriter8","xa_AFLive","xa_APurchasingLive","xa_Bottomline","xa_Civica_ICON",`

  "xa_CrystalReports","xa_DMS","xa_DRS_Live","xa_ExperianCitizenView","xa_Flare","xa_FMS","xa_FrameworkiLive",`

  "xa_GCSXMail","xa_Highways_web","xa_InputAccel_Index7","xa_InputAccel_ValidationBen7","xa_InputAccel_ValidationCred7",`

  "xa_Lagan_ECM_Live","xa_Project2007","xa_RAISE","xa_Servitor_V8_Live","xa_SX3","xa_Uniform_Live","xa_Visio2007","xa_YFAS")

)

 

##Get the date for file naming

$Date=Get-Date-FormatMMMMyyyy

 

##Email Stuff

$From="You"

$To="Me"

$MailSever="It"

 

##Create an empty text file that contains the date in the filename

New-Item-PathC:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt-ItemTypeFile

 

 

##Add a comment to the top of the file explaining what it is for

Add-Content"C:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt"  "These are user accounts, of users who have left the business, whom used applications that are not"

Add-Content"C:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt"  "AD integrated. Therefore the deletion process does not remove them from these systems"

Add-Content"C:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt"  " "

Add-Content"C:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt"  "For the following applications create a support ticket for each and assign to the relevant team"

Add-Content"C:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt"  "For an application such as Raise or Uniform email the relevant administrator of that application"

 

##Loop through each security group and find users who are in the ToProcess Deletion OU and add to the $Date-Applications.txt file

##Add the name of the application, list the users discovered and separate each chunk with a row of dashes

Foreach ($ain$Applications){

Add-Content"C:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt"  "----------------------------------"

Add-Content"C:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt"$a

Get-ADGroupMember-Identity$a|where-object {$_.distinguishedName -like"*OU=ToProcess,OU=Staff-Ex,OU=Users,OU=Here,DC=There,DC=EveryWhere,DC=uk"}`

|Select-Object-ExpandPropertyName `

|Add-Content"C:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt"

}

 

##Create a PSObject for later convertion to HTML

$File=Get-ContentC:\PurgeUserRecords\ApplicationUsers\$Date-Applications.txt

$FileLine= @()

Foreach ($Linein$File) {

 $MyObject=New-Object-TypeNamePSObject

 Add-Member-InputObject$MyObject-TypeNoteProperty-NameApplications-Value$Line

 $FileLine+=$MyObject

}

 

##Convert $FileLine to HTML and save as a file (Proves valid output as file can be opened in a browser)

$FileLine|ConvertTo-Html|Out-FileC:\PurgeUserRecords\ApplicationUsers\$Date-Applications.html

 

##Trying to convert to a format that I can insert into an email

$FileLine=$FileLine|ConvertTo-Html-Fragment

 

##Send an email in HTML format with the $FileLine data as the body

Send-MailMessage-From$From-Subject"User to Application Matching for Ex-Staff $date"-To$To-Body$FileLine-BodyAsHtml-SmtpServer$MailServer

 

 

 

 

PS U:\> $Error[0]

Send-MailMessage : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Body'. Specified method is not supported.

At C:\scripts\MonthlyPurgeApplicationCheck.ps1:54 char:140

+ ... *.***.uk -Body $FileLine -BodyAsHtml -SmtpServer ***.***.***.uk

+                    ~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException

    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.SendMailMessage

 

 

Powershell script for sending a file via bluetooth

$
0
0

I'd like to write a Powershell script to transfer a specific file from my Windows 8 laptop to my Android phone via bluetooth.
I often edit my todo list (text file) on my laptop when I'm on the road (often without internet access)
 and I want an easy way to send this file to my phone via bluetooth. My laptop and Android phone are already paired via bluetooth.
To do this manually requires many clicks and steps.
Thanks

Need help on Script

$
0
0

Good Morning,

I have script that when ypu have a user name goes out and looks up all the machines the user is connected with and scans the machines to see which one the user is currently logged on to and returns the value of the which they are logged into. When I run the it never recognizes the computer the user is logged on to and I know that one of the computers it returns is the one they are logged to currently. I think it has to do with the line if ($CurrentUser -eq $user). I am thinking that it comparing a object to a string and is failing. Any help would be appreciated.

Thanks

function Get-UserLogonComputer
{
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Low')]
Param
(
# The enter the username for this parameter
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
Position=0)]
[string[]]$UserName
)
Begin
{
}
Process
{
# Add a new line for readability
Write-Host ""
# Loop through each user in the username array
foreach ($user in $UserName) {
# Print the username we are currently looking up
Write-Host $user
# Added string formatting at the end to get rid of the Name header
$PCList = Get-ADComputer -Filter {ManagedBy -eq $user} | Select Name
$PCLIst
foreach ($PC in $PCList) {
if (Test-Connection -ComputerName $($PC.Name) -Count 1 -Quiet) {
#The following command looks Uses WMI to get the active user
$CurrentUser = Get-WMIObject -Class Win32_ComputerSystem -Computername $($PC.Name) | Select UserName
$CurrentUser.username.ToLower()
$CurrentUser.ToString()
if ($CurrentUser -eq $user) {
Write-Host "The users current logged on machine is:" $($PC.Name)
}
Else {
Write-Host "Current user is not logged on to:" $($PC.Name)
}
}
Else {
Write-Host "Can Not Connect to" $($PC.Name)
}

}
}

}
End
{
}
}

Migrating from UMRA to Powershell

$
0
0

We currently use UMRA to create and modify many scripts for creating new AD users, security settings, email, etc.  I exported one script in XML format and I am trying to convert to a powershell script and run to see if it works.  The script uses a CSV file to create new users, etc.  Can someone direct me on where to start with this process?  Thank you.


Filter example?

$
0
0

Can someone explain to me how to filter AD results based on  

-Filter { GivenName -eq Surname }

I am trying to get a list of accounts that have the same first and last name.  I get a syntax error with this filter and I don't know what is wrong.

I'm still learning so thanks in advance for any input you provide.

Is it possibleto find Microsoft SQL Server information remotely without logging on to SQL it self

$
0
0

Hello,

I need to run a powershell script against my environment collecting various pieces of Server information into a single csv. The particular piece I am having trouble with is SQL Server Editions.

My server environment contains Microsoft SQL 2000 - 2012 servers and in some cases multiple instances per server. Also I do not have permissions to connect to many servers as well as others do not have or have running a SQL browser service.

I have the following code that I use to grab actual SQL servers that were:

$Service = Get-WmiObject -Class Win32_Service -ComputerName $Computer | Select Caption, State, PathName | ? {$_.PathName -like "*sqlservr.exe*" -and $_.Caption -notlike "*$*" -and $_.Caption -notlike "*#*"}

Using the Get-ItemProperty for sqlservr.exe I can figure out the version number per service,

But I can't seem to find a way to get the edition of the SQL Instance...

Thank you for your help

 

 

 

 

 

 

 

Need Help Summarizing a list of AD accounts

$
0
0

Basically i need to summarize a list of accounts in the below format to this TestAccount01-04:

TestAccount01

TestAccount02

TestAccount03

TestAccount04

 

I tried messing around some but was not successful. The accounts are stored in avariable ran by this command:

$accounts = Get-ADUser -Filter {samaccountname -like "TestAccount*"} -searchbase "OU=xxx,OU=xxx,OU=xxx,dc=xxx,dc=xxx,dc=com" | select name

 Any ideas on how to do this?

Powershell expert in Azure

$
0
0

I wanna excel in Powershell for Azure and thus looking for an reference book or article that can help to be an expertz

louis vuitton fmtv bhoo fjvt

$
0
0

屁股生動傳情,風情萬千。屁股細膩,不易長痘。屁股嚴肅,不拘言笑。屁股莊重,大氣有福相。屁股低調,永遠在後,深藏不露。屁股節儉,不用花錢保養也白淨。屁股和諧,既一分為二,又合二為一。凌雲氣結,第一次聽這麼齷齪的說法,她哼道:屁股這麼好,你還要臉幹什麼? adidas官方網留著臉,主要是怕你認不出來 adidas慢跑鞋 。劉英楠笑呵呵的說:要不你仔細看看 adidas慢跑鞋 的屁股,好好記住 adidas慢跑鞋 屁股的樣子,以後 adidas慢跑鞋 就不要臉了!

凌雲猛的轉過身,臉蛋紅紅,宛如三月桃花嬌媚誘人,她狠狠的瞪了劉英楠一樣,沒好氣的說道。劉英楠無所謂的笑笑,和這種純情的小妞交流,就得無恥一點,流氓一點,讓她跟著 adidas originals的節奏,但她習慣了 adidas慢跑鞋 的無恥和流氓習性,到時候 adidas慢跑鞋 偷偷的摸一下,捏一下,揉一下,她也能接受。可 adidas慢跑鞋 要是和她一樣單純,老老實實,中規中矩的交流,先用眼神交流,談人生談理想談未來,半年後無意中一下碰了一下手,有感而發才拉手,再過半年,因為看一場言情電影,在弱弱的提出親臉蛋一下的要求,等到能xxoo的時候,估計也到更年期了!

凌雲實在拿 adidas慢跑鞋沒轍了,也不堪忍受 adidas慢跑鞋 的調戲,搬出了保鏢。哪知劉英楠葷素不計,道:強壯的男人不一定有實力,既要壯,又要有持久性,還要有技巧。凌雲很純潔,聽不懂 adidas慢跑鞋 的話,但看 adidas慢跑鞋 猥瑣的臉也知道不是好話。她白了 adidas慢跑鞋 一眼,眼光一瞥,又看到了那件雪白陰森的長裙,空氣中還瀰漫著童子尿的味道,這讓凌雲又恐慌又鬱悶,她忍不住道:這到底是怎麼回事兒?

Viewing all 6937 articles
Browse latest View live