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

Powershell in scheduled task to create another ScheduledJob @ next boot

$
0
0

Hi,

I have put together two powershell scripts that will run in a scheduled task once a month. There is one script called start-patching. This script is triggered with a scheduled task, that runs like path\to\powershell.exe -command C:\script.ps1.

That first script will at its end, create a Register-ScheduledJob to run the second script at next boot. The first script runs fine, except that the line that does Register-ScheduledJob does not work. When i run the first script manually from powershell everything works.

First script:

# -------------------------------------
# Variables
# -------------------------------------
$scriptName = "C:\Script\Patch\continue-patching.ps1"
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30

 function sendMail{

     Write-Host "Sending Email"

     $nameofhost = hostname

     #SMTP server name
     $smtpServer = "smtp.domain.com"

     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage

     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)

     #Email structure
     $msg.From = "autopatch@domain.com"
     $msg.ReplyTo = "noreply@domain.com"
     $msg.To.Add("user@domain.com")
     $msg.subject = "Started patching $nameofhost"
     $msg.body = "$nameofhost"

     #Sending email
     $smtp.Send($msg)

}


#Script
New-EventLog –LogName Application –Source “Patch script” -ErrorAction SilentlyContinue

#write event log
Write-EventLog –LogName Application –Source “Patch script” –EntryType Information –EventID 1 –Message “Running patch script start-patching”

#Calling function
sendMail

#Import-Module
Set-ExecutionPolicy Unrestricted
ipmo PSWindowsUpdate

#patch
Get-WUInstall -AcceptAll

#write event log
Write-EventLog –LogName Application –Source “Patch script” –EntryType Information –EventID 1 –Message “Patching is complete. Computer will now reboot”

#Create scheduled job at next startup
Register-ScheduledJob -Trigger $trigger -FilePath $scriptName -Name Continue-Patching-Job

#Reboot computer
shutdown -r -t 0
exit

Second script:

 function sendMailAfter{

     Write-Host "Sending Email"

     #SMTP server name
     $smtpServer = "smtp.domain.com"

     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage

     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)

     #Email structure
     $msg.From = "autopatch@domain.com"
     $msg.ReplyTo = "noreply@domain.com"
     $msg.To.Add("user@domain.com")
     $msg.subject = "Finished patching $nameofhost"
     $msg.body = "$message"

     #Sending email
     $smtp.Send($msg)

}

#Script

#Remove scheduled job
Unregister-ScheduledJob -Name Continue-Patching-Job

#write event log
Write-EventLog –LogName Application –Source “Patch script” –EntryType Information –EventID 1 –Message “Computer has rebooted. Running script continue-patching”

sendMailAfter

#write event log
Write-EventLog –LogName Application –Source “Patch script” –EntryType Information –EventID 1 –Message “Finished patching. Sending status email”

Server is 2008 R2 with WMF4.0


This posting is provided "AS IS" with no warranties or guarantees and confers no rights



Sorting order when using remote powershell

$
0
0

Hi

Are there any documented differences between how Powershell sorts a result set when using a remote session vs when run locally? 

I'm trying to retrieve the smallest of my Exchange 2010 database sizes, which when run locally gives me the results sorted numerically.  When running the same PS command remotely, I get the results sorted alphanumerically.

Is there any way to force the sort to be numeric on the remote session?

Here's the commands and their outputs run locally and then remotely:

Local
Get-MailboxDatabase -Status | sort DatabaseSize | ft name,databasesize

Name                                                     DatabaseSize
----                                                        ------------
LON1JRNL                                              31.88 GB (34,235,023,360 bytes)
LON2MBX5                                             72.51 GB (77,855,784,960 bytes)
LON1MBX3                                             74.76 GB (80,276,946,944 bytes)
LON2MBX2                                             77.14 GB (82,823,938,048 bytes)
LON2MBX1                                             87.51 GB (93,964,533,760 bytes)
LON1MBX2                                             104.8 GB (112,486,580,224 bytes)
LON1MBX1                                             117.9 GB (126,579,965,952 bytes)
LON2MBX4                                             143.1 GB (153,690,898,432 bytes)
NJY1MBX4                                              150.4 GB (161,473,429,504 bytes)
NJY1MBX1                                              156 GB (167,517,421,568 bytes)
NJY1MBX3                                              166 GB (178,267,947,008 bytes)
LON1MBX4                                              177.8 GB (190,872,879,104 bytes)
LON2MBX3                                              185.3 GB (198,980,993,024 bytes)

Remote
Get-MailboxDatabase -Status | Sort DatabaseSize | ft name,databasesize

Name                                                  DatabaseSize                                                                                 
----                                                     ------------                                                                                 
LON1MBX2                                          104.8 GB (112,486,580,224 bytes)                                                             
LON1MBX1                                          117.9 GB (126,579,965,952 bytes)                                                             
LON2MBX4                                          143.1 GB (153,690,898,432 bytes)                                                             
NJY1MBX4                                           150.4 GB (161,473,429,504 bytes)                                                             
NJY1MBX1                                           156 GB (167,517,421,568 bytes)                                                               
NJY1MBX3                                           166 GB (178,267,947,008 bytes)                                                               
LON1MBX4                                          177.8 GB (190,872,879,104 bytes)                                                             
LON2MBX3                                          185.3 GB (198,980,993,024 bytes)                                                             
LON1JRNL                                           31.88 GB (34,235,023,360 bytes)                                                              
LON2MBX5                                          72.51 GB (77,855,784,960 bytes)                                                              
LON1MBX3                                          74.76 GB (80,276,946,944 bytes)                                                              
LON2MBX2                                          77.14 GB (82,823,938,048 bytes)                                                              
LON2MBX1                                          87.51 GB (93,964,533,760 bytes)

For reference, here's the psversiontable on each machine:

LocalName                           Value
----                           -----
CLRVersion                     2.0.50727.5466
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

Remote
Name                           Value                                    
----                           -----                                      
PSVersion                      3.0                                      
WSManStackVersion              3.0                                  
SerializationVersion           1.1.0.1                          
CLRVersion                     4.0.30319.34209                           
BuildVersion                   6.2.9200.16398                         
PSCompatibleVersions           {1.0, 2.0, 3.0}                                  
PSRemotingProtocolVersion      2.2

Any help greatly appreciated!

Thanks

Passing output parameter from stored procedure

$
0
0

Hi,

I have a problem with passing the value from an output parameter from sql stored procedure to a powershell variable, and the value from variable send it via mail:

Script for sql stored procedure:

Use [master]
Go

Alter Procedure dbo.test
	@value nvarchar(4000) output
As
Begin
	Set NoCount ON;
	Set @value = 'Error'
End
Go

Script for powershell:

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "integrated security=SSPI; data source=.\SQLEXPRESS; initial catalog=master;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "[test]"
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandType = [System.Data.CommandType]::StoredProcedure
$SqlCmd.Parameters.Add("@value", "") | out-null
$SqlCmd.Parameters["@value"].Direction = [system.Data.ParameterDirection]::Output

$SqlConnection.Open()
$SqlCmd.ExecuteNonQuery()
$returnvalue = $SqlCmd.Parameters["@value"].Value
$SqlConnection.Close()

$smtp = new-object Net.Mail.SmtpClient("test@test.com")
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "test@test.com"
$objMailMessage.To.Add("test@test.com")
$objMailMessage.Subject = "TestMail"
$objMailMessage.Body = $returnvalue
$smtp.send($objMailMessage)

The powershell script runs without any errors and it send me the mail, but in the mail`s body instead of the word: "Error" apears just a single character: "E".

Can someone guide me how to pass the output value and send it via mail?

Thanks

Group by Subnet

$
0
0

Let's imagine I have this list of IP

$a=@()
$a += New-Object PSObject -Property @{IP="10.10.10.10"}
$a += New-Object PSObject -Property @{IP="10.10.10.20"}
$a += New-Object PSObject -Property @{IP="10.10.12.20"}
$a += New-Object PSObject -Property @{IP="10.5.10.20"}
$a += New-Object PSObject -Property @{IP="10.8.10.20"}
$a += New-Object PSObject -Property @{IP="20.8.10.20"}
$a += New-Object PSObject -Property @{IP="20.8.10.5"}
$a += New-Object PSObject -Property @{IP="20.8.12.5"}
$a += New-Object PSObject -Property @{IP="10.6.10.20"}
$a += New-Object PSObject -Property @{IP="10.6.10.6"}

$a 

I'll like to group these IP by Subnets  /24, or if you prefer by the 3 first octects

So the result should be

10.10.10
10.10.12
10.5.10
10.8.10
20.8.10
20.8.12
10.6.10

My sure it is something like

$a | group { New-Object ...... }

or

$a | group { $_.IP.tostring(.....) }

Thanks for your help

Remotely executing a Backup-CARoleService returns a Access Denied after what appears to be successful execution.

$
0
0

I am trying to understand what is going on with my current script which is a simple one liner. My setup is relatively simple. An AD joined server that is going to be used as a certificate root in an internal PKI (The root server should be a workgroup only system, but let us move on.) running Windows 2012 R2, and a Windows 8.1 workstation that I am using as a RSAT/CnC system. I am able to launch a powershell as the administrator on the local system as well as remote into the server and launch powershell as the administrator.

If I run an invoke-command -Computer RemoteServer -ScriptBlock {Get-Culture} I get back the expected 4 columns of information. If I Enter-PSSession -Computer Remote Server and then issue Get-Culture, I get back the expected 3 columns of information (no remote system name).

The Problem is if do an invoke-command -Computer RemoteServer -ScriptBlock {Backup-CARoleService c:\testdir -Password (ConvertTo-SecureString "SuperSecret" -AsPlainText -Force)} or I run the script block from a Enter-PSSession prompt, it appears to execute properly (I get all of the proper files), but I get :

Backup-CARoleService : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:1 char:1
+ Backup-CARoleService c:\testdir -Password (ConvertTo-SecureString "SuperSecret ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Backup-CARoleService], UnauthorizedAccessException
    + FullyQualifiedErrorId : BackupDatabase,Microsoft.CertificateServices.Administration.Commands.CA.BackupCACommand

at the end of execution.

If I remote terminal into RemoteServer and execute the Backup-CARoleService command from a powershell, everything succeeds without error.

What is going on with the Access Denied message ?

Thank you for your help.

Edit2 : I am the same domain user on both the local workstation and the remote server.

Edit3 : On a lark I also tried using :

$s=New-PSSession -Computer RemoteServer -Credentials Domain\Admin 

Invoke-Command -Session $s -ScriptBlock...

Same error message with these command.

Sean



If statement based on day of the week evaluating despite being false

$
0
0

I have about 400 virtual Citrix servers presenting applications that I would like to reboot daily and come up clean every other day, except Sunday. We've decided that the servers with an even number in them will be rebooted on Monday/Wednesday/Friday and the servers with an odd number in them will be rebooted on Tuesday/Thursday/Saturday. 

The servers all have a naming convention of 4 letters, then 5 numbers, then 1 more letter, I.E. CADS05500a or WORD98001b, so I'm getting my list of servers like this:

$xa_servers = Get-XAServer
$even_servers = $xa_servers | ? {$_.servername.substring(5,4) %2 -eq 0}
$odd_servers = $xa_servers | ? {$_.servername.substring(5,4) %2 -eq 1}

I can confirm this works correctly because $even_servers.count + $odd_servers.count = $xa_servers.count

Next I check the day of the week and if it's Monday/Wednesday/Friday I reboot the even servers, and if it's Tuesday/Thursday/Saturday I reboot the odd servers:

$datetime = get-date
if ($datetime.DayOfWeek -eq "Monday" -or "Wednesday" -or "Friday")
    {
    foreach ($server in $even_servers)
        {
        Set-XAServerLogOnMode -ServerName $server -LogOnMode ProhibitNewLogOnsUntilRestart -whatif
		}
    }


if ($datetime.DayOfWeek -eq "Tuesday" -or "Thursday" -or "Saturday")
    {
    foreach ($server in $odd_servers)
        {
        Set-XAServerLogOnMode -ServerName $server -LogOnMode ProhibitNewLogOnsUntilRestart -whatif
		}
    }

Trouble is, both lists are being processed, and I end up with 400 -whatif lines. Why is the first if statement processing if today is Tuesday?


zarberg@gmail.com


remote desktop can't print locally at ms server 21012r2 std

$
0
0

Hi , recently installed ms remote desktop client to windows server 2012r2. I facing problem to print out documents

at local printers. please help asap. thanks all

Format count the unique number

$
0
0

hi developer,

I have made count the unique number of string so I am trying to read in text file. The file name is bb.txt:

11 23 AA
52 64 AA
75 88 BB
23 65 BB
63 45 BB
85 66 CC
45 54 CC

Here is my sample windows powershell script:

$groups=$( ForEach ($file in Get-Content .\bb.txt )
{
    $Element =$file -split ' ' -replace "\s+", " "

    $ThisElement = $Element[2]
    $ThisElement
}) | Group-Object

$arr = @()
foreach($group in $groups)
{
    for($x = 1; $x -le $group.count; $x++)
    {
    $val = $groups.Name + ",$x"

    $arr += $val
    }
}
$arr

Display output as above code:
,1
,2
,1
,2
,3
,1
,2

Now i am going to Get-Content file:

Get-Content .\bb.txt |ForEach-Object {($_ -replace "\s+",",")} 
Display output as above code:

11,23,AA
52,64,AA
75,88,BB
23,65,BB
63,45,BB
85,66,CC
45,54,CC

But how to display output like this?

11,23,AA,1
52,64,AA,2
75,88,BB,1
23,65,BB,2
63,45,BB,3
85,66,CC,1
45,54,CC,2

I am trying from 1-2 hours continuously still i have no clue.
Any Idea?

Thanks



better way to find "stale" pcs in the network to remove in AD than lastlogondate?

$
0
0

Hello, I ran a typical lastlogondate check against pcs in AD. The first few dozen I checked last logged on 2-3 years ago. Several are pingable. Is there a better object property to check that would be "last phoned home to AD"? Or should I modify the script that would then ping those devices before removing them from AD for cleanup?

This is common for legacy xp to win7 device upgrades to see old objects, however some are still pingable. Thanks for any ideas!

pssession - local variables in scriptblock

$
0
0

hi guys

I'm trying to do some remote PSsession stuff on our domain-controller.

$Computername = gc env:computername
$ComputerModel = get-wmiobject -class win32_computersystemproduct | select Version -ExpandProperty version

$session=new-pssession -computer serv01

invoke-command -session $session -scriptblock {Get-ADcomputer -Filter {name -like $args[0]} -properties *} -Argumentlist @($computername) 

Something about the double {} in get-adcomputer is messing things up... any ideas?


Kindest regards, Martin

InternetExplorer.Application Call Web Page Function

$
0
0

Hi All,

I'm new to PowerShell and I am trying to Automate a web page process. Here is my script:

$User = "MyUserName"
$Pass = "MyPass"
Add-Type -AssemblyName "Microsoft.VisualBasic"
Add-Type - AssemblyName System.Windows.Forms
$IE = New-Object -com "InternetExplorer.Application"
$IE.Visible = $True
$IE.Navigate("URL")
While ($IE.busy -eq $True)
{Start-Sleep -Milliseconds 600}
$Doc = $IE.Document
$Username = $Doc.getElementById("username")
$Password = $Doc.getElementById("password")
$Username.value = $User

$Password.value = $Pass

Now when you type the password manually on the Webpage a Function called "ValidateForm" is called on KeyUp that sees something has been typed into password and Enables the login button.

My question is how can I call the "ValidateForm" Function from my script to enable the login button?

Many Thanks

ConvertTo-SecureString : Length of the data to decrypt is invalid.

$
0
0

Hello,

I am trying to use domain user credential to perform task on non domain (workgroup) machine.  it was workig fine with below powershell code but after changing user's passoword it is giving error "ConvertTo-SecureString : Length of the data to decrypt is invalid."

Below is the Code:

$MName = Hostname $Files = @(Get-ChildItem -path cert:\localmachine\my | Where-Object {$_.Subject -match $_.Mname}) $MName = "$MName.xyz.com" if ($Files.length -eq 0) { write-host " Certificate NOT EXIST" $key = (2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43,6,6,6,6,6,6,31,33,60,23) $test2 = "domain\abc.xyz" # $pass = Read-Host -AsSecureString $securepass = "01000000d08c9ddf0115d1118c7a00c04fc297eb010000009e043c1d88662642b4aeeba59e3808d400000000020000000000106600000001000020000000e9426abf44ee95182ab23cd1d1ed7b845eb245ffd9cd880ad090546e22baead9000000000e8000000002000020000000eec5cc811ab34b26391ff227912a2fe687a9b599ec6c2ca9bfb3474ddddc7f6c3000000009b69d5f671053634058a790bd31d88043792934ad533fa859f419e405503b77cc038706fce6791064c8b8381e8d6ec24000000006dfcff665da911b43ec204c3cbeeb7ac33d343a50c41ce9209f79e85737a0d6944ae04363b63f8c740f7e369b0b159c9b2c2e1182c95b185b1e34dd2767db8c" $bytes = [byte[]][char[]]$securepass

$csp = New-Object System.Security.Cryptography.CspParameters $csp.KeyContainerName = "SuperSecretProcessOnMachine" $csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore $rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 5120,$csp $rsa.PersistKeyInCsp = $true $encrypted = $rsa.Encrypt($bytes,$true) $encrypted |Export-Clixml 'C:\temp\word.xml' $encrypted = Import-Clixml 'C:\temp\word.xml' $password = [char[]]$rsa.Decrypt($encrypted, $true) -join "" |ConvertTo-SecureString -Key $key

I have also  tried key as (1..16)  , (1..24)   and (1..32) .

Thanks

get office 365 mailboxes with E3 license and Litigation hold status (enabled/disabled)

$
0
0

I've been searching the net for this and unable to find what i;m looking for:

get office 365 mailboxes with E3 license and Litigation hold status (enabled/disabled) , so I know if there are any E3 mailboxes with litigation hold not enabled on them.

Thanks.

How to sort 'strings' by property

$
0
0

Hi,

I have a ASCII txt file with seven 'delimited' columns of data, delimited by 1 blank space, which is the Netlogon.log file.  The last column is an IP address.  I'd like to sort this last column in ascending sequence.  So far, I've done the following which doesn't yield the right results:

Get-Content myfile.txt | Sort -ascending | out-file sortedfile.txt

Need I create a Hash table to build properties to Sort on or how would I do this?


Thanks for your help! SdeDot



How to get list of users excluding a praticular OU?

$
0
0

I'm not having any luck with my search. I'm trying to get a list of all AD users but I want to exclude a few OU's from the search, "non-employee" and "board". When I run the following script it's still outputting the users in these OUs:

Get-ADUser-Filter  {(Enabled-eq"True")}|?{ ($_.distinguishedname-notlike'NON-EMPLOYEE')-or($_.DistinguishedName-notlike"Board") } | ogv


Issue with New-Object System.Windows.Forms and Function using Register-Object Event

$
0
0

Hi everyone,

I've found 2 great functions to scan an Ip range extremely quickly, both of these function are using Register-Object Event,  I've used these functions multiple time, in many different script without any issue. But now I'm trying to build a GUI for these functions,  and I'm having a quite surprising issue

Here the code

Add-PsSnapin VMware.VimAutomation.Core


function Ping-IPRange3 {
    [CmdletBinding(ConfirmImpact='Low')]
    Param(
        [parameter(Mandatory = $true, Position = 0)]
        $FirstOctet,
        [parameter(Mandatory = $true, Position = 1)]
        $SecondOctet,
        [parameter(Mandatory = $true, Position = 2)]
        $ThirdOctet

    )

    $octet1     = $FirstOctet;
    $octet2     = $SecondOctet;
    $octet3     = $ThirdOctet
    $octet4     = (0..255);
    $timeout    = 500
    $global:res = @();
    $jobs= @();

    $octet3 | %{ $oct3 = $_;
        Write-verbose "Third Octet: $oct3"
        $octet4 | %{ $oct4 = $_;
            Write-verbose  "Fourth Octet: $oct4"
            $ip         = "$octet1.$octet2.$oct3.$oct4"
            Write-Verbose  $ip
            $ping       = New-Object System.Net.NetworkInformation.Ping

            $jobs       += Register-ObjectEvent -Action {
                $newIP      = $event.SourceArgs[1].UserState
                $reply      = $event.SourceArgs[1].Reply # | Add-Member -MemberType NoteProperty -Name ComputerName -Value $comp.Name -PassThru;
                $global:res += $reply | Select-Object Address, Status,  RoundtripTime | Add-Member -MemberType NoteProperty -Name "OriginalAddress" -Value $newIP -PassThru
                Unregister-Event -SourceIdentifier $EventSubscriber.SourceIdentifier
            } -EventName PingCompleted -InputObject $ping

            $ping.SendAsync($ip,$timeout, $ip);

        } #end Octet4

    }  #end Octet3

    $result = Receive-Job $jobs

    while($global:res.Count -lt $octet4.count)
    {
        #Start-Sleep -Milliseconds 500
        Write-Verbose  "Waiting for: $($global:res.Count) - Octet4.count: $($octet4.count)"
    }

$global:res

}



[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null

Ping-IPRange3 -FirstOctet 192 -SecondOctet 168 -ThirdOctet 100 -Verbose

#$form1                  = New-Object System.Windows.Forms.Form
$buttonSearchIP         = New-Object System.Windows.Forms.Button

Ping-IPRange3 -FirstOctet 192 -SecondOctet 168 -ThirdOctet 100 -Verbose

So if you want to test the script, you'll have to modify the 2 lines with Ping-IPRange3 with your own subnet.

If you copy/paste the script or save it to a file and run it the result would be the same.

So the issue is: the first Ping-IPRange3 works perfectly, but not the second one.

if $form1 and $buttonsearchIp lines are commented, everything works.
if any is commented out, the second Ping-IRange fails.

 I suppose there is a conflict between New-Object System.Windows.Form and Register-Object, that all I can think of !!!

Any help is welcome

PS: I have tries with the other function I found on the web, and the behavior is the same !

Trouble extracting data from data table

$
0
0

I'm new to powershell.

I create a data table:

$dt = New-Object System.Data.Datatable "sql_admins"

$dt.Columns.Add("sql_server")

$dt.Columns.Add("sql_db_name")

$dt.Columns.Add("sql_admin")

$dt.Columns.Add("sql_priv")

I load it with records (filtering out anything not CSV)

$dt = get-content C:\temp\SQL_admins_raw.txt | where {$_.contains(",")}

I check for data

$dt

FAHQSNA09SSQL38,CFT,NT SERVICE\SQLSERVERAGENT,sysadmin

FAHQSNA09SSQL38,CFT,sa,db_owner

SNACPSQLFAMS003,ELSWeb,CORP\FAHQ-GU-CCDBA,sysadmin

SNACPSQLFAMS003,ELSWeb,CORP\FAHQ-GU-SCM-DBA,sysadmin

SNACPSQLFAMS003,ELSWeb,CORP\FAHQ-SA-SCOMMSA,sysadmin

I extract the first row

$dt[0]

FASTSNA09CSQL01,FASTPROD,archiver,db_owner

I try to extract the first element of the first row

$dt[0]. sql_server

But nothing is returned

Where did I go wrong?

How do i trim '[' ???

$
0
0

I have no bloody clue:

PS C:\> $junk[1].Trimstart([char]0x005B)
 [Active     

PS C:\> $junk[1].Trimstart('/[')
 [Active     

PS C:\> $junk[1].Trimstart('[')
 [Active     

PS C:\> $junk[1].Trimstart([)
At line:1 char:21
+ $junk[1].Trimstart([)
+                     ~
Missing type name after '['.
At line:1 char:20
+ $junk[1].Trimstart([)
+                    ~
Missing ')' in method call.
At line:1 char:20
+ $junk[1].Trimstart([)
+                    ~
Unexpected token '[' in expression or statement.
At line:1 char:21
+ $junk[1].Trimstart([)
+                     ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingTypename
 

PS C:\> $junk[1].Trimstart("[")
 [Active     

PS C:\> $junk[1].Trimstart("/[")
 [Active     

PS C:\> 

Out-file with variable date problem

$
0
0
$date = Get-Date -UFormat "%x_%T"

Get-Content -Path 'C:\...(path of computer list)' |
Get-InstalledApp | Out-File ('C:\..(pathname)' + "$date" + '.txt')
The script is supposed to get a list of all the software installed on the computers from the text file and output it to another text file with the date. The problem I'm having is that Out-File keep spitting out an error that says the path's format is not supported. How do I have the output file's name include the date on which this script was run?

Starting this morning it takes 3-4 seconds to start even very simple PowerShell script on my machine

$
0
0

Starting this morning it takes 3-4 seconds to start even very simple PowerShell script on my machine. This command shows 3.2-3.4 seconds on my machine and only 0.4 second on co-worker's machine.

powershell ( Measure-Command { powershell "Write-Host 1" } ).TotalSeconds

I know there are thousands of possible reasons (including viruses!)... But I don't see any suspicious activity on my machine, and I've installed a bunch of Windows updates this morning, and it was the only significant change in my environment.

I'm wondering if anybody has the same problem.

Viewing all 21975 articles
Browse latest View live


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