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

Help wanted by app-v powershell

$
0
0

Hello, i want that app-v 5 packages that are not used anymore being cleaned up from my cache without clearing the whole cache.

i know this must be possible with powershell, im am just a newbie with powershell, could somebody help me?

i was thinking te following must be possible for powershell.

first check if the content share is reachable (test-connection), if not stop script.
then (get-appvclientpackage) and use the path value to test if the file is still there on the content share (test-path), it should return "True" or "False" 
when the result is "False" then remove that specific package (remove-appvclientpackage), if the result is "True" do nothing.

i think for somebody with powershell knowledge this should not be to hard to create a script to do this.

please help.
if you need more information, i will provide it.

Thanks in advance,

Johnny Bos

the result from get-appvclientpackage is for example

PackageId            : 37cf1ec2-faab-4e03-aa63-79a6e2b84ae7
VersionId            : 5238b914-7327-465d-935c-fe0cbf559158
Name                 : Microsoft Office 15 ProPlusVolume_VisioProVolume_ProjectProVolume_en-us_x64
Version              : 0.0.0.0
Path                 :\\servername\Content\office 2013\ProPlusVolume_VisioProVolume_ProjectProVolume_en-us_x64.appv
IsPublishedToUser    : True
UserPending          : False
IsPublishedGlobally  : False
GlobalPending        : False
InUse                : False
InUseByCurrentUser   : False
PackageSize          : 2839157873
PercentLoaded        : 100
IsLoading            : False
HasAssetIntelligence : True



PowerShell script not executing correctly when used as a shutdown script

$
0
0

I have a script to unzip files that I'm testing as a shutdown script. I have the property to visibly display script output set to true as well so I can see if it's being run. The script doesn't execute properly when it's used as a shutdown script.

The script runs as expected from the command line. Also runs correctly when testing the script using psexec to run as SYSTEM.

Here's the script. The output follows the script. All the output lines display properly. The script also sleeps at the end as expected. However, the zip file does NOT get extracted. The script goes right through that line and doesn't even throw an exception. Again, this script runs perfectly from the command line.

I'm stumped as to why all the rest of the script works, but the unzip part doesn't.

Write-Host "Hello"
try
{
Write-Host "1"
  $ZipFile = $args[0]
Write-Host "2 - $ZipFile"
  $TargetDir = $args[1]
Write-Host "3 - $TargetDir"
  new-item $TargetDir -itemtype directory -ErrorAction SilentlyContinue
Write-Host "4"
  $shell_app=new-object -com shell.application
Write-Host "5"
  $zip_file = $shell_app.namespace($ZipFile)
Write-Host "6"
  $destination = $shell_app.namespace($TargetDir)
Write-Host "7"
  $destination.Copyhere($zip_file.items())
Write-Host "8"
Start-Sleep -s 10
  exit 0
}
Catch [Exception]
{
  Write-Host "Generic Exception"
  Write-Host $_
  $_ | Select *
  exit 1
}

The output I get is :

Hello
1
2 - c:\somedir\somezip.zip
3 - c:\somedir
4
5
6
7
8


Remoting from a PS 3.0 server to a PS 2.0 client using CIM cmdlets.

$
0
0

I'm brand new to powershell and my first use is to retrieve information from client machines about printers. When working with a client machine that has PS 3.0 already installed it's pretty straight forward...

"Get-PrinterPort -ComputerName LabPC-002-32" Will return a list of ports in use.

Using the same command on a client that has PS 2.0 installed returns...

PS H:\> Get-PrinterPort -ComputerName LabPC-002-32
Get-PrinterPort : The spooler service is not reachable.  Ensure the spooler service is running.
At line:1 char:1
+ Get-PrinterPort -ComputerName LabPC-002-32
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (MSFT_PrinterPort:ROOT/StandardCimv2/MSFT_PrinterPort) [Get-PrinterPort], CimException
    + FullyQualifiedErrorId : HRESULT 0x800706ba,Get-PrinterPort

I understand that in order to communicate with a v2.0 client I will need to used CIM cmdlets, but I'm new enough that I'm having trouble getting my head around the syntax. Can anyone provide or point me to an example of how to retrieve this kind of data from a 2.0 client?

Thanks,

Andy

(WMI) Need a cluster resource information - resource owned by cluster group

$
0
0
Hello guys,

I need to get some information regarding the drives that a cluster group owns.

Here is the Code i m using to get the cluster network names:-

    

 strWMIQuery = "SELECT * FROM MSCluster_Resource WHERE Type = 'Network Name'"

   Set colWMIItems = objWMICluster.ExecQuery(strWMIQuery)   

   WScript.Echo "List of Cluster Network Names:"

   For Each objItem in colWMIItems

      WScript.Echo objItem.PrivateProperties.Name

   Next



Now i need to get the DRIVES (specifically, resources of type "volume manager disk group") owned by a cluster group.

Can someone please help me which WMI class object can give this information?

I have attached a screenshot of the information i need from WMI/vbscript. (circled in red)

screenshot :   i38.tinypic.com/1jc8.jpg


Someone please help me! Will pay if needed!!

Custom tables and PSobject

$
0
0

Hi, so im messing with ps hash tables and custom tables i am looking for an alternative way of outputting them in the right format below, maybe someone could show me an easier way so this is what i typically use that works:

$objcol = @()
$data1 = "a1","a2","a3","a4"
$data2 = "b1","b2","b3","b4"
$data1 |foreach{
$obj = New-Object -Type PSObject
$Obj | Add-Member -MemberType NoteProperty -Name "data1" -Value "$_"
$objcol += $obj
}
$i = 0
$data2 |foreach{
$objcol[$i++] | Add-Member -MemberType NoteProperty -Name "data2" -Value "$_"
}
$objcol

result

data1                                                    data2                                                  
-----                                                    -----                                                  
a1                                                       b1                                                     
a2                                                       b2                                                     
a3                                                       b3                                                     
a4                                                       b4 

is there another way of doing this without using the $i++ incase there is different number of results in each variable?



POWERSHELL - MAKE MOUSE CURSOR GO TO THE CENTER OF THE SCREEN NUMBER 3

$
0
0

Hello everybody,

I have a multimonitor setup with 4 monitors (2 columns with 2 monitors). Monitor number 1 is on the left upper corner, monitor number 2 is on the left bottom corner, monitor number 3 is on the right upper corner and monitor number 4 is on the right bottom corner. My primary monitor is monitor number 2. All monitors have 1920x1200 resolution.

The following PowerShell code is used to place the mouse cursor in center of primary screen (left bottom corner).

"C:\users\joao42\powershell\centercursor1.ps1"
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | out-null
$bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
$center = $bounds.Location
$center.X += $bounds.Width / 2
$center.Y += $bounds.Height / 2
[System.Windows.Forms.Cursor]::Position = $center

I need to create a new code so that the mouse cursor goes to the center of screen number 3 (right upper corner).

Although it seems to be easy, so far I could not make the cursor go to the center of screen #3.

I really appreciate any help.

Thaks,

John

Cannot uninstall Powershell V1 From Server 2003 R2 Standard x86

$
0
0

I am posting this question in this forum at the recommendation of a moderator who feels this is a Powershell forum inquiry. Any help would be appreciated!

I have been reading through many articles without any success in finding the answer.

I have to upgrade a Server 2003 Standard 32 Bit server to 2008 Standard (Non R2) to preserve 32 bit functionality of some vendor applications that are currently running on the server.

I found a round-about way of removing powershell (Delete the registry entry and move the V1.0 folder out of the powershell directory in the Windows folder) and Windows Server 2008 will upgrade that way (I'm doing testing in a virtual environment) but after I perform the upgrade to 2008 I have random errors about powershell 1.0 registration on some of the applications. I also fear that additional changes to the server such as installing applications might cause problems. This is definitely not an orthadox solution.

Here is the deal (And yes I have read the KB articles I have been able to locate) the installation folders for powershell were removed whenever this Server 2003 R2 Standard server had the latest service packs removed in previous years. When attempting an upgrade (I don't have a choice) it tells me Powershell must be uninstalled.

Powershell cannot be uninstalled from the server in add / remove programs (With the show updates checkbox selected). It does not exist. There are no un-installer packages in the c:\windows directory.

I tried this stuff:

http://social.technet.microsoft.com/Forums/en-US/winservergen/thread/8ff0cd96-f86d-416b-8fdb-095f3fca2766/

WindowsServer2003-KB926139-v2-x86-ENU.exe >>> This will not install because it says the previous version of powershell must be removed (There is no uninstaller / and there is no "V1" version ofWindowsServer2003-KB926139-v2-x86-ENU.exe anywhere that I can locate online..... I think I need this version to possibly install / uninstall to recover the uninstall directories in the c:\windows directory.

I tried this:

http://support.microsoft.com/kb/926139

These do not exist on the server to uninstall.....

  • Hotfix for Windows Server 2003 (KB926139)
  • Hotfix for Windows Server 2003 (KB926140)
  • Hotfix for Windows Server 2003 (KB926141)


Eventually I just caved into trying this method:
http://social.technet.microsoft.com/Forums/en-US/itprovistaapps/thread/262ab957-1b90-1486c-8a7d-c8f84fd6e732/

Steps 1 wouldn't work (I couldn't find WindowsServer2003-KB926139-x86-ENU.exe)
2. Manually remove the Installation folder(s) (I did that)
%windir%\System32\WindowsPowerShell\V1.0

3. Remove the registry key (I did this)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell

I did not fully understand some of the other steps. All I know is after the upgrade to 2008 finished Server 2008 reported needing to run a repair on the .Net Framework. This took a while and after it completed I had to reboot.

Is there a more orthadox way to do this? Why doesn't Microsoft keep an archive of sorts of installers that are critical to being able to successfully upgrade operating systems to 2008 / 2012 such as WindowsServer2003-KB926139-x86-ENU.exe ???

If anyone has any input or has actually successfully cleanly installed this old version of powershell please let me know so that I can meet the clients requirements of maintaining the integrity of their applications.

Thanks everyone!

How to link the output from win32_diskdrive and win32_volume

$
0
0

Hi,

I am doing some analysis on multiple servers and am looking at ways to link
the output from the following 2 lines:

Get-WmiObject win32_volume | Select SystemName, name, Label, DriveLetter,
serialnumber |ft -AutoSize

Get-WmiObject win32_diskdrive | Select systemname, name, serialnumber |ft
-AutoSize

I would like to have a table outputting information that basically shows me
which physical drive is linked to each drive letter\mount point and I can't see
any common options to link the two.

Can anybody suggest how to do this?

Thanks


List print queues on workstations

$
0
0

Hello,

I am trying to write a script to list all the printers defined on a workstation (local and network). I was successful listing the local printers but I can't find a way to list the network printers as well. Win32_Printer gives me only the local printers.

Any help is greatly appreciated

Thanks

Change SQL Agent Job notification operator

$
0
0

Need help with this powershell script that will assign operator email for failure.  Here is what I have:

$server = "SQLSERVER\NAMED_INSTANCE"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null;
$srv = new-object Microsoft.SqlServer.Management.Smo.Server ($server)
foreach ($job in $srv.JobServer.jobs)
{
$job.EmailLevel = [Microsoft.SqlServer.Management.Smo.Agent.CompletionAction]::OnFailure
$job.OperatorToEmail = "SQLADMINS"
}
When I run it, it says script execution completed but after I checked nothing changed.  Any idea?


Move-ADObjects cmdlet: how do I log output?

$
0
0

Hello all,

I cannot get this cmdlet to log any output.  In the help file it does say the following:

PassThru

Returns the new or modified object. By default (i.e. if -PassThru is not specified), this cmdlet does not generate any output.

I'm not exactly sure what I'm doing wrong as I've specified this option and I still cannot log any output.  I've tried all the following variations:

Move-ADObject -Identity $ADObject.dn -TargetPath $OU -PassThru >> $logfile

Move-ADObject -Identity $ADObject.dn -TargetPath $OU -PassThru | Tee-Object -file $logfile -append

I've also tried these without the -passthru parameter.  Move-ADObject does display output on screen but I want to log this output.  I was able to log it with Start-Transcription, however, the output from this command is ugly.  It put all output on one line...  very unreadable.  Does anyone have any advice?  

Thanks!

How to pass the value out of the script, I am not sure how to use global or reference variable.

$
0
0
New-Variable -Name GlobalVar -Value "Initial" -Scope "Global"
write "GlobalVar is $GlobalVar"

$script = 
{
	param(
		$server,
		$mycred
	)
	$GlobalVar="Different"
}
# Passing of the parameters to the block through argumentlist.
Invoke-Command -credential $mycred -ComputerName $server -ScriptBlock $script -ArgumentList $server,$mycred

write "GlobalVar is $GlobalVar"

Output is 
GlobalVar is Initial
GlobalVar is Initial

It should be as below as the $GlobalVar is modified in the script block...
GlobalVar is Initial
GlobalVar is Different

Powershell Script Help

$
0
0
add-pssnapin quest.activeroles.admanagement
$date = (get-date).ToString()
$DistinguishedName = get-content C:\TEMP\90InactiveMoves\SSCtest.txt | foreach-object {get-qaduser $_ -Service 'My server.com' -SearchRoot 'Mydomain.com/BLA/users' -properties DistinguishedName}
get-content C:\TEMP\90Moves\SSCtest.txt | foreach-object {get-qaduser $_ -Service 'Myserver.com' -SearchRoot 'mydomain.com/ssc/users' -Enabled | Disable-QADUser | set-qaduser -Description "Account disabled on $date, $DistinguishedName" |Move-QADObject -Service 'Myserver.com' -NewParentContainer 'MyDomain.com/Inactive users'}

Need some help. I am trying to update the 'Description' Field of a list of AD users with two variables I need to pass. One is the date, which works fine, the other is the DistinguishedName. What Im doing is a bulk user move here and need the account stamped with the date it was moved and the old OU path it originated at before it was moved in case it needs to go back. Can someone look at this and maybe suguest a way to get the DistinguishedName part done? My script works fine but I am stuck on the DistinguishedName part. I pass it as a variable by looking up the account DistinguishedName and passing it as the variable but this is sketchy at best. Thanks for the help:

 

Change remote configuration using powershelll for multiple servers

$
0
0

Hi,

Can anyone help me with changing the "Disconnected session from 10mins to 6hours" in remote session host configuration under Remote Desktop Services using powerhsell.

I used this command to install the Remote desktop Services

import-module servermanager -verbose
get-windowsfeature -name *RDS*
Add-WindowsFeature –Name RDS-RD-Server –IncludeAllSubFeature -WhatIf -Restart
import-module remotedesktopservices -verbose
Get-Command –Module RemoteDesktopServices
Get-PSProvider

I can see remotedesktopservices in PSPROVIDER but when i go to RDS drive :-\

PS C:\Users\Administrator> cd RDS:

PS RDS:\ get-childitem

Name                           Type      CurrentValue         GP   PermissibleValues PermissibleOperations
----                           ----      ------------         --   ----------------- ---------------------
LicenseServer                  Container                      -                      Get-Item, Get-ChildItem

If i go to PS RDS:\> cd ./RDSCongiuration . This error i get
Set-Location : Cannot find path 'RDS:\RDSCongiuration' because it does not exist.
At line:1 char:3
+ cd <<<<  ./RDSCongiuration
    + CategoryInfo          : ObjectNotFound: (RDS:\RDSCongiuration:String) [Set-Location], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

I dont see RDSConfiguration because of which i am just not able to go to this location which is RDS:\RDSConfiguration\Connections\RDP-Tcp\Sessions to change the end disconnected session to 6hours. Please help



how to -expand a property but include the label

$
0
0

Hi, i am looking for an easier way to -expand a property but to keep the label.. I know you can do the fl and different ft to sort of expand multiple results but that still can be cut off depending on the length so i prefer -expand which removes the label, and i end up doing 4 pipes to re add label after i -expand

i feel like i am missing something..

thanks


Looking for good books on the Virtual Machine Manager Powershell Module

$
0
0

Hi, I am looking for a good book, or books that teach you about the Virtual Machine Manager Powershell Module for Windows Server 2012.  I am looking for examples of the cmdlets, in addition to a description of them and what they do.

Thanks in advance!

Tim


Tim

Using AsJob To Improve Performance

$
0
0

Hi All,

I am working on a script which checks a server for ping and then check all SQL Server Services status and sotre this in a table. However I have to check across 70 servers and it takes over a minute to run. I looked into the AsJob parameter and when I added this to all my "Get_WMIObject" Commands it started returning the wrong information for each Service. Although it ran in just 20 seconds. Can someone take a look below and advise where I am going wrong or what I can do to make the retrieval of the server service information asynchronous?

Thanks

<#
Tests all Servers for Ping and SQL Server Service Status
#>

# Return the Ping Status
Function GetStatusCode 
{  
    Param([int] $StatusCode)   
    switch($StatusCode) 
    { 
        0         {"Success"} 
        11001   {"Buffer Too Small"} 
        11002   {"Destination Net Unreachable"} 
        11003   {"Destination Host Unreachable"} 
        11004   {"Destination Protocol Unreachable"} 
        11005   {"Destination Port Unreachable"} 
        11006   {"No Resources"} 
        11007   {"Bad Option"} 
        11008   {"Hardware Error"} 
        11009   {"Packet Too Big"} 
        11010   {"Request Timed Out"} 
        11011   {"Bad Request"} 
        11012   {"Bad Route"} 
        11013   {"TimeToLive Expired Transit"} 
        11014   {"TimeToLive Expired Reassembly"} 
        11015   {"Parameter Problem"} 
        11016   {"Source Quench"} 
        11017   {"Option Too Big"} 
        11018   {"Bad Destination"} 
        11032   {"Negotiating IPSEC"} 
        11050   {"General Failure"} 
        default {"Failed"} 
    } 
} 

# Format the Server Up-time
Function GetUpTime 
{ 
    param([string] $LastBootTime) 
    $Uptime = (Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($LastBootTime) 
    "Days: $($Uptime.Days); Hours: $($Uptime.Hours); Minutes: $($Uptime.Minutes); Seconds: $($Uptime.Seconds)"  
} 

#Main Body
# Populate Table MyDB.dbo.tbl_ServerPingTest

$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=MyServer; Initial Catalog=MyDB; Integrated Security=SSPI")
$conn.Open()

$cmd = $conn.CreateCommand()
$cmd.CommandText ="DELETE FROM MyDB.dbo.tbl_ServerPingTest
INSERT INTO MyDB.dbo.tbl_ServerPingTest (ServerName, InstanceName)
SELECT ServerName, InstanceName FROM MyDB.dbo.tbl_servers
WHERE ServerCategory <> 'DECOMMED'"
$cmd.ExecuteNonQuery()

$cmd2 = $conn.CreateCommand()
$cmd2.CommandText = "SELECT * FROM MyDB.dbo.tbl_ServerPingTest"
$da = New-Object System.Data.SqlClient.SqlDataAdapter #($cmd2)
$da.SelectCommand = $cmd2
$dt = New-Object System.Data.DataTable
$da.Fill($dt) | Out-Null

# Cycle through Server and Instances and retrieve information
Foreach($row in $dt.rows) 
{ 
    $ServerName = $row.ServerName
	$InstanceName = $row.InstanceName
            
    $pingStatus = Get-WmiObject -Query "Select * from win32_PingStatus where Address='$ServerName'" 
    $Uptime = $null 
    $SQLServerStatus = $null 
    $SQLAgentStatus = $null 
	# Enter the Loop if a Server is Pingable
    if($pingStatus.StatusCode -eq 0) 
    { 
        # Trap needed for server where Access is Denied causes the SQL Job to fail
		trap {continue}
        $OperatingSystem = Get-WmiObject Win32_OperatingSystem -ComputerName $ServerName -ErrorAction SilentlyContinue -ErrorVariable wmiResults
        $Uptime = GetUptime( $OperatingSystem.LastBootUpTime ) 
        if ($wmiResults -ne $null)
          {
            $tmperr = "Uptime Info Could Not be Obtained"
            $Uptime = $null
          }
        else
          {
            $tmperr = ""

			filter SvcFilter {
				if ($_.StartMode -eq "Disabled") {$_.StartMode }
				else {$_.State}
				}
			$props="Name","StartMode","State"

			if ($InstanceName -eq 'DEFAULT') 
				{
					Write-Host $ServerName + '\' + $InstanceName 
					$SQLServerStatus = Get-WMIObject win32_service -property $props -filter "name='MSSQLSERVER'" -computer $ServerName | SvcFilter
					#Write-Host $SQLServerStatus
					$SQLAgentStatus = Get-WMIObject win32_service -property $props -filter "name='SQLSERVERAGENT'" -computer $ServerName | SvcFilter
					#Write-Host $SQLAgentStatus
					$RSAgentStatus = Get-WMIObject win32_service -property $props -filter "name='ReportServer'" -computer $ServerName | SvcFilter
					#Write-Host $RSAgentStatus
				}
				else
				{
					Write-Host $ServerName + '\' + $InstanceName 
					$NamedInstanceSQLService = "MSSQL$" + $InstanceName
					$NamedInstanceAgentService = "SQLAgent$" + $InstanceName
					$NamedInstanceRSService = "ReportServer$" + $InstanceName
					$SQLServerStatus = Get-WMIObject win32_service -property $props -computer $ServerName | where {$_.name -eq $NamedInstanceSQLService} | SvcFilter
					$SQLAgentStatus = Get-WMIObject win32_service -property $props -computer $ServerName | where {$_.name -eq $NamedInstanceAgentService} | SvcFilter
					$RSAgentStatus = Get-WMIObject win32_service -property $props -computer $ServerName | where {$_.name -eq $NamedInstanceRSService} | SvcFilter
				}
			$ASAgentStatus = Get-WMIObject win32_service -property $props -filter "name='MSSQLServerOLAPService'" -computer $ServerName | SvcFilter
          }
    } 
    $IPAddress = $pingStatus.IPV4Address
    $PingTest = GetStatusCode( $pingStatus.StatusCode ) 
    $ErrMSG = $tmperr
    # Update Table MyDB.dbo.tbl_ServerPingTest with all retreived information 
    $updateRow = $dt.Select("ServerName = '$ServerName' AND InstanceName = '$InstanceName'")
    $updateRow[0].IPAddress = $IPAddress
    $updateRow[0].PingTest = $PingTest
    $updateRow[0].ErrMSG = $ErrMSG
    $updateRow[0].Uptime = $Uptime
    $updateRow[0].SQLServerStatus = $SQLServerStatus
    $updateRow[0].SQLAgentStatus = $SQLAgentStatus   
    $updateRow[0].RSAgentStatus = $RSAgentStatus 
    $updateRow[0].ASAgentStatus = $ASAgentStatus 

    $cmdUpd = $conn.CreateCommand()
    $cmdUpd.CommandText = "UPDATE MyDB.dbo.tbl_ServerPingTest
    SET IPAddress = @IPAddress, PingTest = @PingTest, ErrMSG = @ErrMSG, Uptime = @Uptime, SQLServerStatus = @SQLServerStatus, SQLAgentStatus = @SQLAgentStatus, RSAgentStatus = @RSAgentStatus, ASAgentStatus = @ASAgentStatus
    WHERE ServerName = @ServerName AND InstanceName = @InstanceName"
    # Add parameters to pass values to the UPDATE statement
    $cmdUpd.Parameters.Add("@ServerName", "nvarchar", 50, "ServerName") | Out-Null
    $cmdUpd.Parameters["@ServerName"].SourceVersion = "Original"
    $cmdUpd.Parameters.Add("@InstanceName", "nvarchar", 50, "InstanceName") | Out-Null
    $cmdUpd.Parameters["@InstanceName"].SourceVersion = "Original"
    $cmdUpd.Parameters.Add("@IPAddress", "nvarchar", 50, "IPAddress") | Out-Null
    $cmdUpd.Parameters["@IPAddress"].SourceVersion = "Current"
    $cmdUpd.Parameters.Add("@PingTest", "nvarchar", 50, "PingTest") | Out-Null
    $cmdUpd.Parameters["@PingTest"].SourceVersion = "Current"
    $cmdUpd.Parameters.Add("@ErrMSG", "nvarchar", 50, "ErrMSG") | Out-Null
    $cmdUpd.Parameters["@ErrMSG"].SourceVersion = "Current"
    $cmdUpd.Parameters.Add("@Uptime", "nvarchar", 50, "Uptime") | Out-Null
    $cmdUpd.Parameters["@Uptime"].SourceVersion = "Current"
    $cmdUpd.Parameters.Add("@SQLServerStatus", "nvarchar", 50, "SQLServerStatus") | Out-Null
    $cmdUpd.Parameters["@SQLServerStatus"].SourceVersion = "Current"
    $cmdUpd.Parameters.Add("@SQLAgentStatus", "nvarchar", 50, "SQLAgentStatus") | Out-Null
    $cmdUpd.Parameters["@SQLAgentStatus"].SourceVersion = "Current"
	$cmdUpd.Parameters.Add("@RSAgentStatus", "nvarchar", 50, "RSAgentStatus") | Out-Null
    $cmdUpd.Parameters["@RSAgentStatus"].SourceVersion = "Current"
	$cmdUpd.Parameters.Add("@ASAgentStatus", "nvarchar", 50, "ASAgentStatus") | Out-Null
    $cmdUpd.Parameters["@ASAgentStatus"].SourceVersion = "Current"

    # Set the UpdateCommand property
    $da.UpdateCommand = $cmdUpd

    # Update the database
    $RowsUpdated = $da.Update($dt)


} 

$conn.Close()





Power shell archive script

$
0
0

Apologies if thisis abad post, if it is please redirect me...

I'm new to power shell and have a question regarding scripting an archive solution.

The solution has to do the following

Move files older than 31 days from one location to another on the same server

The solution check for a sub directory in the destination based on the date of the file being moved. 

If the appropiate sub directory doesn't exist it should be created before the file is moved.

This is my crude move script that dos work but I need help with the sub directory check\creation based on the target files creation date.

get-childitem -Path "E:\PRD\ARCHIVE\" |
    where-object {$_.LastWriteTime -lt (get-date).AddDays(-31)} |
    move-item -destination "E:\Service Archive"

Any advice or help is much appreciated.

Alan

listing AD accounts that been inactive for more than 90 days, or that shows the last used date

$
0
0

Hi, I am trying to get information about more than 90 days, could someone verify script below, is it fine or I should add anything else

$90Days = (get-date).adddays(-90)

Get-ADUser -properties * -filter {(lastlogondate -notlike "*" -OR lastlogondate -le $90days) -AND (passwordlastset -le $90days) -AND (enabled -eq $True) -and (PasswordNeverExpires -eq $false) -and (whencreated -le $90days)} | select-object name, SAMaccountname, passwordExpired, PasswordNeverExpires, logoncount, whenCreated, lastlogondate, PasswordLastSet, lastlogontimestamp


AG

Remote command works on one client but not another

$
0
0

My previous question turns out to be erroneous -

http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/52e5861f-3cde-42c4-9a52-64bbda0c16da

It turns out that the fact that one of the clients was running PS 2.0 is not the root of the problem. I now have PS 3.0 running on both clients and the Get-PrinterPort command works as you would expect on one Client1, but on Client2 I always receive the same error. Other commands like Get-Service works fine on both machines. Both client machines are running Win7 SP1 and the spooler service IS running on both. The commands are being sent to both clients from the same machine which is running Windows 2012 server.

Any suggestions would be greatly appreciated.

PS C:\Windows\system32> Get-PrinterPort -ComputerName Client1

Name                 ComputerName         Description          PortMonitor        
----                     ------------         -----------          -----------        
COM1:                Client1          Local Port           Local Monitor      
COM2:                Client1          Local Port           Local Monitor      
COM3:                Client1          Local Port           Local Monitor      
COM4:                Client1          Local Port           Local Monitor      
FILE:                   Client1          Local Port           Local Monitor      
LPT1:                  Client1          Local Port           Local Monitor      
LPT2:                  Client1          Local Port           Local Monitor      
LPT3:                  Client1          Local Port           Local Monitor      
XPSPort:             Client1          Local Port           Local Monitor      
xxx.xxx.xx.xxx    Client1          Standard TCP/IP Port TCPMON.DLL          
USB001               Client1          Virtual printer p... Dynamic Print Mon...

PS C:\Windows\system32> Get-PrinterPort -ComputerName Client2
Get-PrinterPort : The spooler service is not reachable.  Ensure the spooler service is running.
At line:1 char:1
+ Get-PrinterPort -ComputerName Client2
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (MSFT_PrinterPort:ROOT/StandardCimv2/MSFT_PrinterPort) [Get-PrinterPort], CimEx
   ception
    + FullyQualifiedErrorId : HRESULT 0x800706ba,Get-PrinterPort

Viewing all 21975 articles
Browse latest View live


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