Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

remotely checking the server port is open or not

$
0
0

I have a project where i need to do the below

From ServerA  telnet to mulitiple server on a specific port.

ex:

Source = Server A

Destination = ServerB,ServerC,ServerD,ServerE
Port = 80

Usually i have to login to Server A and in the cmd issue a telnet [ telnet ServerB 80]..[telnet ServerC 80]...so on

its Ok if i have only one source server. As i have many..its very difficult.

======

$socket = new-object Net.Sockets.TcpClient
$socket.Connect("ServerA",80)
$socket.Connected

=====

But as there are mulitple Source SErvers from where i have to check..i have to login to all the servers to execute the above ps code.

remoting is not enabled.

Is there a way i can run the above ps code from one server ...like i am executing on source server and get the output.

====

Sorry if its confusing. Please reply back if you didn't understood anything.


How to replace sting value with variable.....

$
0
0

In the wonderful world of Exchange 2010 running the command below is successful evaluating and exporting email messages with the subject of "ozzzzzy". 

New-MailboxExportRequest -Mailbox $dlist.alias -Contentfilter {(subject -like "ozzzzy")} -FilePath $PSTpth }

So in my effort to build a GUI to this command, replacing "ozzzzzy" with a string variable from a textbox has proven in-effective. (Doesn't work) 

I have tried a multitude of different methods to manipulate this string / texbox value. I must be missing something very  fundamental about PowerShell that's not allowing my to substitute this parameter / value. 

I've tried this local to the Exchange box as well as remote. 

Your idea's are greatly appreciated. Thank you.....


Djoe

Reference Column in Datatable

$
0
0

Hi

I have the following code below and would like to know how I can reference the column UserName in the FOREACH statement so I can manipulate the value.  

Many thanks

$SqlConnectionString = "Data Source=HALLW2678\SQL2012ENT;Initial Catalog=Printers;Trusted_Connection=Yes"
$SqlConnection = new-object system.data.SqlClient.SqlConnection($SqlConnectionString);
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = ("SELECT UserName FROM dbo.Fujitsu")
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$data = $dataset.Tables[0]

foreach ($dataitem in $data.Rows)
{	
	
	Write-Host "Name is: " $dataitem
}

Telnet using powershell

$
0
0

I have list of servers, which should telnet to an ip address to port 12232, and display the result as Yes, IF the server can telnet to IP address, or NO, when it fails.

How do I write a script in powershell? 

For Ex:-

trying to telnet 127.0.0.1 80 from Server 1, it should display yes or no, depends upon the response.

How do I have the same thing in powershell?

Thanks for the help.

Merging multiple Large (500 MB+) CSV files into one to comparing it to another bigger CSV files

$
0
0

Hi Experts,

I have a requirement to combine multiple large CSV files (500 MB+) files into one, it is working super fine with csv files of smaller size (till 200 MB) and doing what I want to do i.e. merge all and create a single csv file with single header and data from all CSVs. My system configuration is Windows XP with 3GB RAM. 

The error that I get is the out of memory exception on files with 200+ MB, Is there any way I can change the memory allocation to powershell as 3 GB is fine for working with 500 MB+ files ?

Also, is there anyother way to do this process.

Currently I am using 

Import-Csv processes.csv

and Export-Csv to export csv in a merged CSV,

Thanks in Advance.

Prajesh



([adsisearcher]"(&(objectClass=person)(objectClass=user)(displayname=$DisplayName))").FindAll().properties

$
0
0

$DisplayName="ahamed Asif x"
([adsisearcher]"(&(objectClass=person)(objectClass=user)(displayname=$DisplayName))").FindAll().properties

Comes empty why?

Take ownership of a registry key, and change permissions

$
0
0

Hello,

I am writing a powershell script to configure a W2008-R2 Server. In one of the steps, I need to take ownership of an existing registry key, and then give full control permissions to the administrators.

I have done this:

$acl= Get-Acl $key$me=[System.Security.Principal.NTAccount]"$env:userdomain\$env:username"$acl.SetOwner($me)$person=[System.Security.Principal.NTAccount]"Administrators"$access=[System.Security.AccessControl.RegistryRights]"FullControl"$inheritance=[System.Security.AccessControl.InheritanceFlags]"None"$propagation=[System.Security.AccessControl.PropagationFlags]"None"$type=[System.Security.AccessControl.AccessControlType]"Allow"$rule= New-Object System.Security.AccessControl.RegistryAccessRule($person,$access,$inheritance,$propagation,$type)$acl.AddAccessRule($rule)

 Set-Acl $key$acl

But it fails in "set-acl" command, with the message "Set-Acl : Requested registry access is not allowed."

 

Any ideas of how to do this? or if it is even possible?

 

Thank you!

Clearing Out Bleeding Scripts when using GWMI

$
0
0

OK, so I may be in the minority, but I don't like when the scripts I write bleed all over my screen.  And when I use GWMI, I find that they bleed more often than not.  See, I often work with systems that I don't have access to, and when I use GWMI (even with the ever popular "-ErrorAction SIlentlyContinue", a personal friend of mine), my scripts leave blood all over the screen.  So, I went out to figure out the issue.  It appears that the error returned by GWMI with you don't have access to a computer is not returned at the PowerShell level, but through the OS itself.  So when you have a group of computers and run something like:

Get-WmiObject -computer $Server Win32_OperatingSystem -ErrorAction SilentlyContinue

You get something back like:

Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:1 char:14
+ Get-WmiObject <<<<  -computer $Server Win32_OperatingSystem
    + CategoryInfo          : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

(OK, yeah, it's exactly like that, thanks to cut and paste and a bit of formatting.) Anyway, since I have a script that calls WMI for OS info, disk info, boot info, ... in fact, info about several other things, all this bleeding on my screen was giving me heartaches.

So I went about trying to find a way around it.  Turns out that other commands fail, but catch the issue at a higher level:  for example, Get-ChildItem gives "Cannot find path '\\ServerName\c$' because it does not exist." and works with -ErrorAction.  While this would work, what if the item really doesn't exist and Windows is installed on the D: drive?  That wouldn't help much, and I wanted to find a way to shunt my WMI requests only if the server had an access denied.

I finally found that the DOS command running "net use \\ServerName\C$" will return the denied access error, and you can keep it from bleeding on the screen, but you have to do it wisely.  First, you need to use what .Net calls "[Diagnostics.Process] Start()".  To use this, I created the following function:

function Chk-ServerAccess {
    param($Server, $Share)
    $PSAccessTest = New-Object System.Diagnostics.Process
    $PSAccessTest.StartInfo.FileName = "NET"
    $PSAccessTest.StartInfo.Arguments = ' VIEW \\'+ $Server + '\' + $Share+ '$'
    $PSAccessTest.StartInfo.RedirectStandardError = $true
    $PSAccessTest.StartInfo.UseShellExecute = $FALSE
    $PSAccessTest.Start() | Out-Null
    $StdErr = $PSAccessTest.StandardError.ReadToEnd()
    -not ($StdErr -match 'Access is denied.')
} # Chk-ServerAccess

 

This function returns Boolean True if you can access the server and Boolean false if you can't.  You initialize a variable of type "System.Diagnostics.Process".  Then you set the command (file name) as "NET" (ignoring the fact this isn't really a file, but an internal Windows OS command).  Build the arguments using the variable for your server name and an admin share you should be able to access on the server (you can also build it with "VIEW\\$Server\$Share`$", if you prefer expanding variables inside the text string).  Make sure you redirect standard error - we don't really care about standard output, but we need to catch the error.  We also need to make sure we set UseShellExecute to false so we can redirect any output (including errors).

Once we are ready, we run the command by starting it ($PSAccessTest.Start() | Out-Null) - note that we pipe this to Out-Null - we do this so we don't have a spurious "True" returned by our script accidentally. Once run, we capture the error output into a variable ($StdErr, in this case) and test to see if it matches 'Access is denied'.  If it doesn't, we return true, meaning you have rights to the admin share you wish to access on the server.  And it doesn't throw any blood to the screen - making it possible to then run your GWMI commands without having your friends wondering what your script is doing to their servers.

I just love when you start a script and it ends with nothing but white output on the screen.  Hope this helps someone else out there ...

Will Martin


Detect mapped drive path and disconnect if exists

$
0
0

Hello!

My issue is that a former admin somehow managed to get a mapped drive onto several hundred machines. The user under which this mapped drive was created is causing us a huge headache. What I'm looking to do is to write a script that basically looks at the path of the mapped drives, and if a drive is mapped to a certain location, disconnect it.

For instance:

Z is mapped to \\server01\share01

If Z is indeed mapped to \\server01\share01 then disconnect it. If drive Z exists, but is not mapped to \\server01\share01 then leave it alone.

I came across the Test-Path and Get-PSDrive commands, but I couldn't figure out how to set the Root from Get-PSDrive as a variable, or the Providername from the WMI equivalent.

Using Registry UninstallString to remove software

$
0
0

I have some code that will search the registry for specified software, and return the UninstallString. I am trying to make this into a script that will uninstall various software. For example, this:

Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall,
HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall  |
    Get-ItemProperty |
    Where-Object {$._DisplayName -match "java" |
    Select-Object -Property DisplayName, UninstallString

when run will return this:

DisplayName                             UninstallString                                                   
-----------                             ---------------                                                   
Java 7 Update 40 (64-bit) 		MsiExec.exe /X{26A24AE4-039D-4CA4-87B4-2F86417040FF} 
Java 7 Update 40 			MsiExec.exe /X{26A24AE4-039D-4CA4-87B4-2F83217040FF}  

I'm still not sure how to call the uninstallstring though. This works with Get-WmiObject, but is incredibly slow:

$app = Get-WmiObject -Class Win32_Product | Where-Object { 
$_.Name -match "Java"    }
$app.Uninstall()
So how can you call the uninstallstring to execute and remove the program when using the Get-ChildItem method?

Export multiple variables to csv

$
0
0

I am a bit lost in adding my results to a csv.

I tried several way, but the objects are not written to csv.

##########################################################
# Var
##########################################################
$wdb = Read-Host "Enter Mailbox Database"
##########################################################
add-pssnapin microsoft.exchange.management.powershell.e2010
Import-Module ActiveDirectory
$ADSettings = Get-adserversettings
If ($AdSettings.ViewEntireForest -ne $true) {
	Set-AdServerSettings -ViewEntireForest $true
	}
##########################################################
function Get-ADUserLastLogon([string]$userName)
{
  $dcs = Get-ADDomainController -Filter {Name -like "*"}
  $time = 0
  foreach($dc in $dcs)
  { 
    $hostname = $dc.HostName
    $user = Get-ADUser $userName | Get-ADObject -Properties lastLogon 
    if($user.LastLogon -gt $time) 
    {
      $time = $user.LastLogon
    }
  }
  $dt = [DateTime]::FromFileTime($time)
  $AdvStats = Get-mailbox $U.SamAccountName | Get-MailboxStatistics
  Write-Host "$($username) last logged on at: $($dt), the Mailbox was last accessed on $($AdvStats.LastLogOffTime) by $($AdvStats.LastLoggedOnUserAccount).
  The mailboxsize is $($Advstats.TotalItemSize) and contains $($AdvStats.ItemCount)."
	  $Item = { 
		  @{
			  $Item.UserName = $userName
			  $Item.LastLogonAD = $dt
			  $Item.LastMailboxLogoff = $AdvStats.LastLogOffTime
			  $Item.LastLoggedOnMailbox = $AdvStats.LastLoggedOnUserAccount
			  $Item.MailboxTotalItemsize = $Advstats.TotalItemSize
			  $Item.MailboxItemCount = $AdvStats.ItemCount
			}
	  	}
	$Collection = $Item.toString()
  }
##########################################################
$DisAcc = Get-Mailbox -database $wdb -resultsize Unlimited | ? {$_.Identity -like "*/Disabled_Accounts/*"}
Foreach ($U in $DisAcc) {Get-AdUserLastLogon $U.SamAccountName}
$Collection | Export-Csv -Path C:\Temp\DisabledAcc_$($wdb).csv
##########################################################
# End
##########################################################

I also tried with select-Object ... | Export-csv -Path ... -append


Answers provided are coming from personal experience, and come with no warranty of success. I as everybody else do make mistakes.

cmdlet equivalent to c# "System.Diagnostics.Trace.Write"

$
0
0

hi, I'm writing a script and I want its output to be picked up by the debugview utility, in C# I'd achieve this by using System.Diagnostics.Trace.Write (or System.Diagnostics.Debug.Write). Please can you tell me the powershell way to achieve the same thing.

Thanks

Try / Catch

$
0
0

Hi all, 

I have used this in the past but not having much success this time. In the below a Failures.txt file is created but is blank...

BackupTarget = "\\server\share"
$TodaysDate = $((Get-Date).ToString('dd-MM-yyyy'))
Import-Module ActiveDirectory

# Get a list of print servers to be backed up
$Servers = Get-ADComputer -Filter * -SearchBase "OU=PrintServers,DC=dev,DC=local"

ForEach ( $Server in $Servers ) { 
	# Capture the server name for use with error reporting
	$CatchHostname = $Server.Name
	Try {
		# Get the servers hostname and store it as a variable
		$HostName = $Server.Name
		# See if the server already has a backup. If so rename the previous backup
		If (Test-Path -Path $BackupTarget\$HostName.printerExport) {
			Rename-Item "$BackupTarget\$HostName.printerExport" "$BackupTarget\$HostName.printerExportold"
		}
		# Perform the backup
		Invoke-Expression 'C:\Windows\System32\spool\tools\PrintBrm.exe -s \\$HostName -b -o force -f "$BackupTarget\$HostName.printerExport"'
		# Check to see if the new backup file exists, if do delete the older backup
		If (Test-Path -Path $BackupTarget\$HostName.printerExport) {
		Remove-Item "$BackupTarget\$HostName.printerExportold"
		}
	}
	Catch {
		$FailedServers += "$CatchHostname @ $TodaysDate"
	}
	$FailedServers | Out-File "$BackupTarget\Failures.txt" -Append
}

If I move the Out-File command into the Catch section I get no Failures.txt file being created at all.

I am trying to generate a list of servers that have failed to export their printer configuration.

Thanks.

Connect-IscsiTarget AuthenticationType parameter is case sensitive

$
0
0

Hi Folks:

The 'AuthenticationType' parameter of the Connect-IscsiTarget cmdlet must be UPPERCASE to work.

The documentation at 'http://technet.microsoft.com/en-us/library/hh826098.aspx' for the parameter reads:

-AuthenticationType<String>
Specifies the type of authentication to use when logging into the target. Valid values are None (the default), OneWayCHAP, and MutualCHAP.

Entering the values as written for OneWayCHAP and MutualCHAP returns an authentication error. However, if the values are entered in uppercase ONEWAYCHAP and MUTUALCHAP, the cmdlet succeeds. Bruce Langworthy's article 'Managing iSCSI Initiator connections with Windows PowerShell on Windows Server 2012' at 'http://blogs.msdn.com/b/san/archive/2012/07/31/managing-iscsi-initiator-connections-with-windows-powershell-on-windows-server-2012.aspx' provided insight into the problem when he specified the authentication type as ONEWAYCHAP instead of mixed case. The problem occurs in both PS versions 3.0 and 4.0.

Side Note: The command New-IscsiTargetPortal also uses the 'AuthenticationType' parameter and appears to work when a mixed-case authentication type is passed (as documented).

Here's how to replicate the problem

PS> get-iscsitarget | connect-iscsitarget -targetportaladdress fd8e:c88b:b9d7:1::58 -ispersistent $true -initiatorportaladdress fd8e:c88b:b9d7:0001:0000:0000:0000:0061%0 -authenticationtype MutualCHAP -chapusername vApps -chapsecret <mysecret> -ismultipathenabled $true

connect-iscsitarget : Authentication Failure.
At line:1 char:19
+ get-iscsitarget | connect-iscsitarget -targetportaladdress fd8e:c88b:b9d7:1::58  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (MSFT_iSCSITarget:ROOT/Microsoft/...SFT_iSCSITarget) [Connect-IscsiTarget], CimException
    + FullyQualifiedErrorId : HRESULT 0xefff0009,Connect-IscsiTarget

# Entering authentication type in uppercase
PS> get-iscsitarget | connect-iscsitarget -targetportaladdress fd8e:c88b:b9d7:1::58 -ispersistent $true -initiatorportaladdress fd8e:c88b:b9d7:0001:0000:0000:0000:0061%0 -authenticationtypeMUTUALCHAP -chapusername vApps -chapsecret <mysecret> -ismultipathenabled $true

Succeeds!

I reported this to Microsoft Connect, but thought I'd post it on this forum in case someone else runs into this same issue. Confirmation of the problem would be appreciated. Thanks!

Have a GREAT DAY!!

Shaun  

MSSQL 2012 Backup Timeout

$
0
0

Dear Microsoft Technet Team,

we have an issue regarding creating a Backup using Powershell. Each time we try backing up on special database we get into a timeout after 10 minutes (default connection timeout is as far as we know about 600 seconds). Creating a database backup using the MSSQL Management Studio it works without any problems. Unfortunately we haven't found the option changing the default timeout. Of course on our other databases which require less time to create our backup there is no problem. We hope you may have any helping advice. Thank you in advance. Please let us know if you need any further information.

Powershell command: qlps Backup-SqlDatabase -Server db02 -BackupFile E:\\bacula-tmp\\backup-oewsaas.sql -Database oewsaas -Checksum

Backup-SqlDatabase : Timeout ist abgelaufen. Das Zeitlimit wurde vor dem Beenden des Vorgangs überschritten oder der Server reagiert nicht.
Bei Zeile:1 Zeichen:19
+ Backup-SqlDatabase <<<<  -Server db02 -BackupFile E:\bacula-tmp\backup-oewsaas.sql -Database oewsaas -Checksum
    + CategoryInfo          : InvalidOperation: (:) [Backup-SqlDatabase], SqlException
    + FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.BackupSqlDatabaseCommand

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

Event Log:
2014-03-04 08:21:41.89             Fehler: 3041, Schweregrad: 16, Status: 1.
2014-03-04 08:21:41.89             BACKUP failed to complete the command BACKUP DATABASE oewsaas. Check the backup application log for detailed messages.

Best Regards,

Paul Becker


Cert error when trying to install WMF 4.0

$
0
0

We have two different Servers both running Server 2012 and are fully patched. When trying to install WMF/Powershell 4 we get the following error:

One Server has TFS Server 2012  Installed(Server1). The other one has TFS Server 2013 Installed(Server2). Both have SQL Server 2012 SP1 installed. Server1 has 3.5 & 4.5 framework installed. Server2 has framework 3.5 & 4.5.1 installed. I've tried downloading the installer multiple times with multiple browsers (thinking it got corrupted) but no go. Searching around i tried a few things....adding WIF 3.5 but nothing has worked.

Registry Uninstall of 3rd party applications

$
0
0
While browsing the forums I found this thread. I'm wondering if it is possible to modify it so it will look into a CSV file that contains the names of the applications I want to remove?

If this is helpful please mark it so. Also if this solved your problem mark as answer.

how to add multiple users with passwords and groups

$
0
0
we are a college adding students to 365 education and we need add their password, license and put them in a group. I believe it can be done by powershell. Does anyone have a script or how would it be written.

Set-ADUser to modify givenname and surname attributes based upon displayname in powershell

$
0
0
Hello to everyone,

i'm trying to restore AD Users records to a proper shape.

More in details,current AD users records contains only the displayname and the other mandatory attributes,everything is lacking (like givenname,surname,telephonenumber,address,city,country ecc. ecc.)

Actuallly,i'm trying to achieve three results:

1 - Populate at least the Givenname and Surname from the displayname attribute (since this one is "name-space-surname")

2 - Populate the address,country,city based on the OU's membership

3 - populate the phonenumber attribute from a csv that i'm trying to build from mixing various others excel files

I need help for the first one.

An example of a displayname that i have is like:

"test1 Test2"

What i'm trying to do is to extract "test1"and assign as "Givenname" and extract "test2" and assign it as "surname"

How can i use Set-aduser to achieve what i want?

Thanks for any reply


How to get excel data from a single cell?

$
0
0

Hi, I'm looking to take a group of 31 excel workbooks, loop through them, get the value from the same field (M7), which is of the General format, and get a sum total for all of the workbooks.

What I'm stuck on is how to get the data from excel.  From a bit of web surfing so far, I have:

$workbook = $excel.Workbooks.Open("C:\Path\To\File\1_3_14.xlsx")
$workbook.sheets.item(1).activate()
$WorkbookTotal=$workbook.Worksheets.item(1).range("M7").value
$WorkbookTotal

When I run this, I don't get a value, I just get the following, but do not get a number.  Even if I change the field format from general to number, I get the same:

$WorkbookTotal  (I have tired $WorkbookTotal.Value, and get the same)

IsSettable          : True
IsGettable          : True
OverloadDefinitions : {Variant Value (Variant)}
TypeNameOfValue     : System.Object
MemberType          : ParameterizedProperty
Value               : Variant Value (Variant) {get} {set}
Name                : Value
IsInstance          : True

Can anyone point me in the right direction or tell me a better way?

As always, help is greatly appreciated.



Thanks,
Kevin

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>