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

Is it a string or not?

$
0
0

I'm a PS rookie; OK with .NET and VBA. There is something fundamental I don't understand about PS language.

1:
echo [environment]::GetFolderPath("MyDocuments")
[environment]::GetFolderPath
MyDocuments

2:
$thePath = [environment]::GetFolderPath("MyDocuments")
echo $thePath
C:\Users\Tom\Documents

Why does 1 not print the same path as 2?
Is it significant what it does print?


-Tom. Microsoft Access MVP


Not able to invoke-webrequest using task scheduler

$
0
0

Hi,

I am not able to download a content using task scheduler. URI is of following format :

-ExecutionPolicy Bypass -command & {Invoke-WebRequest -Uri "http://XX.XXX.XX.XXX:8080/Server.svc/Module(Config='abc',MN='xyz',MV='0')/ModuleContent"}


Whereas the same work with tinyurl and not with the above one. Is this bcz of comma(,) in URI. I also tried uri encoding, that also didn't help.

Invoke-webrequest works perfectly with long url if run on powershell console directly.

Why is this not working from task scheduler with this long url and runs with tiny url?

I even tried with $ProgressPreference = "silentlyContinue" in task scheduler by appending it in argument section.


-SSS

Replacing boot.wim in WDS using PowerShell

$
0
0

Hi, I created PowerShell script to remove and add boot.wim in remote servers. The script works fine if I run it in single server and it works fine if I use batch script to execute powershell in remote server but if I use default stuff of WDSUTIL or get-wdsbootimage command to execute on remote server it doesn't work.  I did following steps to find out reason.

 

  1. I have full administrator access on remote server
  2. I used powershell in administrator mode
  3. WinrRM service is runninng on remote server
  4. I tried to execute script using Enter-Pssession to try execute remotely
  5. Tried with WDSUTIL and WDS modeul command also
  6. Tried with Invoke-command

    Replacing boot.wim in WDS using PowerShell

    $
    0
    0

    Hi, I created PowerShell script to remove and add boot.wim in remote servers. The script works fine if I run it in single server and it works fine if I use batch script to execute powershell in remote server but if I use default stuff of WDSUTIL or get-wdsbootimage command to execute on remote server it doesn't work.  I did following steps to find out reason.

     

    1. I have full administrator access on remote server
    2. I used powershell in administrator mode
    3. WinrRM service is runninng on remote server
    4. I tried to execute script using Enter-Pssession to try execute remotely
    5. Tried with WDSUTIL and WDS modeul command also
    6. Tried with Invoke-command

      Read-host secure string

      $
      0
      0

      Hello,

           i would like to store a key typed in by user in registry as a secure string and decrypt is as a plain text again whenever i need to use it by retrieving from registry. How can i do it?

      Script to backup MySQL database failing

      $
      0
      0

      Hello Friends

      I have created this super simple script which should run daily to backup the MySQL database running my WordPress website.

      $root = 'C:\Backups\My Website\Database Dumps\'
      
      $dateString = (Get-Date).ToString("yyyy-MM-dd")
      
      $fileName = $dateString + "-MyWebsiteDbBackup.sql"
      
      $backupFilePath = ($root + $fileName)
      
      $command = ("mysqldump -u root wpdatabase > " + "`"$backupFilePath`"")
      
      Write-Host $command
      
      Invoke-Expression $command

      When I run the script inside PowerShell ISE, it runs fine and creates the .sql file, however, in Task Scheduler, the task is stuck on Running with code 0x00041301.

      Why is this happening? Any help would be greatly appreciated.

      Thank You


      Always Learning.

      Suppressing Error Message

      $
      0
      0

      I am running a simple command:

      Remove-ADGroupMember I would like to suppress an error message is account is not found in the group. I tried running-ErrorActionSilentlyContinue but not getting any luck?

      Thanks for the help.

      For each $row in $csv , for each $head in $row Theory

      $
      0
      0

      Hi all

      I am in the middle of creating a CSV import utility that searches the CSV import for invalid and special characters. I would like to check each row's column for specific characters. Once it has checked the row I want it to export the results to a csv appended. I know how to do this part.

      but I cannot specify how many columns there would be as I am creating a universal import tool.

      I am not sure how exactly to apply this.

      Do I need to do

      1. For Each ($row in $csv) {}

      followed by

      2. For Each ($heading in $row) {}

      or am I completely wrong?

      Please help.




      Shell has stopped working (Windows Multipoint Server 2012)

      $
      0
      0

      l am using Windows Multipoint Server 2012.

      During work it pops up a small window says (Shell has stopped working , A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available)

      then the computer freezes together with all LAN connected Atrust stations. Please help me, I need to know how can l fix that error.

      Is there an alternative to this ?

      $
      0
      0

      Hi All

      I have this piece of code, however its running really slow. I was wondering if there is an alternative to this piece of code.

      try
      {
      
      
      $ErrorActionPreference = "Stop"; #Make all errors terminating
      $CITbl = "[dbo].[databasedata]”
      $s = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $inst
      #$dbs=$s.Databases
      foreach ($db in $s.Databases) {
      if ($db.IsAccessible -eq $True) {
      $dt= $db | Select @{n="ServerName";e={$svr}}, @{n="InstanceName";e={$inst}}, Name, Status, Owner, CreateDate, Size,
      	@{n="DBSpaceAvailableInMB";e={[math]::round(($_.SpaceAvailable / 1024), 2)}},
      	@{e={"{0:N2}" -f ($_.Size-($_.SpaceAvailable / 1024))};n=”DBUsedSpaceInMB”},
      	@{e={"{0:P2}" -f (($_.SpaceAvailable / 1024)/$_.Size)};n=”DBPctFreeSpace”},
      	@{n="DBDataSpaceUsageInMB";e={[math]::round(($_.DataSpaceUsage / 1024), 2)}},
      	@{n="DBIndexSpaceUsageInMB";e={[math]::round(($_.IndexSpaceUsage / 1024), 2)}},
      	ActiveConnections, Collation, RecoveryModel, CompatibilityLevel, PrimaryFilePath,
      	LastBackupDate, LastDifferentialBackupDate, LastLogBackupDate, AutoShrink, AutoUpdateStatisticsEnabled,IsReadCommittedSnapshotOn,
      	IsFullTextEnabled, BrokerEnabled, ReadOnly, EncryptionEnabled, IsDatabaseSnapshot, ChangeTrackingEnabled,
      	IsMirroringEnabled, MirroringPartnerInstance, MirroringStatus, MirroringSafetyLevel, ReplicationOptions,  AvailabilityGroupName,
      	@{n="NoOfTbls";e={$_.Tables.Count}}, @{n="NoOfViews";e={$_.Views.Count}}, @{n="NoOfStoredProcs";e={$_.StoredProcedures.Count}},
      	@{n="NoOfUDFs";e={$_.UserDefinedFunctions.Count}}, @{n="NoOfLogFiles";e={$_.LogFiles.Count}}, @{n="NoOfFileGroups";e={$_.FileGroups.Count}},
      	@{n="NoOfUsers";e={$_.Users.Count}}, @{n="NoOfDBTriggers";e={$_.Triggers.Count}},
      	@{n="LastGoodDBCCChecKDB"; e={$($_.ExecuteWithResults("dbcc dbinfo() with tableresults").Tables[0] | where {$_.Field -eq "dbi_dbccLastKnownGood"}|  Select Value).Value}},
      	AutoClose,  HasFileInCloud, HasMemoryOptimizedObjects, MemoryAllocatedToMemoryOptimizedObjectsInKB, MemoryUsedByMemoryOptimizedObjectsInKB,
      	@{n="DateAdded";e={$RunDt}}  | out-datatable
      Write-DataTable -ServerInstance $SQLInst -Database $Centraldb -TableName $CITbl -Data $dt
      #write-log -Message "Database info collection Finished on  $svr at | $(get-date)" -NoConsoleOut  -Path $progress_log
      
      
      }}#end For Each
      write-log -Message "Database info collection finished on | $svr at | $(get-date)" -NoConsoleOut  -Path $progress_log
      
      }
      catch
      {
              $ex = $_.Exception
      
      }finally{
         $ErrorActionPreference = "Continue"; #Reset the error action pref to default
      
      }
      
      

      Powershell - hash /array values

      $
      0
      0

      I have 2 columns  of users - one has the employees and other one their managers. I need to email the list of employees working under each manager.How can I get just the users working for each manager?

      manager 1, emp1; manager 1, emp2; manager 2, emp3;...

      Automating IIS SSL Certificate Installation with PowerShell e VBSCRIPT

      $
      0
      0

      Hello guys!

      I am searching for a way to automate the installation process and renewal certiifcados WEB using vbscript in the case of Windows 2003 and Power shell in the case of versions of Windows Server later .

      I found some tips on the Internet , however , nothing very clear.

      Thank you in advance for your attention.


      Fabio Gomes STS,LPI,MCP,MCTS,MCSA,MCITP, MCSE,,MCT Veja meus artigos no TechNet Wiki Veja meus artigos no blog http://virtualizandoaju.wordpress.com/ "Você pode, se acredita que pode."


      Publish-Module throws "The specified name '$moduleName' is already used for a different item on the specified repository 'PSGallery'

      $
      0
      0

      I've already published with the Publish-Module many modules but suddenly I get this message only for PSGallery

      The specified name '$moduleName' is already used for a different item on the specified repository 'PSGallery'. Run 'Find-Script -Name

      $moduleName -Repository PSGallery' to check whether the specified name '$moduleName' is already taken.

      where $moduleName is the name of the module. The PowerShell I use is

      Publish-Module -Path $path -NuGetApiKey $key -Repository PSGallery -WhatIf

      Find-Module reports that $moduleName is indeed a module. On PowerShell gallery it presents the artificat as a module Same Publish-Module works for any other PSRepository.

      Any ideas anyone?

      Can't find anything on google and the message is not correct.

      Link from stackoverflow


      Extracting the last octet from local machines ip and applying to computer name

      $
      0
      0

      What I am trying to do is on startup have a script run (this is new server only) that looks at the IP assigned to the system (192.168.0.44) say .. then take the last octet (44) and add it too NEWSERVER to get newserver44 

      $octet = 

      Add-Computer -DomainName $domain -NewName "NEWSERVERXX" -Credential $credential -Force -Restart

      I have tried the . splt .. but can not get it to work

      Thanks

      Converting "System.Windows.Forms.TextBox to use with Remove-ADGroupMember

      $
      0
      0

      I am trying to write a GIU. Getting a user name from the text box and then trying to use it to remove from from ADGroup.

      But getting an error:

      Cannot bind parameter 'Members'. Cannot convert the "System.Windows.Forms.TextBox

      I understand that TextBox is passing a different format than Remove-ADGroupMember expects as a member.

      Do not know how to convert it.

      Thank you


      adding line to the .ps file to remove password and disable script ... (just read below)

      $
      0
      0

      Thanks to Mike L. for helping on the octet part!! 

      heres the run down 

      we have to create scaleable server, they will create and remove as needed.

      Problem is they are not on the domain and they have one set name .. so...

      I need to do the following things in a PS script that runs at start up on each machine

      1. Rename the computer and join to the domain (GOT THAT)
      2. After its done , edit the .ps file to remove the password or change it or something.
      3. add a line at the top of the code that has the date it ran and then a command to exit and not run anymore code (effectively making it a once run kinda thing)

      Just want it to run the one time on startup and then just sit there and future restarts, but I dont want to erase the file incase we need it to run again (for what ever reason)

      This is what i have so far

      $domain = "mydomain.com"
      $password = "thepassword" | ConvertTo-SecureString -asPlainText -Force
      $username = "$domain\aduser" 
      $credential = New-Object System.Management.Automation.PSCredential($username,$password)
      $ip = (Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=True').IPAddress[0]
      $lastOctet = $ip.Split('.')[-1]
      Add-Computer -DomainName $domain -NewName "NEWSERVER$lastoctet" -Credential $credential -Force -Restart

      Thanks in advance!

      Importing new users with .csv file

      $
      0
      0

      I'm having issues importing this csv file.  Here the headings of what has been given to me in the csv file.  

      GIVENNAMESNDisplayNameOfficeDESCRIPTIONUserPrincipalNameSamAccountNameParentContainerPasswordEmailLogin ScriptConnect To

      I tried doing on by one powershell with New-ADUser and I can't seem to get that working either.  This is what I got.  


      New-ADUser -name "Lastname, Firstname" -GIVENNAME firstname -SURNAME lastname -DISPLAYNAME "Lastname, Firstname" -OFFICE 111111 -DESCRIPTION "Class of 2025" -USERPRINCIPALNAME username@email.com -SAMACCOUNTNAME flastname -PATH"OU=orgunitsample,DC=domain,DC=org" -ACCOUNTPASSWORD (ConvertTo-SecureString passwordhere -AsPlainText -Force) -EMAILADDRESS username@email.com  -SCRIPTPATH login.bat -HOMEDIRECTORY \\servername\share\username-ENABLED $true -HOMEDRIVE x: -CANNOTCHANGEPASSWORD $true -CHANGEPASSWORDATLOGON $false -PASSWORDNEVEREXPIRES $true

      New-ADUser : Directory object not found
      At line:1 char:1
      + New-ADUser -name "lastname, firstname" -GIVENNAME Firstname SURNAME Lastname
      -DIS ...
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      ~~~
          + CategoryInfo          : ObjectNotFound: (CN=username\, ...C=domain,DC=o
         rg:String) [New-ADUser], ADIdentityNotFoundException
          + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.
         Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Managemen
        t.Commands.NewADUser

      Pasting data from clipboard to the excel sheet cell.

      $
      0
      0

      I have a powershell script in which I am inserting some text in the clipboard and then from the clipboard to a excel sheet cell.

      I am getting the workbook from here:

      $workbook = $xldoc.Workbooks.Open($testType)

      and the $currentSheet which is send in the below function is initialized by :

      $mysheet = $workbook.worksheets | where {$_.name -eq "JPT"}

      Now this $mysheet is send in the function addTitle as $currentSheet

      The function used for this is:

      Function addTitle($currentRow , $maxRow , $currentSheet ,$currentCol, $currentCode){
      
                               $i =1
                               $intRow = $currentRow
                               $cSheetName = $currentSheet.Name
      
                               $finCode=""
      
                               $fRow=$intRowfor($intRow = $fRow ; $intRow -le $maxRow ; $intRow++){
      
                                  $codeName = $currentCode
                                  $fin = $codeName +"_"+ $i +"`n"
                                  $finCode=$finCode+$fin
      
      
                                  $i= $i +1}
      
      
      
      
                               $clipboardData = $finCode#$newClipboardData = $clipboardData.Where({$_.TrimStart() -ne ""}).ForEach({$_.TrimStart()})[System.Windows.Forms.Clipboard]::SetText($ClipboardData)[System.Windows.Forms.Clipboard]::GetText()
      
                               $currentSheet.Cells.Item($fRow,$currentCol).Value2=[System.Windows.Forms.Clipboard]::GetText()
      
                               $currentSheet.Cells.Item($fRow,$currentCol).Select()|Out-Null
      
                               $currentSheet.Paste($finCode)|Out-Null}

      The error I am getting is:

      You cannot call a method on a null-valued expression.At D:\UploadsNew\DataGenerator.ps1:239 char:26+                          $currentSheet.Cells.Item($fRow,$currentCol).Select()|...+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+CategoryInfo:InvalidOperation:(:)[],RuntimeException+FullyQualifiedErrorId:InvokeMethodOnNull

      Unable to Stop-Process on Remote Computer

      $
      0
      0

      Hi,

      I am learning PowerShell and want to use Invoke-Command to stop a process on remote computer.  I am getting below error.

      Any idea why I am getting below exception? 

      C:\>  Invoke-Command -ComputerName C123456 -ScriptBlock { Stop-Process $Agent -Force }
      [C123456] Connecting to remote server C123456 failed with the following error message : WinRM cannot complete the operation. Verify
      that the specified computer name is valid, that the computer is accessible over the network, and that a firewall exception for the
      WinRM service is enabled and allows access from this computer. By default, the WinRM firewall exception for public profiles limits
      access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
          + CategoryInfo          : OpenError: (C123456:String) [], PSRemotingTransportException
          + FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionStateBroken

      code will only run in ISE

      $
      0
      0

      I am writing a script that compares 2 text files that runs without a hitch in ISE but when I try to run the script from the command line as

      powershell.exe -executionpolicy bypass -file C:\scripts\myscript.ps1

      I get the error "Cannot bind argument to parameter 'Pattern' because it is an empty string.  At C:\scripts\myscript.ps1 : 10 char:64 + $ event51 = Get-Content 'c:\scripts\file02.txt | Select-String $event41 -SimpleM....  

      +CategoreyInfo   :InvalidData (:) [select-string], ParameterBindingValidationException + FullyQualifiedErrorID : ParamaeterArgumentValidationEmptyStringNotAllowed,Microsoft.Powershell.Commands.SelectStringCommand

      I cannot figure out what is causing this error since it runs fine in ISE.  Here is my script

      Clear-Content c:\scripts\file02.txt
      Clear-Content c:\scripts\file03.txt
      $event10 = get-winevent -filterhashtable @{logname='ForwardedEvents'; id=4688} 
      $event10 | format-list >> C:\scripts\file02.txt 
      $event11 = get-content -path C:\scripts\file02.txt | where-object {$_ -like '*new process name*'} | ForEach-Object {$_ -replace "New Process Name: ", ""}
      $event21 = $event11.trim()
      $event31 = $event21 | sort -u 
      $event31 >> c:\scripts\file03.txt 

      $event41 = compare-object -ReferenceObject (get-content -path c:\scripts\file01.txt) -DifferenceObject (Get-Content -Path c:\scripts\file03.txt) | Where-object {$_.SideIndicator -ne '<='} | select-object -expandproperty inputobject

      $event51 = Get-Content 'c:\scripts\file02.txt' | Select-String $event41 -SimpleMatch -Context 19,5

      Viewing all 21975 articles
      Browse latest View live